videobook 0.2.1 → 0.2.3

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +7 -8
  3. package/dist/book-manager.js +40 -2
  4. package/dist/chat-router.js +1 -1
  5. package/dist/env-secrets.js +1 -0
  6. package/dist/guides/seedance_2_prompting_guide.md +1 -1
  7. package/dist/image-edit-models.js +2 -0
  8. package/dist/jobs/generate-media.js +18 -6
  9. package/dist/jobs/run-notebook.js +23 -4
  10. package/dist/media/adapters/fal.js +7 -0
  11. package/dist/media/catalog.js +17 -2
  12. package/dist/media/cost.js +80 -7
  13. package/dist/media/json-schema.js +7 -0
  14. package/dist/media/ref-fields.js +11 -3
  15. package/dist/media/refs.js +13 -0
  16. package/dist/media/request.js +56 -0
  17. package/dist/media/seedance-edit.js +9 -0
  18. package/dist/provider-usage.js +22 -8
  19. package/dist/tools/estimate-cost.js +8 -5
  20. package/dist/tools/generate-media.js +2 -1
  21. package/dist/tools/provider-key-status.js +2 -0
  22. package/dist/tools/reconcile-project-work.js +2 -1
  23. package/package.json +13 -13
  24. package/ui/assets/{alive-captions-e-n3xmCd.js → alive-captions-4QySEGdt.js} +1 -1
  25. package/ui/assets/confirm-bodies-Bw818V9J.js +1 -0
  26. package/ui/assets/{fullscreen-VY7f4mJ-.js → fullscreen-CzTnPPG5.js} +1 -1
  27. package/ui/assets/{goal-ui-B__NgZYz.js → goal-ui-CosrK_ko.js} +2 -2
  28. package/ui/assets/index-C9xjFEGL.js +37 -0
  29. package/ui/assets/{inspector-BBuZIaqg.js → inspector-BN2fezh4.js} +1 -1
  30. package/ui/assets/{jobs-ui-vmEH4zBT.js → jobs-ui-C4Wgy6I1.js} +1 -1
  31. package/ui/assets/{music-video-CklLKD1R.js → music-video-BSj8SgbQ.js} +1 -1
  32. package/ui/assets/ui-Cpr6zMTA.js +2 -0
  33. package/ui/assets/{vendor-flow-DY81i6dC.js → vendor-flow-zBavaNEW.js} +1 -1
  34. package/ui/assets/{vendor-mcp-BsGNAD4I.js → vendor-mcp-DQ7EusT9.js} +1 -1
  35. package/ui/assets/vendor-yctIZ9Dz.js +19 -0
  36. package/ui/assets/videobook-B5G0jMoi.js +20 -0
  37. package/ui/index.html +11 -11
  38. package/ui/assets/confirm-bodies-DS6jh0Kb.js +0 -1
  39. package/ui/assets/index-BPco0HoT.js +0 -37
  40. package/ui/assets/ui-CtYXY_po.js +0 -2
  41. package/ui/assets/vendor-OClqq_Da.js +0 -19
  42. package/ui/assets/videobook-lhLK6e6Q.js +0 -20
@@ -0,0 +1,20 @@
1
+ import{c as ne,a as _,j as Be}from"./vendor-react-Dj7D1fD4.js";import{n as yt,a as Fs,t as Ft,T as Wr,b as ue,N as de,d as X,e as Qt,f as ve,S as Ds,i as Kr,g as Vs,s as to,h as js,j as We,k as $n,l as Gs,m as Ee,o as qs,p as To,q as Nn,r as Us,u as zr,M as Bs,v as Xr,w as Le,x as Yr,y as Dt,z as Hs,A as Ws,B as Jr,C as qt,D as Ks}from"./vendor-yctIZ9Dz.js";import{o as te,n as V,a as ae,s as j,_ as Xe,l as Zr,b as Te,C as zs,S as Xs}from"./vendor-mcp-DQ7EusT9.js";import{l as Ys,u as Js,a as Zs}from"./vendor-remotion-CH1HXrlc.js";const Db=["x","instagram","tiktok","youtube","other"],Vb=["views","impressions","likes","replies","reposts","quotes","bookmarks","shares","clicks"];function Qs(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"book"}function Qr(e,t,n){return`${Qs(e)}/post-${t.replace(/^@/u,"")}-${n.slice(-6)}`}function ea(e){const t=e.trim().replace(/\/+$/u,"");return t?t.startsWith("/")||t.startsWith("~")?"Use a folder inside iCloud Drive › Videobook, like my-book/post-a1.":[...t].some(n=>n.charCodeAt(0)<32||n.charCodeAt(0)===127)?"Use an iCloud folder without control characters.":t.split("/").some(n=>n===".."||n==="."||n==="")?"Use an iCloud folder without empty, . or .. segments.":null:"Choose an iCloud folder."}const ta="16:9",na="2K",oa="jpg",jb=25,ra="16:9",ia="1080p",sa=13,aa="mp4",ca=!0,Gb=60,la={resolution:ia,aspect_ratio:ra,duration:sa,output_format:aa,generate_audio:ca},ua={aspect_ratio:ta,resolution:na,output_format:oa},da=3,fa=2.3,ma=.3,pa="th",ga=["fyp","bkk"],ha={profileUrl:"https://www.tiktok.com/@jtbkk",includePlatformIcon:!0,includeHandleBorder:!0,handlePaddingX:15,handlePaddingY:12,handleRounding:56,handlePlacement:"center",handleVerticalPercent:10,handleStartSeconds:0,handleEndSeconds:da,handleOpacity:.28,qrLeadSeconds:fa,qrOpacity:.37,fadeSeconds:ma};function ba(e,t){const n=Number.isFinite(t)?Math.max(0,t):0,o=Math.min(n,Math.max(0,e.handleStartSeconds)),r=Math.min(n,Math.max(o,e.handleEndSeconds)),i=n,s=e.qrLeadSeconds,a=Math.max(0,n-Math.min(n,Math.max(0,s)));return{handleStartSeconds:o,handleEndSeconds:r,qrStartSeconds:a,qrEndSeconds:i}}const qb=["en","th"],ya={en:"English",th:"Thai"},_a={x:280,instagram:2200,tiktok:2200,youtube:5e3,other:2200},ei={x:2,instagram:10,tiktok:5,youtube:15,other:8},no={x:"X",instagram:"Instagram",tiktok:"TikTok",youtube:"YouTube Shorts",other:"Other"},va=/^#[\p{L}\p{M}\p{N}_]+$/u;function ka(e){return e.trim().replace(/^#+/u,"").replace(/[^\p{L}\p{M}\p{N}_]/gu,"")}function en(e,t=Number.POSITIVE_INFINITY){const n=new Set,o=[];for(const r of e){const i=ka(r),s=i.toLocaleLowerCase();if(!(!i||n.has(s))&&(n.add(s),o.push(i),o.length>=t))break}return o}function wa(e){const t=e.trim().split(/\s+/u);return t.length>0&&t.every(n=>va.test(n))}function Sa(e){const n=e.trimEnd().split(`
2
+ `),o=n[n.length-1]??"";return!o.trim()||!wa(o)?{body:e,tags:[]}:{body:n.slice(0,-1).join(`
3
+ `).trimEnd(),tags:en(o.trim().split(/\s+/u))}}function Ia(e,t){const n=en(t).map(r=>`#${r}`).join(" "),o=e.trimEnd();return n?o?`${o}
4
+
5
+ ${n}`:n:o}const Ub=[{id:"x",label:"X"},{id:"tiktok",label:"TikTok"},{id:"instagram",label:"Instagram"},{id:"youtube",label:"YT Shorts"},{id:"other",label:"Other"}],Bb=["Longer caption","Punchier","More emoji","Fewer tags","Add a call to action"],xa=/[฀-๿]/u;function Aa(e){return xa.test(e)?"th":"en"}function Hb(e){const t=e.definition.caption,n=e.definition.platform==="tiktok"&&!t.trim(),o=n?pa:Aa(t),r=Sa(t),i=t.trim()?{[o]:{versions:[{body:r.body,tags:r.tags,origin:"saved",instruction:null}],index:0}}:n?{th:{versions:[{body:"",tags:[...ga],origin:"auto",instruction:null}],index:0}}:{};return{language:o,platform:e.definition.platform,tracks:i,prompt:"",drafting:null,error:null}}function et(e){const t=e.tracks[e.language];return t?.versions[t.index]??null}function Ut(e){const t=et(e);return t?Ia(t.body,t.tags):""}function Ea(e,t){const n=e.tracks[e.language],o=n?{...n,versions:n.versions.map((r,i)=>i===n.index?t:r)}:{versions:[t],index:0};return{...e,tracks:{...e.tracks,[e.language]:o}}}function ti(e,t){const n=et(e)??{body:"",tags:[],origin:"edited",instruction:null};return Ea(e,{...n,...t,origin:"edited"})}function Wb(e,t){const n=et(e)?.tags??[],o=en([...n,...t.split(/[\s,]+/u)]);return o.length===n.length?e:ti(e,{tags:o})}function Kb(e,t){const n=et(e)?.tags??[];return ti(e,{tags:n.filter(o=>o!==t)})}function zb(e,t,n,o){const r=e.tracks[t]??{versions:[]},i={body:n.caption,tags:n.tags,origin:o?"astra":"auto",instruction:o},s=[...r.versions,i];return{...e,language:t,tracks:{...e.tracks,[t]:{versions:s,index:s.length-1}},drafting:null,error:null}}function Xb(e,t){const n=e.tracks[e.language];if(!n)return e;const o=Math.min(n.versions.length-1,Math.max(0,n.index+t));return{...e,tracks:{...e.tracks,[e.language]:{...n,index:o}}}}function Yb(e,t,n){const o=e.tracks[t],r=o?.versions[o.index]?.body.trim()??"";return!n&&!e.drafting&&r.length===0}function Jb(e,t,n,o,r){const i=n.tracks[o],s=i?.versions[i.index];return{book_id:e,post_cell_id:t,language:o,platform:n.platform,...r?{instruction:r}:{},...r&&s?{caption:s.body,tags:s.tags}:{}}}function Zb(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=typeof t.caption=="string"?t.caption.trim():"";if(!n)throw new Error("Astra returned an empty caption.");const o=Array.isArray(t.tags)?t.tags.filter(r=>typeof r=="string"):[];return{caption:n,tags:en(o)}}function Qb(e){const t=et(e),n=ya[e.language];return t?t.origin==="saved"?"Saved caption":t.origin==="edited"?"Edited by you · Regen keeps this version in history":t.origin==="astra"?`Rewritten by Astra · “${t.instruction??""}”`:t.body.trim()?`Drafted by Astra from the video analysis · ${n}`:`No ${n} caption yet`:`No ${n} caption yet`}function Ca(e){const t=Ut(e).length,n=_a[e.platform],o=et(e)?.tags.length??0;return{length:t,limit:n,over:t>n,tooManyTags:o>ei[e.platform]}}function Ma(e){const t=Ca(e),n=no[e.platform];return t.over?`Over ${n}'s ${t.limit.toLocaleString()}-character limit. Shorten it or regen with Astra.`:t.tooManyTags?`${n} works best with ${ei[e.platform]} tags or fewer.`:null}const Ta=new Set(["posting","needs_reconciliation","scheduled"]),Ro=25e3,Ra="iCloud Drive isn't available on this Mac.";function $a(e,t,n){const o=n.replace(/^@/u,"").toLowerCase();return e.id.toLowerCase()===o||e.address.replace(/^@/u,"").toLowerCase()===o?!0:[t.find(s=>s.id===e.id)?.outputArtifactId,e.definition.source?.snapshotArtifactId,e.runtime.outbound?.artifactId].some(s=>s?.toLowerCase()===o)}function ey(e,t,n,o){const r=n?.trim();return r?e.find(i=>$a(i,t,r))??null:e.find(i=>i.id===o)??null}const Na=new Set(["image","video","generate_image","generate_video","concat","splice","split_video"]);function ty(e,t){const n=t.trim().replace(/^@/u,"").toLowerCase();return e.find(o=>o.type!=="post"&&!!o.outputArtifactId&&Na.has(o.type)&&[o.id,o.outputArtifactId,yt(o.slot)].some(r=>r?.toLowerCase()===n))??null}function ny(e,t){return e.filter(n=>n.definition.source?.cellId===t).reduce((n,o)=>!n||o.definition.createdAt>n.definition.createdAt?o:n,null)}function oy(e,t){return e.runtime.icloud?.folder??Qr(t,e.address,e.id)}function ry(e,t){return e.runtime.dropbox?.folder?e.runtime.dropbox.folder:`/Videobook/${Qr(t,e.address,e.id)}`}function Pa(e,t){return e==="dropbox"||t&&!t.available?"dropbox":"icloud"}function iy(e,t){return{...e,icloud:t,destination:e.pinnedDestination?e.destination:Pa(e.entry,t)}}function tn(e){return!!e.runtime.outbound}function Oa(e){const t=e.trim();return t?t.startsWith("/")?t.split("/").includes("..")||[...t].some(n=>n.charCodeAt(0)<32)?"Use a Dropbox folder without .. segments or control characters.":null:"Start the Dropbox folder with /, like /Videobook/clips.":"Choose a Dropbox folder."}function La(e,t){return t?"Finish connecting Dropbox in the other tab.":e?e.connected?null:e.hasCredentials?"Connect Dropbox to upload.":"Dropbox delivery is not configured. Set DROPBOX_CLIENT_ID on the server.":"Checking the Dropbox connection…"}function Fa(e,t){return e?e.definition.source?.snapshotArtifactId?Ta.has(e.runtime.status)?`Resolve or cancel ${e.address}'s current publication first.`:t.length>Ro?`Shorten the caption to ${Ro.toLocaleString()} characters.`:null:`${e.address} has no saved source clip. Choose one in the Post panel.`:"This Post is no longer on the canvas."}function sy(e){return e?.available?e.shared===!0?"Shared with your iPhones":e.shared===!1?"Share iCloud Drive › Videobook with your phones first":null:null}function Da(e,t){return!e||tn(e)?null:t.copy.drafting?"Astra is writing the caption…":null}function $o(e,t){return e&&!tn(e)?Ma(t.copy):null}function ay(e,t){const n=Fa(e,Ut(t.copy))??Da(e,t);if(t.destination==="dropbox"){const i=n??Oa(t.dropboxFolder)??La(t.connection,t.connecting),s=e?.runtime.dropbox&&!e.runtime.dropbox.completedAt&&e.runtime.dropbox.folder===t.dropboxFolder.trim()?"A previous upload to this folder stopped early. Uploading resumes where it left off.":$o(e,t);return{blocking:i,notice:i?null:s}}const o=t.icloud?t.icloud.available?null:t.icloud.reason??Ra:"Checking iCloud Drive…",r=n??o??ea(t.icloudFolder);return{blocking:r,notice:r?null:$o(e,t)}}function cy(e,t){const n=(t.destination==="icloud"?t.icloudFolder:t.dropboxFolder).trim().replace(/\/+$/u,"");return{book_id:t.bookId,post_cell_id:e.id,folder:n,...!tn(e)&&Ut(t.copy)!==e.definition.caption?{caption:Ut(t.copy)}:{}}}function ly(e,t){return tn(e)||t.copy.platform===e.definition.platform?null:{book_id:t.bookId,post_cell_id:e.id,platform:t.copy.platform}}function uy(e){return e==="icloud"?"save_post_to_icloud":"upload_post_to_dropbox"}function Va(e){const t=[];return e.runtime.icloud?.completedAt&&t.push("iPhone"),e.runtime.dropbox?.completedAt&&t.push("Dropbox"),t}function ni(e){return!e.runtime.url&&Va(e).length>0}function dy(e){const t=e.definition.platform;return t==="other"?"Posted it? Paste the link":`Posted on ${no[t]}? Paste the link`}function ja(e){return no[e.definition.platform]}function fy(e){return ni(e)?"needs_link":e.runtime.status}function my(e){return e.runtime.postedAt||e.runtime.url?null:ni(e)?e.definition.platform==="other"?"Paste the published link":`Paste ${ja(e)} link`:"Save to iPhone next"}function py(e){return e.runtime.postedAt?new Date(e.runtime.postedAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}):null}function gy(e){const t=e.runtime.metrics.at(-1)?.values;return t?[t.views!=null?"views":"impressions","likes"].filter(o=>t[o]!=null).map(o=>({label:o,value:Ga(t[o])})):[]}function Ga(e){return new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(e)}function hy(e){return`On iPhone · iCloud Drive › Videobook › ${e}`}function by(e,t){if(t==="icloud"){const o=e.runtime.icloud?.folder;return o?`Saved ${e.address} to iCloud · Videobook/${o}`:`Saved ${e.address} to iCloud`}const n=e.runtime.dropbox?.folder;return n?`Uploaded ${e.address} to Dropbox · ${n}`:`Uploaded ${e.address} to Dropbox`}function yy(e,t){return e==="uploading"?"Uploading to iCloud…":e==="uploaded"?"On iCloud":e==="error"?t?.trim()||"iCloud upload failed":null}function qa(e){return e===null||e==="uploading"}function Ua(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=t.phase;return{phase:n==="uploaded"||n==="uploading"||n==="error"||n==="not-icloud"?n:"not-icloud",error:typeof t.error=="string"&&t.error?t.error:null}}function oo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}async function No(e){const t=oo(await e("service_status",{service:"dropbox"}));return{connected:t.connected===!0,pending:t.pending===!0,hasCredentials:t.has_credentials!==!1,error:typeof t.error=="string"&&t.error?t.error:null}}async function _y(e){const t=oo(await e("service_status",{service:"icloud"})),n=t.role==="owner"||t.role==="participant"?t.role:null;return{available:t.available===!0,root:typeof t.root=="string"?t.root:"",shared:typeof t.shared=="boolean"?t.shared:null,role:n,reason:typeof t.reason=="string"&&t.reason?t.reason:null}}async function vy(e){const t=oo(await e("connect_service",{service:"dropbox"}));if(typeof t.authorize_url!="string")throw new Error("Dropbox did not return an authorization link.");return t.authorize_url}async function ky(e,t,n){let o=await No(e);for(let r=0;r<90&&o.pending&&!o.connected&&n();r+=1)await t(2e3),o=await No(e);return o}const Ba=3e3,Ha=12e4;function wy(e,t,n,o,r){const i=ne.c(9),s=_.useRef(r);let a,c;i[0]!==r?(a=()=>{s.current=r},c=[r],i[0]=r,i[1]=a,i[2]=c):(a=i[1],c=i[2]),_.useEffect(a,c);let l,u;i[3]!==n||i[4]!==t||i[5]!==e||i[6]!==o?(l=()=>{if(!e||!t||!n||!o)return;let m=!1;const d=Date.now()+Ha,f=async()=>{if(!(m||Date.now()>d))try{const p=Ua(await t("post_icloud_sync_status",{book_id:n,post_cell_id:o},{background:!0}));if(m)return;s.current(p),qa(p.phase)||(m=!0)}catch(p){const y=p;if(m)return;m=!0,s.current({phase:"error",error:y instanceof Error?y.message:"iCloud upload failed"})}};f();const g=window.setInterval(()=>{if(m||Date.now()>d){window.clearInterval(g);return}f()},Ba);return()=>{m=!0,window.clearInterval(g)}},u=[e,t,n,o],i[3]=n,i[4]=t,i[5]=e,i[6]=o,i[7]=l,i[8]=u):(l=i[7],u=i[8]),_.useEffect(l,u)}function Sy(e,t,n){const[o,r]=_.useState(!1),[i,s]=_.useState(null);return{busy:o,error:i,run:async(c,l={})=>{if(!e||o)return!1;r(!0),s(null);try{return await e(c,{book_id:t,...l}),await n(),!0}catch(u){return s(u instanceof Error?u.message:String(u)),!1}finally{r(!1)}}}}const _t=280,Po=25,Pn=4,Wa=5e3,Ka=3600*1e3,Oo=300*1e3;function za(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];const n=t,o=n.image_asset_ids,r=Array.isArray(o),i=r?o.filter(c=>typeof c=="string"):[],s=typeof n.text=="string",a=s?n.text:"";return s||r?[{text:a,imageAssetIds:i}]:[]}):[]}function Iy(e){const t=Object.hasOwn(e,"scheduled_for")?typeof e.scheduled_for=="string"?e.scheduled_for:"":null,n=e.orientation==="portrait"||e.orientation==="landscape"?e.orientation:null;return{postText:typeof e.text=="string"?e.text:"",scheduledFor:t,orientation:n,followups:za(e.followups)}}function xy(e,t){const n={...e};return t.postText!==void 0&&(t.postText?n.text=t.postText:delete n.text),t.scheduledFor!==void 0&&(t.scheduledFor===null?delete n.scheduled_for:n.scheduled_for=t.scheduledFor),t.orientation!==void 0&&(t.orientation===null?delete n.orientation:n.orientation=t.orientation),n}function Ay(e,t){const n={...e};return t.length===0?(delete n.followups,n):(n.followups=t.map(o=>({text:o.text,...o.imageAssetIds.length>0?{image_asset_ids:o.imageAssetIds}:{}})),n)}const Xa="Add a title for the post.";function Ya(e,t=Date.now(),n=_t){if(e.postText.trim()==="")return Xa;if(e.postText.length>n){const r=e.postText.length-n;return`Title is ${r} character${r===1?"":"s"} too long.`}if(e.followups.length>Po)return`Thread has ${e.followups.length} replies; X posts support at most ${Po} here.`;for(const[r,i]of e.followups.entries()){if(!i.text&&i.imageAssetIds.length===0)return`Follow-up ${r+1} needs text or an image.`;if(i.text.length>n){const s=i.text.length-n;return`Follow-up ${r+1} is ${s} character${s===1?"":"s"} too long.`}if(i.imageAssetIds.length>Pn)return`Follow-up ${r+1} has more than ${Pn} images.`}if(e.scheduledFor===null)return null;const o=Date.parse(e.scheduledFor);return!e.scheduledFor||Number.isNaN(o)?"Choose a valid date and time.":o-t<=Wa?"Scheduled time must be in the future.":null}function Ey(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const n=o=>o.toString().padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function Cy(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toISOString()}function My(e=Date.now()){const t=e+Ka,n=Math.ceil(t/Oo)*Oo;return new Date(n).toISOString()}function Ja(e){return e==="fal:minimax/h3-max/insert-video"||e==="minimax/h3-max/insert-video"}function Za(e,t){const n=typeof e.start_time=="string"&&e.start_time.trim()?Number(e.start_time):e.start_time,o=typeof e.resume_time=="string"&&e.resume_time.trim()?Number(e.resume_time):e.resume_time;if(typeof n!="number"||typeof o!="number"||!Number.isFinite(n)||!Number.isFinite(o))return null;if(t!=null&&t>0){const r=Number(t.toFixed(3));if(n>=t)return`Replace from must be before the source video ends at ${r}s (currently ${n}s).`;if(o>t)return`Resume original must be within the ${r}s source video (currently ${o}s).`}return o<=n?"Resume original must be after Replace from. Both times refer to the original video.":null}function Qa(e){return e.find(t=>t.targetInput==="video")??e.find(t=>t.type==="video"||t.type==="final")}function Ty(e,t,n){if(!Ja(e))return null;const o=Qa(n);if(!o)return"Connect the original video to choose the section to replace.";const r=o.asset?.duration;return!r||!Number.isFinite(r)?"The original video duration is unavailable. Wait for the source to finish processing.":Za(t,r)}const ec=["x","tiktok"],Ry={x:"X",tiktok:"TikTok"},$y={x:"M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z",tiktok:"M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z"};function Ny(e,t="x"){return t==="tiktok"?`https://www.tiktok.com/@${e}`:`https://x.com/${e}`}function tc(e){return e==="x"||e==="tiktok"}function oi(e,t,n){return![e,t,n].every(Number.isFinite)||n<.5?"Choose a playable video at least 0.5 seconds long.":e<0||t>n||t-e<.5-1e-6?"Choose a highlight at least 0.5 seconds long within the video.":null}const nc=new Set(["generate_audio","generate_image","generate_video"]),ri=["audio","image","video"],oc=new Set([...ri,"character"]),rc=new Set(ri),ic={analysis:"data",analyze:"data",audio:"audio",character:"data",concat:"video",extract_audio:"audio",generate_audio:"gen",generate_image:"gen",generate_video:"gen",goal:"goal",image:"image",post:"data",prompt:"gen",splice:"video",timeline:"data",split_video:"video",video:"video"};function ii(e){return ic[e]}function vt(e){return nc.has(e)}function ro(e){return oc.has(e)}function sc(e){return rc.has(e)}function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function x(e){return typeof e=="string"&&e.trim().length>0?e:null}function W(e){return typeof e=="string"&&e.length>0?e:null}function b(e){return typeof e=="string"?e:null}function F(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const ac=[["3:1",3],["21:9",21/9],["2:1",2],["16:9",16/9],["3:2",3/2],["4:3",4/3],["5:4",5/4],["1:1",1],["4:5",4/5],["3:4",3/4],["2:3",2/3],["9:16",9/16],["1:2",1/2],["9:21",9/21],["1:3",1/3]],cc=new Set(["analyzing","archiving","awaiting-output","changing-speed","completing","cropping","deleting","downloading","generating","isolating","loading","processing","queued","render-queued","render-queued-landscape","render-queued-portrait","render-queued-square","rendering","rendering-landscape","rendering-portrait","rendering-square","replacing-audio","reversing","running","splicing","transcribing","trimming","uploading"]),lc={analyze:"Analyze",concat:"Concatenate",extract_audio:"Extract",generate_audio:"Generate",generate_image:"Generate",generate_video:"Generate",prompt:"Rewrite",splice:"Splice",split_video:"Split"};function st(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function mn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function uc(e){return e.type!=="analysis"&&!ro(e.type)&&!!(e.operation??e.tool??e.model)}function nn(e){return cc.has(e)}function dc(e,t){return e==="analyzing"?"ANALYZING":e==="archiving"?"ARCHIVING":e==="changing-speed"?"CHANGING SPEED":e==="queued"?"QUEUED":e==="completing"?"FINISHING":e==="cropping"?"CROPPING":e==="deleting"?"DELETING":e==="downloading"?"DOWNLOADING":e==="generating"?"GENERATING":e==="isolating"?"ISOLATING VOCALS":e==="loading"?"LOADING":e==="processing"?"PROCESSING":e.startsWith("render-queued")?"QUEUED TO RENDER":e.startsWith("rendering")?"RENDERING":e==="replacing-audio"?"REPLACING AUDIO":e==="reversing"?"REVERSING":e==="splicing"?"SPLICING":e==="transcribing"?"TRANSCRIBING":e==="trimming"?"TRIMMING":e==="uploading"?"UPLOADING":e==="awaiting-output"||t.startsWith("generate_")?"GENERATING":t==="analyze"?"ANALYZING":t.startsWith("extract_")?"EXTRACTING":t==="split_video"?"SPLITTING":t==="splice"?"SPLICING":t==="concat"?"CONCATENATING":t==="prompt"?"REWRITING":"RUNNING"}const Py=3,fc={1:"QUEUED",2:"PROVIDER GENERATING",3:"DOWNLOAD & COMMIT"};function mc(e){return e==="queued"?1:e==="running"||e==="generating"||e==="awaiting-output"?2:e==="downloading"||e==="completing"?3:null}function Oy(e){const t=mc(e);return t===null?null:{step:t,label:fc[t]}}function pc(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string"||e.length===0)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function Ly(e,t,n){return t==="error"?{overlay:"failed",label:null,startedAt:null,error:n?.error??(ro(e)?"Media processing failed":"Generation failed"),tone:"error"}:nn(t)?{overlay:"clock",label:dc(t,e),startedAt:pc(n?.startedAt),error:null,tone:t==="queued"?"queued":"active"}:{overlay:null,label:null,startedAt:null,error:null,tone:null}}function Fy(e,t){const n=h(e.execution),o=n&&h(n[t]);return{error:W(o?.error),status:W(o?.status)}}function gc(e,t,n){const o=h(e.execution),r=o&&h(o[t]);if(!r||W(r.runId)!==n)return{error:null,state:"pending",status:null};const i=W(r.status),s=W(r.error);return s||i==="error"?{error:s,state:"error",status:i}:i==="completed"?{error:null,state:"completed",status:i}:{error:null,state:i&&nn(i)?"active":"pending",status:i}}function Dy(e,t){if(!uc(e))return null;const n=nn(t);return vt(e.type)?{disabled:n,label:"Gen"}:{disabled:n,label:e.outputArtifactId||t==="completed"||t==="error"?"Re-run":"Run"}}function Vy(e,t){const n=lc[e];return n?t==="Re-run"?`${n} again`:n:t}function jy(e,t){return ro(e)?null:t}function me(e){const t=Math.round(Math.max(0,e)*100),n=Math.floor(t/6e3),o=t-n*6e3,r=Math.floor(o/100),i=o%100,s=String(r).padStart(2,"0");return i===0?`${n}:${s}`:`${n}:${s}.${String(i).padStart(2,"0")}`}function hc(e,t){let n=Math.abs(Math.round(e)),o=Math.abs(Math.round(t));for(;o>0;){const r=n%o;n=o,o=r}return n}function on(e,t){if(e===null||t===null||!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0)return null;const n=e/t,o=ac.reduce((a,c)=>Math.abs(c[1]-n)<Math.abs(a[1]-n)?c:a);if(Math.abs(o[1]-n)/n<=.03)return o[0];const r=Math.round(e),i=Math.round(t);if(r<1||i<1)return null;const s=hc(r,i);return`${r/s}:${i/s}`}function io(e){const t=st(e.inputs?.startSeconds),n=st(e.inputs?.endSeconds),o=st(e.inputs?.durationSeconds),r=e.audioInfo?.durationSeconds??e.durationSeconds??o??(t!==null&&n!==null&&n>t?n-t:null),i=e.inputs?.audioRole==="continuous-source"?"Continuous source":e.inputs?.audioRole==="scene"?"Scene audio":e.hasOutput?"Audio output":"Select audio media",s=r!==null&&r>0?r:null;return{role:i,duration:s===null?null:me(s),durationSeconds:s,details:[e.audioInfo?.codec.toUpperCase()??null,e.audioInfo?`${e.audioInfo.sampleRateHz/1e3} kHz`:null,e.audioInfo?.channelLayout??null].filter(a=>!!a)}}function si(e){const t=e.inputs?.mediaRole;return e.type==="image"&&t==="generate-image-output"||e.type==="video"&&t==="generate-video-output"}function Gy(e,t){const n=Array.isArray(e?.outputVersionArtifactIds)?e.outputVersionArtifactIds.filter(o=>typeof o=="string"&&o.length>0):[];return[...new Set([...n,...t?[t]:[]])]}function bc(e){const t=h(e),n=t&&h(t.text),o=n&&h(n.format),r=W(o?.type);return r?{name:W(o?.name),strict:o?.strict===!0,type:r}:null}function qy(e){const t=h(e);if(!t)return[];const o=(Array.isArray(t.llmExchanges)?t.llmExchanges:[]).flatMap((i,s)=>{const a=h(i);if(!a||!mn(a,"input")||!mn(a,"response"))return[];const c=h(a.input);return[{complete:!0,input:a.input,model:W(a.model)??W(c?.model)??"Unknown",provider:W(a.provider)??"Unknown",response:a.response,responseFormat:bc(a.input),stage:W(a.stage)??`call_${s+1}`}]});if(o.length>0)return o;const r=h(t.request);return!r||!mn(t,"raw")?[]:[{complete:!1,input:r,model:W(r.model)??"Unknown",provider:W(r.provider)??"Unknown",response:t.raw,responseFormat:null,stage:"legacy_analysis"}]}function yc(e){return{first:W(e?.firstFrameArtifactId),last:W(e?.lastFrameArtifactId)}}function Uy(e){const t=st(e?.startSeconds),n=st(e?.endSeconds);return t!==null&&n!==null&&n>t?{startSeconds:t,endSeconds:n}:null}function By(e){return e.replace(/^generate_/,"gen_").replaceAll("_"," ").toUpperCase()}function Ke(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid cold-open response");return e}function _c(e){const t=Ke(e);if(typeof t.sourceArtifactId!="string"||typeof t.sourceObjectHash!="string"||typeof t.durationSeconds!="number"||typeof t.fps!="number"||typeof t.startSeconds!="number"||typeof t.endSeconds!="number"||typeof t.reason!="string"||typeof t.model!="string"||oi(t.startSeconds,t.endSeconds,t.durationSeconds))throw new Error("The server returned an invalid cold-open selection");return t}async function ai(e,t,n,o){if(typeof n!="number")throw new Error("The server did not return a cold-open job ID");for(let r=0;r<1200;r+=1){if(!o())throw new Error("Workspace changed. Reopen the cold-open review.");const i=await e("list_jobs",{book_id:t,job_ids:[n]},{background:!0});if(!Array.isArray(i)||!i.length)throw new Error("The cold-open job could not be found");const s=Ke(i[0]);if(s.state==="done")return Ke(s.result);if(s.state==="failed"||s.state==="aborted")throw new Error(String(Ke(s.error??{}).message??"Cold-open job cancelled"));await new Promise(a=>setTimeout(a,500))}throw new Error("The cold open is still processing. Check Jobs, then retry to reconnect.")}async function Hy(e,t,n){const o=Ke(await e("prepare_cold_open",{book_id:t.bookId,notebook_id:t.notebookId,asset_id:t.assetId})),r=o.status==="ready"?o:await ai(e,t.bookId,o.job_id,n),i=_c(r.suggestion);if(!n()||i.sourceArtifactId!==t.assetId)throw new Error("Workspace changed. Reopen the cold-open review.");return{...t,suggestion:i}}async function Wy(e,t,n){const o=t.suggestion;if(!o)throw new Error("Find a highlight first");const r=oi(o.startSeconds,o.endSeconds,o.durationSeconds);if(r)throw new Error(r);const i=Ke(await e("edit_cold_open",{book_id:t.bookId,notebook_id:t.notebookId,asset_id:t.assetId,source_object_hash:o.sourceObjectHash,start_time:o.startSeconds,end_time:o.endSeconds,request_id:t.requestId})),s=await ai(e,t.bookId,i.job_id,n);if(!n())throw new Error("Workspace changed. The copy is available in its original notebook.");if(typeof s.cell_id!="string"||typeof s.address!="string")throw new Error("The cold-open copy has no notebook cell");return{cellId:s.cell_id,address:s.address}}const ci="nano-banana-2-1";function Ky(e){if(!e)return!1;const t=e.toLowerCase().replaceAll(/[_-]+/g," ");return/\b(?:out of|insufficient|not enough|no(?: remaining| more| available)?) credits?\b/.test(t)||/\bcredits? (?:balance )?(?:is |are )?(?:insufficient|exhausted|depleted|too low)\b/.test(t)||/\b(?:insufficient|not enough|low|exhausted) (?:account |credit )?balance\b/.test(t)||/\b(?:account |credit )?balance (?:is )?(?:insufficient|too low|exhausted)\b/.test(t)||/\binsufficient quota\b/.test(t)||/\b(?:exceeds? (?:your|the) (?:remaining |available )?credits?|credits? (?:left|remaining).{0,100}(?:required|requested|needed))\b/.test(t)}function zy(e,t){const n=e.cells.find(r=>r.id===t);if(!n||!["image","video","audio"].includes(n.type))return null;const o=e.edges.find(r=>r.target===n.id&&r.targetInput==="media");return e.cells.find(r=>r.id===o?.source&&r.type===`generate_${n.type}`)??null}function Xy(e,t){(!e||e.isCurrent())&&t()}function Yy(e,t,n){e&&!e.isCurrent()||(e?.review(t),n())}function lt(e){return["sending","working","queued","review"].includes(e.status)}function Jy(e,t=!0){if(!t&&lt(e)&&e.status!=="review")return"Reconnecting…";const n={sending:"Sending",working:"Working",queued:"Queued",review:"Awaiting review",completed:"Completed",failed:"Failed",cancelled:"Cancelled"},o=e.work.filter(r=>r.state==="completed").length;return e.work.length>1&&lt(e)&&e.status!=="review"?`${n[e.status]} · ${o} of ${e.work.length} complete`:n[e.status]}function On(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ge(e){return typeof e=="string"&&e?e:void 0}function at(e){return e==="failed"||e==="error"?"failed":e==="aborted"||e==="cancelled"?"cancelled":e==="done"||e==="completed"||e==="ready"?"completed":e==="running"||e==="completing"||e==="processing"?"working":"queued"}function vc(e,t,n){const o=On(n);if(!o)return[];const r=o.job_id??o.jobId??o.retry_job_id,i=Ge(r)??Ge(o.operation_id??o.operationId),s=Ge(o.run_id??o.runId),a=Array.isArray(o.cell_ids)?o.cell_ids:Array.isArray(t.cell_ids)?t.cell_ids:[],c=Ge((e==="run_notebook_cell"?o.output_cell_id:void 0)??o.cell_id??o.cellId??t.cell_id??(a.length===1?a[0]:void 0)),l=Ge(o.output_artifact_id??o.outputArtifactId??o.artifact_id??o.artifactId??o.asset_id??o.assetId),u=e.replaceAll("_"," ").replace(/^./u,d=>d.toUpperCase()),m=[];if((typeof r=="number"||i)&&m.push({key:s?`run:${s}`:`job:${r??i}`,label:u,...typeof r=="number"?{jobId:r}:{},operationId:i,runId:s,cellId:c,artifactId:l,state:s?"queued":at(o.status)}),Array.isArray(o.steps))for(const d of o.steps){const f=On(d);if(!(!f||!Array.isArray(f.child_job_ids)))for(const g of f.child_job_ids)typeof g=="number"&&m.push({key:`job:${g}`,jobId:g,label:Ge(f.tool)?.replaceAll("_"," ")??u,state:at(f.status)})}return m}function kc(e,t){const n=new Map(e.map(o=>[o.key,o]));for(const o of t){const r=n.get(o.key);n.set(o.key,r&&["completed","failed","cancelled"].includes(r.state)?r:{...r,...o})}return[...n.values()]}function Ln(e){if(e.status==="sending"||e.status==="review"||e.status==="failed"||e.status==="cancelled"||!e.work.length)return e;const t=e.work.find(r=>r.state==="failed");if(t)return{...e,status:"failed",reply:t.detail??e.reply};const n=e.work.filter(r=>r.state==="queued"||r.state==="working");if(n.length)return{...e,status:n.some(r=>r.state==="working")?"working":"queued"};if(e.executing)return{...e,status:"working"};const o=e.work.some(r=>r.state==="cancelled")?"cancelled":"completed";return{...e,status:o,reply:e.status==="queued"||e.status==="working"?o==="completed"?"Work completed.":"Work cancelled.":e.reply}}function wc(e,t,n,o=[]){const r=e.work.map(i=>{if(["completed","failed","cancelled"].includes(i.state))return i;const s=t.filter(m=>m.id===i.jobId||m.operationId===i.operationId||i.runId&&m.payload?.runId===i.runId),a=s.find(m=>m.state==="failed"||m.state==="aborted");if(a)return{...i,state:at(a.state),detail:a.error?.message};if(i.runId&&n?.id===e.notebookId){const d=(i.cellId?[i.cellId]:Object.entries(n.execution??{}).filter(([,g])=>On(g)?.runId===i.runId).map(([g])=>g)).map(g=>gc(n,g,i.runId));if(d.length&&d.every(g=>g.state==="completed"))return{...i,state:"completed"};const f=d.find(g=>g.state==="error");return f?{...i,state:"failed",detail:f.error??void 0}:{...i,state:s.some(g=>g.state!=="queued")?"working":i.state}}const c=s.find(m=>["queued","running","completing"].includes(m.state));if(c)return{...i,state:at(c.state)};if(!s.length)return i;if(i.runId)return{...i,state:"working"};const l=i.artifactId??s.find(m=>m.artifactId)?.artifactId,u=o.find(m=>m.artifactId===l);return u&&u.status!=="ready"?{...i,state:at(u.status)}:l&&!u?{...i,artifactId:l,state:"working"}:{...i,state:"completed"}});return Ln({...e,work:r})}const Zy=2400;function Qy(e,t){const n=t.filter(o=>!e.has(o));return n.length===0?e:new Set([...e,...n])}function e_(e,t){const n=[...e].filter(o=>!t.includes(o));return n.length===e.size?e:new Set(n)}const Sc=new Set(["queued","running","completing"]);function li(e,t,n){const o=n.find(i=>i.target===e.id&&i.targetInput==="media");if(!o)return null;const r=t.find(i=>i.id===o.source);return r&&(r.type==="generate_image"||r.type==="generate_video")?r:null}function Ic(e,t,n){return si(e)?li(e,t,n):null}function xc(e,t,n){const o=(n??[]).filter(r=>{if(r.type!=="await_notebook_output"||!Sc.has(r.state))return!1;const i=r.payload,s=typeof i?.outputCellId=="string"&&i.outputCellId?i.outputCellId:null;if(s)return s===e;const a=typeof i?.cellId=="string"&&i.cellId?i.cellId:null;return t!==null&&a===t});return o.length===0?null:o.reduce((r,i)=>(i.operationId??"")>(r.operationId??"")?i:r)}function Lo(e,t){const n=e?.payload?.[t];return typeof n=="string"&&n?n:null}function Fo(e,t,n,o){return{...{startedAt:typeof n?.startedAt=="number"?new Date(n.startedAt).toISOString():null,provider:t?.provider??null,model:t?.model??null,prompt:t?.prompt??e.prompt??null,producerCellId:t?.id??null,jobId:n?.operationId??null,providerArtifactId:Lo(n,"providerArtifactId"),runId:Lo(n,"runId")},kind:o||n===null||n.state==="queued"?"queued":"generating"}}function t_(e){if(!si(e.cell))return{kind:"ready"};const t=li(e.cell,e.cells,e.edges),n=t?.id??null,o=e.runErrors?.[e.cell.id]??e.error;if(o)return{kind:"failed",message:o,producerCellId:n};const r=xc(e.cell.id,n,e.jobs);return r?Fo(e.cell,t,r,e.queuedCellIds?.has(e.cell.id)??!1):e.queuedCellIds?.has(e.cell.id)?Fo(e.cell,t,null,!0):{kind:"ready"}}function n_(e){return e==="video"||e==="generate_video"?"video":e==="image"||e==="generate_image"?"image":e==="audio"||e==="generate_audio"?"audio":"generation"}function Ac(e,t){const n=[e,t].filter(o=>typeof o=="string"&&o.length>0);return n.length===0?null:n.join(" · ")}function o_(e){const t=e.error.trim()||"the provider rejected the request",n=Ac(e.provider,e.model),o=e.producerAddress?`the ${e.mediaLabel} generated by ${e.producerAddress}`:`the ${e.mediaLabel}`,r=e.producerAddress?` and the settings on ${e.producerAddress}`:" and this cell's settings",i=e.producerAddress?`re-run ${e.producerAddress} into ${e.address}`:`re-run ${e.address}`;return[`Repair ${e.address}: ${o} failed with "${t}".`,n?`Generator: ${n}.`:null,`Inspect the recorded provider request${r}, fix what the provider rejected, and ${i} as a preview.`].filter(s=>s!==null).join(" ")}function r_(e,t){return e==="kie"?"https://kie.ai/logs":e!=="fal"||!t||!/^[a-z0-9_-]+(?:\/[a-z0-9_.-]+)+$/iu.test(t)||t.split("/").some(n=>n==="."||n==="..")?null:`https://fal.ai/models/${t.split("/").map(encodeURIComponent).join("/")}/requests`}function ui(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.provider!=="kie"&&t.provider!=="fal"?null:{provider:t.provider,model:typeof t.model=="string"?t.model:null,taskId:typeof t.taskId=="string"?t.taskId:null}}function Ye(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Je(e){return typeof e=="string"&&e?e:null}function Ec(e){const t=Ye(e),n=Je(t?.taskId),o=Je(t?.submittedAt);return!t||!n||!o?null:{taskId:n,submittedAt:o,completing:t.completing===!0}}function i_(e){const t=Ye(e)??{},n=ui(t.providerTask);return{payload:t.payload??null,taskType:Je(t.taskType),task:Ec(t.task),errorMessage:Je(Ye(t.error)?.message),...n?{providerTask:n}:{}}}function di(e){const t=Ye(e);return t?Ye(t.input)??t:null}function s_(e){return Je(di(e)?.prompt)??Je(Ye(e)?.prompt)}const Cc=new Set(["prompt","model","callBackUrl"]);function Mc(e){return typeof e=="number"||typeof e=="boolean"?String(e):typeof e!="string"||!e||/^https?:\/\//i.test(e)?null:e}function a_(e){const t=di(e);return t?Object.entries(t).flatMap(([n,o])=>{if(Cc.has(n))return[];const r=Mc(o);return r===null?[]:[{key:n,value:r}]}):[]}function Tc(e){return e.runKind==="queued"?["active","pending","pending","pending"]:e.task?e.task.completing?["done","done","done","active"]:["done","done","active","pending"]:["done","active","pending","pending"]}function c_(e){const t=Tc(e),n=e.runKind==="failed"?t.findIndex(r=>r==="active"):-1;return[{id:"started",label:"Run started",at:e.startedAt},{id:"submitted",label:"Submitted",at:e.task?.submittedAt??null},{id:"generating",label:"Provider generating",at:e.task?.submittedAt??null},{id:"landing",label:"Download & commit",at:null}].map((r,i)=>({...r,status:i===n?"failed":t[i]??"pending"}))}let Do=0;function Bt(){return Do+=1,Do}function l_(e,t){const n=ne.c(23);let o;n[0]===Symbol.for("react.memo_cache_sentinel")?(o=[],n[0]=o):o=n[0];const[r,i]=_.useState(o),s=_.useRef(r);let a;n[1]!==e||n[2]!==t?(a={bookId:e,notebookId:t},n[1]=e,n[2]=t,n[3]=a):a=n[3];const c=_.useRef(a),l=_.useRef(0);let u;n[4]===Symbol.for("react.memo_cache_sentinel")?(u=new Map,n[4]=u):u=n[4];const m=_.useRef(u),d=_.useRef(null),f=_.useRef(null);let g,p;n[5]!==e||n[6]!==t?(g=()=>{c.current={bookId:e,notebookId:t},l.current=l.current+1,d.current=s.current.filter(M=>M.bookId===e&&M.notebookId===t).at(-1)?.id??null,f.current=null},p=[e,t],n[5]=e,n[6]=t,n[7]=g,n[8]=p):(g=n[7],p=n[8]),_.useLayoutEffect(g,p);let y;n[9]===Symbol.for("react.memo_cache_sentinel")?(y=M=>{const R=M(s.current);JSON.stringify(R)!==JSON.stringify(s.current)&&(s.current=R,i(R))},n[9]=y):y=n[9];const v=y;let S;n[10]===Symbol.for("react.memo_cache_sentinel")?(S=M=>{const R=f.current===null?void 0:m.current.get(f.current);if(/^\/(?:apply|cancel)(?:\s|$)/iu.test(M)&&R?.isInScope())return v(K=>K.map(H=>H.id===R.id?{...H,status:"working",executing:!0}:H)),R;const D={...c.current},z=l.current,q=Bt();d.current=q,f.current=null,v(K=>[...K.map(H=>H.bookId===D.bookId&&H.notebookId===D.notebookId&&H.status==="review"?{...H,status:"cancelled"}:H),{id:q,...D,text:M,status:"sending",reply:"",work:[],executing:!0}].filter(Pc));const J=K=>v(H=>H.map(U=>U.id===q?K(U):U)),pe=()=>l.current===z&&c.current.bookId===D.bookId&&c.current.notebookId===D.notebookId,ge={id:q,isInScope:pe,isCurrent:()=>pe()&&d.current===q&&s.current.find(K=>K.id===q)?.status!=="cancelled",working:()=>J(Nc),review:K=>{K&&ge.isCurrent()?f.current=q:f.current===q&&(f.current=null),J(H=>({...H,status:K?"review":"working"}))},accept:(K,H,U)=>{const ke=vc(K,H,U);ke.length&&J(Q=>Ln({...Q,work:kc(Q.work,ke)}))},finish:K=>J(H=>H.status==="cancelled"?H:Ln({...H,reply:K.message,executing:!1,status:K.status??(f.current===q?"review":K.ok?"completed":"failed")}))};m.current.set(q,ge);for(const K of m.current.keys())s.current.some(H=>H.id===K)||m.current.delete(K);return ge},n[10]=S):S=n[10];const w=S;let k;n[11]===Symbol.for("react.memo_cache_sentinel")?(k=()=>{const M=Bt(),R=l.current;d.current=M;let D=!1;for(const[q,J]of m.current)J.visible===!1&&q!==f.current&&m.current.delete(q);const z={id:M,visible:!1,isInScope:()=>l.current===R,isCurrent:()=>!D&&l.current===R&&d.current===M,working:$c,accept:Rc,finish:q=>{q.status==="cancelled"&&(D=!0)},review:q=>{q&&z.isCurrent()?f.current=M:f.current===M&&(f.current=null)}};return m.current.set(M,z),z},n[11]=k):k=n[11];const I=k;let E;n[12]===Symbol.for("react.memo_cache_sentinel")?(E=(M,R,D,z)=>{v(q=>q.map(J=>J.bookId===M&&(!D||J.notebookId===D.id)&&lt(J)?wc(J,R,D,z):J))},n[12]=E):E=n[12];const C=E;let A;n[13]===Symbol.for("react.memo_cache_sentinel")?(A=()=>{const M=f.current;f.current=null,M!==null&&m.current.get(M)?.finish({ok:!0,status:"cancelled",message:"Pending action cancelled."}),M!==null&&v(R=>R.map(D=>D.id===M?{...D,status:"cancelled"}:D))},n[13]=A):A=n[13];const $=A;let T;if(n[14]!==e||n[15]!==t||n[16]!==r){let M;n[18]!==e||n[19]!==t?(M=R=>R.bookId===e&&R.notebookId===t,n[18]=e,n[19]=t,n[20]=M):M=n[20],T=r.filter(M),n[14]=e,n[15]=t,n[16]=r,n[17]=T}else T=n[17];let N;return n[21]!==T?(N={turns:T,begin:w,observe:C,cancelReview:$,claimVoice:I},n[21]=T,n[22]=N):N=n[22],N}function Rc(){}function $c(){}function Nc(e){return{...e,status:"working"}}function Pc(e,t,n){return t>=n.length-256||lt(e)}const fi="data:text/javascript;base64,Y2xhc3MgVm9pY2VDYXB0dXJlIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsKICAgIHN1cGVyKCkKICAgIHRoaXMuZnJhbWVTaXplID0gTWF0aC5yb3VuZChzYW1wbGVSYXRlIC8gNTApCiAgICB0aGlzLmZyYW1lID0gbmV3IEFycmF5QnVmZmVyKHRoaXMuZnJhbWVTaXplICogMikKICAgIHRoaXMudmlldyA9IG5ldyBEYXRhVmlldyh0aGlzLmZyYW1lKQogICAgdGhpcy5vZmZzZXQgPSAwCiAgfQoKICBwcm9jZXNzKGlucHV0cykgewogICAgY29uc3Qgc2FtcGxlcyA9IGlucHV0c1swXT8uWzBdCiAgICBpZiAoIXNhbXBsZXMpIHJldHVybiB0cnVlCiAgICBmb3IgKGNvbnN0IHNhbXBsZSBvZiBzYW1wbGVzKSB7CiAgICAgIGNvbnN0IGNsYW1wZWQgPSBNYXRoLm1heCgtMSwgTWF0aC5taW4oMSwgc2FtcGxlKSkKICAgICAgdGhpcy52aWV3LnNldEludDE2KHRoaXMub2Zmc2V0ICogMiwgY2xhbXBlZCAqIChjbGFtcGVkIDwgMCA/IDMyNzY4IDogMzI3NjcpLCB0cnVlKQogICAgICB0aGlzLm9mZnNldCArPSAxCiAgICAgIGlmICh0aGlzLm9mZnNldCA9PT0gdGhpcy5mcmFtZVNpemUpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5mcmFtZSwgW3RoaXMuZnJhbWVdKQogICAgICAgIHRoaXMuZnJhbWUgPSBuZXcgQXJyYXlCdWZmZXIodGhpcy5mcmFtZVNpemUgKiAyKQogICAgICAgIHRoaXMudmlldyA9IG5ldyBEYXRhVmlldyh0aGlzLmZyYW1lKQogICAgICAgIHRoaXMub2Zmc2V0ID0gMAogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZQogIH0KfQoKcmVnaXN0ZXJQcm9jZXNzb3IoJ3ZpZGVvYm9vay12b2ljZS1jYXB0dXJlJywgVm9pY2VDYXB0dXJlKQo=";class Oc{socket=null;capture=null;input=null;mute=null;stopped=!1;nextAt=0;sources=new Set;timers=new Set;items=[];completed=new Set;interrupted=new Set;rejectStart=null;options;constructor(t){this.options=t}async start(t,n){if(n.aborted)throw new Error("Voice start cancelled.");const o=new URL(`/api/voice/${t.id}/audio`,window.location.href);o.protocol=o.protocol==="https:"?"wss:":"ws:";const r=new WebSocket(o);this.socket=r;const i=()=>this.stop();n.addEventListener("abort",i,{once:!0});try{if(await new Promise((c,l)=>{this.rejectStart=l,r.addEventListener("open",()=>{this.stopped||r.send(JSON.stringify({type:"authenticate",token:t.token}))}),r.addEventListener("message",u=>{try{if(JSON.parse(String(u.data)).type!=="ready")throw new Error("Unexpected audio response");this.rejectStart=null,c()}catch{this.fail("Voice audio could not authenticate. Start voice again.")}}),r.addEventListener("error",()=>this.fail("Voice audio connection failed. Start voice again.")),r.addEventListener("close",()=>{this.stopped||this.fail("Voice audio connection ended. Start voice to reconnect.")})}),this.stopped)return;const{context:s,microphone:a}=this.options;if(await s.audioWorklet.addModule(fi),this.stopped)return;this.capture=new AudioWorkletNode(s,"videobook-voice-capture"),this.capture.port.onmessage=c=>{if(!(this.stopped||r.readyState!==WebSocket.OPEN)){if(r.bufferedAmount>s.sampleRate*4){this.fail("Voice audio connection is too slow. Start voice to reconnect.");return}r.send(c.data)}},this.input=s.createMediaStreamSource(a),this.mute=s.createGain(),this.mute.gain.value=0,this.input.connect(this.capture),this.capture.connect(this.mute),this.mute.connect(s.destination)}finally{n.removeEventListener("abort",i)}}enqueue(t,n,o){if(this.stopped||this.interrupted.has(n))return;const{context:r,output:i,sampleRate:s}=this.options;if(t.length>256e3||this.nextAt-r.currentTime>30)throw new Error("Voice audio exceeded its buffer limit.");const a=Uint8Array.from(atob(t),g=>g.charCodeAt(0));if(a.length===0||a.length%2!==0)throw new Error("Voice sent an invalid audio frame.");const c=new DataView(a.buffer),l=r.createBuffer(1,a.length/2,s),u=l.getChannelData(0);for(let g=0;g<u.length;g+=1)u[g]=c.getInt16(g*2,!0)/32768;const m=Math.max(r.currentTime+.015,this.nextAt);this.nextAt=m+l.duration;let d=this.items.find(g=>g.itemId===o);if(!d){d={responseId:n,itemId:o,startAt:m,duration:0},this.items.push(d);const g=window.setTimeout(()=>{this.timers.delete(g),this.stopped||this.options.onStarted(n)},Math.max(0,(m-r.currentTime)*1e3));this.timers.add(g)}d.duration+=l.duration;const f=r.createBufferSource();f.buffer=l,f.connect(i),this.sources.add(f),f.onended=()=>{f.disconnect(),this.sources.delete(f),!this.stopped&&this.sources.size===0&&this.completed.has(n)&&(this.options.onFinished(n),this.items=[],this.completed.clear())},f.start(m)}finish(t){this.stopped||this.interrupted.has(t)||(this.completed.add(t),this.sources.size===0&&(this.options.onFinished(t),this.items=[],this.completed.clear()))}interrupt(){const t=this.options.context.currentTime,n=this.items.find(r=>r.startAt+r.duration>t)??this.items.at(-1),o=n?{responseId:n.responseId,itemId:n.itemId,audioEndMs:Math.floor(Math.max(0,Math.min(n.duration,t-n.startAt))*1e3)}:void 0;for(const r of this.items)this.interrupted.add(r.responseId);return this.clear(),o}clear(){for(const t of this.timers)window.clearTimeout(t);this.timers.clear();for(const t of this.sources)t.onended=null,t.stop(),t.disconnect();this.sources.clear(),this.items=[],this.completed.clear(),this.nextAt=this.options.context.currentTime}fail(t){this.stopped||(this.rejectStart?.(new Error(t)),this.rejectStart=null,this.options.onError(t),this.stop())}stop(){this.stopped||(this.stopped=!0,this.rejectStart?.(new Error("Voice start cancelled.")),this.rejectStart=null,this.socket?.close(),this.capture?.port.close(),this.capture?.disconnect(),this.input?.disconnect(),this.mute?.disconnect(),this.clear())}}const Lc="videobook-voice";class Fc{connectAt=0;permissionStartAt=0;permissionEndAt=0;utteranceEndAt=0;turnAt=0;extra={};setSession(t){this.extra={...this.extra,...t}}mark(t,n){performance.mark(Lc,{detail:{stage:t,...this.extra,...n}})}connectStart(){this.connectAt=performance.now(),this.mark("connect-start")}permissionWaitStart(){this.permissionStartAt=performance.now(),this.mark("permission-wait-start")}permissionWaitEnd(){this.permissionEndAt=performance.now(),this.mark("permission-wait-end",{durationMs:this.permissionEndAt-this.permissionStartAt})}sessionRequest(){this.mark("session-request")}providerReady(t){this.setSession({model:t.model,provider:t.provider,transport:t.transport}),this.mark("provider-ready",t),t.fallbackReason&&this.mark("fallback",{reason:t.fallbackReason})}mediaReady(){const t=performance.now();this.mark("media-ready"),this.mark("connection-setup",{durationMs:t-this.connectAt,permissionWaitMs:Math.max(0,this.permissionEndAt-this.permissionStartAt)})}turnDetection(t){this.turnAt=performance.now(),this.utteranceEndAt=t&&t>0?t:this.turnAt,this.mark("turn-detection",{microphoneSignalEndedAt:t})}firstDecodedAudio(t){if(this.turnAt===0){this.mark("activation-audio");return}this.utteranceEndAt===0&&t&&t>0&&(this.utteranceEndAt=t);const n=performance.now();this.mark("first-audio"),this.utteranceEndAt>0&&this.mark("utterance-end-to-decoded-audio",{durationMs:n-this.utteranceEndAt,turnDetectionMs:this.turnAt>0?this.turnAt-this.utteranceEndAt:void 0,generationMs:this.turnAt>0?n-this.turnAt:void 0,microphoneSignalEndedAt:this.utteranceEndAt})}acknowledgement(t){this.mark("acknowledgement",t?{status:t}:void 0)}}function mi(e){return e!=="xai"}function Dc(e){const t={bookId:e.bookId,mode:e.mode,sampleRate:e.sampleRate};return e.notebookId&&(t.notebookId=e.notebookId),mi(e.mode)&&e.sdp&&(t.sdp=e.sdp),{url:"/api/voice",body:t}}function pn(e){if(e instanceof DOMException){if(e.name==="NotAllowedError"||e.name==="SecurityError")return"Microphone access is blocked. Allow it in your browser, then start voice again.";if(e.name==="NotFoundError")return"No microphone found. Connect one, then start voice again.";if(e.name==="NotReadableError")return"The microphone is busy or unavailable. Check your audio device, then try again."}return e instanceof Error?e.message:"Voice could not connect. Try again."}class Vc{abort=new AbortController;peer=null;pcm=null;microphone=null;channel=null;context=null;remoteAudio=null;output=null;inputMeter=null;outputMeter=null;descriptor=null;stopped=!1;frame=0;deadline=0;playing=!1;awaitingAudio=!1;awaitingSilence=!1;lastMicrophoneSignalAt=0;outputResponseId=null;review=null;actions=new Set;captionStarts=new Set;outcomes=Promise.resolve();phase="connecting";cleanupListeners=[];timeline=new Fc;options;constructor(t){this.options=t}updatePhase(t,n){this.phase=t,this.options.onPhase(t,n)}mark(t,n){this.timeline.mark(t,{model:this.descriptor?.model,...n})}listen(t,n,o,r=!1){t.addEventListener(n,o,r),this.cleanupListeners.push(()=>t.removeEventListener(n,o,r))}async start(){let t;try{if(this.stopped)return;if(!window.isSecureContext||!navigator.mediaDevices?.getUserMedia||!window.RTCPeerConnection||!window.AudioContext)throw new Error("Voice needs a browser with microphone support on HTTPS or localhost.");this.updatePhase("connecting","Connecting voice"),this.timeline.connectStart(),this.deadline=window.setTimeout(()=>this.stop("Voice connection timed out. Start voice to retry.",!0),this.options.mode==="auto"?8e4:3e4),this.timeline.permissionWaitStart(),this.updatePhase("connecting","Allow microphone access");const n=navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1}).finally(()=>{this.timeline.permissionWaitEnd()});t=()=>{n.then(s=>{this.microphone!==s&&s.getTracks().forEach(a=>a.stop())}).catch(()=>{})},this.context=new AudioContext({latencyHint:"interactive",sampleRate:48e3}),this.context.resume().then(()=>{this.stopped||this.mark("audio-context-running")}).catch(()=>{this.stopped||this.options.onPlaybackBlocked(!0)}),this.output=this.context.createGain(),this.outputMeter=this.context.createAnalyser(),this.outputMeter.fftSize=256,this.output.connect(this.outputMeter),this.outputMeter.connect(this.context.destination);for(const s of document.querySelectorAll("audio, video"))s.pause();this.installAmbientListeners(),this.context.audioWorklet.addModule(fi).catch(()=>{});const o=!mi(this.options.mode);o&&this.timeline.sessionRequest();const r=o?this.requestSession():null,i=await n;if(this.stopped){i.getTracks().forEach(s=>s.stop()),this.mark("microphone-released",{ended:i.getTracks().every(s=>s.readyState==="ended")});return}if(this.microphone=i,this.updatePhase("connecting","Connecting voice"),this.bindMicrophone(i),this.measure(),o){const s=await r;if(!s)return;if(s.transport!=="pcm")throw new Error("Voice returned a WebRTC session for an xAI request.");await this.acceptPcm(s,i);return}await this.startWebRtc(i)}catch(n){t?.(),this.stopped||this.stop(pn(n),!0)}}installAmbientListeners(){this.listen(document,"play",()=>this.stop("Comms paused for media playback. Start voice to resume."),!0),this.listen(document,"visibilitychange",()=>{document.hidden&&this.stop("Comms off while the page is hidden.")}),this.listen(window,"pagehide",()=>this.stop()),this.listen(window,"offline",()=>this.stop("You are offline. Start voice after reconnecting.",!0))}bindMicrophone(t){for(const n of t.getAudioTracks())this.listen(n,"ended",()=>this.stop("Microphone disconnected. Check the device and start voice again.",!0));this.inputMeter=this.context.createAnalyser(),this.inputMeter.fftSize=256,this.context.createMediaStreamSource(t).connect(this.inputMeter)}async requestSession(t){const{url:n,body:o}=Dc({bookId:this.options.bookId,notebookId:this.options.notebookId,mode:this.options.mode,sampleRate:this.context.sampleRate,sdp:t}),r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:this.abort.signal}),i=await r.json();if(!r.ok)throw new Error(i.error??"Voice could not connect. Try again.");return this.descriptor=i,this.timeline.providerReady({provider:i.provider,transport:i.transport,model:i.model,fallbackReason:i.fallbackReason}),this.stopped?(this.releaseSession(),null):(this.options.onProvider(i.provider,i.fallbackReason),i)}async acceptPcm(t,n){this.pcm=new Oc({context:this.context,microphone:n,output:this.output,sampleRate:t.sampleRate,onStarted:o=>this.mediaEvent({type:"output_audio_buffer.started",response_id:o}),onFinished:o=>this.mediaEvent({type:"output_audio_buffer.stopped",response_id:o}),onError:o=>this.stop(o,!0)}),this.readEvents(t),await this.pcm.start(t,this.abort.signal),this.stopped||this.connected()}connected(){window.clearTimeout(this.deadline),this.mark("connected"),this.timeline.mediaReady(),this.updatePhase("listening"),this.post("ready",{})}async startWebRtc(t){const n=new RTCPeerConnection;this.peer=n;for(const r of t.getAudioTracks())n.addTrack(r,t);if(this.listen(n,"track",r=>{if(this.stopped)return;const i=r.track;this.mark("media-track");const s=new MediaStream([i]);this.remoteAudio=new Audio,this.remoteAudio.muted=!0,this.remoteAudio.srcObject=s,this.remoteAudio.play().catch(()=>{this.stopped||this.options.onPlaybackBlocked(!0)}),this.context.createMediaStreamSource(s).connect(this.output),this.options.onPlaybackBlocked(this.context?.state!=="running")}),this.listen(n,"connectionstatechange",()=>{this.stopped||(n.connectionState==="failed"||n.connectionState==="disconnected"||n.connectionState==="closed")&&this.stop("Voice connection lost. Start voice to reconnect.",!0)}),this.channel=n.createDataChannel("oai-events"),this.listen(this.channel,"message",r=>{if(!this.stopped)try{this.mediaEvent(JSON.parse(String(r.data)))}catch{this.stop("Voice sent an unreadable event. Start voice again.",!0)}}),this.listen(this.channel,"open",()=>{this.stopped||this.connected()}),this.listen(this.channel,"close",()=>{this.stopped||this.stop("Voice channel closed. Start voice again.",!0)}),await n.setLocalDescription(await n.createOffer()),this.stopped)return;this.timeline.sessionRequest();const o=await this.requestSession(n.localDescription?.sdp);if(o){if(o.transport==="pcm"){this.cleanupListeners.splice(0).forEach(r=>r()),this.channel?.close(),this.peer?.close(),this.channel=null,this.peer=null,this.installAmbientListeners(),this.bindMicrophone(t),await this.acceptPcm(o,t);return}this.readEvents(o),await n.setRemoteDescription({type:"answer",sdp:o.sdp})}}mediaEvent(t){if(typeof t.type=="string"&&/audio_buffer\.(started|stopped|cleared)|speech_(started|stopped)/u.test(t.type)&&this.mark(t.type),t.type==="input_audio_buffer.speech_started"){const n=this.pcm?.interrupt();n&&this.post("interrupt",n),this.playing&&(this.mark("barge-in"),this.awaitingSilence=!0,this.outputResponseId&&!n&&this.post("interrupt",{responseId:this.outputResponseId})),this.playing=!1,this.awaitingAudio=!1,this.output&&(this.output.gain.value=0),this.options.onRetrying?.(!1),this.updatePhase(this.review?"review":"listening")}else if(t.type==="input_audio_buffer.speech_stopped")this.mark("speech-stop",{microphoneSignalEndedAt:this.lastMicrophoneSignalAt}),this.timeline.turnDetection(this.lastMicrophoneSignalAt),this.updatePhase(this.review?"review":"thinking");else if(t.type==="output_audio_buffer.started")this.outputResponseId=typeof t.response_id=="string"?t.response_id:null,this.playing=!0,this.awaitingAudio=!0,this.output&&(this.output.gain.value=1),this.updatePhase(this.review?"review":"speaking");else if(t.type==="output_audio_buffer.stopped"||t.type==="output_audio_buffer.cleared"){if(t.response_id&&t.response_id!==this.outputResponseId)return;this.playing=!1,this.output&&(this.output.gain.value=0),this.updatePhase(this.review?"review":"listening")}}measure(){const t=new Float32Array(256),n=new Float32Array(256),o=i=>Math.sqrt(i.reduce((s,a)=>s+a*a,0)/i.length),r=()=>{if(this.stopped)return;this.inputMeter?.getFloatTimeDomainData(t),this.outputMeter?.getFloatTimeDomainData(n),o(t)>.008&&(this.lastMicrophoneSignalAt=performance.now());const i=Math.min(1,Math.max(o(t),this.playing?o(n):0)*5);this.awaitingAudio&&o(n)>.002&&this.context?.state==="running"&&(this.timeline.firstDecodedAudio(this.lastMicrophoneSignalAt),this.awaitingAudio=!1),this.awaitingSilence&&o(n)<.002&&(this.mark("local-silence"),this.awaitingSilence=!1),this.options.onLevel(i),this.frame=requestAnimationFrame(r)};this.frame=requestAnimationFrame(r)}async readEvents(t){try{const n=await fetch(`/api/voice/${t.id}/events`,{headers:{Authorization:`Bearer ${t.token}`},signal:this.abort.signal});if(!n.ok||!n.body)throw new Error("Voice event connection failed. Start voice again.");const o=n.body.getReader(),r=new TextDecoder;let i="";for(;!this.stopped;){const s=await o.read();if(s.done)break;if(i+=r.decode(s.value,{stream:!0}),i.length>512e3)throw new Error("Voice event exceeded its size limit.");const a=i.split(`
6
+ `);i=a.pop()??"";for(const c of a)c&&!this.stopped&&this.receive(JSON.parse(c))}this.stopped||this.stop("Voice connection ended. Start voice to reconnect.",!0)}catch(n){this.stopped||this.stop(pn(n),!0)}}receive(t){t.type==="caption"?(this.captionStarts.has(t.caption.id)||(this.captionStarts.add(t.caption.id),this.mark("caption-first",{role:t.caption.role})),t.caption.final&&!t.caption.interrupted&&this.mark("caption-final",{role:t.caption.role}),t.caption.interrupted&&this.mark("caption-interrupted"),this.options.onCaption(t.caption)):t.type==="error"?this.stop(t.message,!0):t.type==="closed"?this.stop(t.reason):t.type==="audio"?this.pcm?.enqueue(t.audio,t.responseId,t.itemId):t.type==="audio-done"?this.pcm?.finish(t.responseId):t.type==="activity"?(t.interrupt?this.mediaEvent({type:"input_audio_buffer.speech_started"}):this.pcm&&t.phase==="thinking"&&this.mediaEvent({type:"input_audio_buffer.speech_stopped"}),this.options.onRetrying?.(!!t.retry),this.playing||this.updatePhase(this.review?"review":t.phase)):t.type==="action"&&!this.actions.has(t.callId)?(this.actions.add(t.callId),this.action(t)):t.type==="review"&&!this.actions.has(t.callId)&&(this.actions.add(t.callId),this.reviewCommand(t))}async reviewCommand(t){let n;try{n=await this.options.onReviewCommand(t.command)}catch(o){n={status:"failed",message:o instanceof Error?o.message:"The review command failed."}}this.stopped||(n.status!=="review"&&(this.review=null),this.updatePhase(this.review?"review":this.playing?"speaking":"listening"),await this.acknowledge(t.callId,n))}async action(t){let n;try{n=await this.options.onAction(t)}catch(o){n={status:"failed",message:o instanceof Error?o.message:"The action failed."}}this.stopped||(n.status==="review"&&(this.mark("action-review"),this.review=t.callId,this.updatePhase("review")),await this.acknowledge(t.callId,n))}async post(t,n){const o=this.descriptor;if(!(this.stopped||!o))try{if(!(await fetch(`/api/voice/${o.id}/${t}`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:this.abort.signal})).ok)throw new Error("Voice could not receive the action outcome. Check the command UI.")}catch(r){this.stopped||this.stop(pn(r),!0)}}reportOutcome(t){if(!this.review)return;const n=this.review;t.status!=="review"&&(this.review=null),this.acknowledge(n,t),this.updatePhase(this.review?"review":this.playing?"speaking":"listening")}acknowledge(t,n){return this.timeline.acknowledgement(n.status),this.outcomes=this.outcomes.then(()=>this.post("outcome",{callId:t,outcome:n})),this.outcomes}shareTypedTurn(t,n){this.post("context",{userText:t.slice(0,8e3),assistantText:n.slice(0,4e3)})}async resumePlayback(){if(!(this.stopped||!this.context))try{await this.context.resume(),await this.remoteAudio?.play(),this.stopped||this.options.onPlaybackBlocked(this.context.state!=="running")}catch{this.stopped||this.options.onPlaybackBlocked(!0)}}releaseSession(){const t=this.descriptor;this.descriptor=null,t&&fetch(`/api/voice/${t.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({interruptedResponseId:this.playing?this.outputResponseId:null}),keepalive:!0}).catch(()=>{})}stop(t="Comms off.",n=!1){this.stopped||(this.stopped=!0,this.output?.disconnect(),this.remoteAudio?.pause(),this.remoteAudio&&(this.remoteAudio.srcObject=null),this.microphone?.getTracks().forEach(o=>o.stop()),this.mark("microphone-released",{ended:this.microphone?.getTracks().every(o=>o.readyState==="ended")??!0}),this.microphone=null,this.mark("stopped"),cancelAnimationFrame(this.frame),window.clearTimeout(this.deadline),this.cleanupListeners.splice(0).forEach(o=>o()),this.abort.abort(),this.channel?.close(),this.pcm?.stop(),this.peer?.getReceivers().forEach(o=>o.track.stop()),this.peer?.close(),this.context?.close().catch(()=>{}),this.options.onLevel(0),this.options.onPlaybackBlocked(!1),this.releaseSession(),this.updatePhase(n?"error":"off",t))}get active(){return!this.stopped&&this.phase!=="off"&&this.phase!=="error"}}const jc=6e4;function Gc(e){return e.text.trim().length>0||!!e.interrupted}function u_(e,t,n=[],o=[]){const r=e.filter(Gc).map(u=>({kind:"caption",sequence:u.sequence??0,caption:u})),i=n.map(u=>({kind:"caption",sequence:u.id,turn:u,caption:{id:`typed:${u.id}`,sequence:u.id,role:"user",text:u.text,final:!0},calls:t.calls.filter(m=>m.turnId===u.id)})),s=t.calls.filter(u=>u.turnId===void 0).map(u=>({kind:"call",sequence:u.id,call:u})),a=[...r,...i,...s,...o].sort((u,m)=>u.sequence!==m.sequence?u.sequence-m.sequence:u.kind===m.kind?0:u.kind==="caption"?-1:1),l=a.flatMap((u,m)=>u.kind==="caption"&&u.caption.role==="user"?[m]:[]).at(-2);return l===void 0?a:a.filter((u,m)=>m>=l||u.kind==="caption"&&u.turn&&lt(u.turn))}function d_(e){return e.at(-1)?.sequence??0}function f_(e){return e.map(t=>t.kind==="status"?`${t.sequence}:${t.text}`:t.kind==="call"?`${t.sequence}:${t.call.phase}`:t.turn?`${t.sequence}:${t.turn.status}:${t.turn.reply}:${t.turn.work.map(n=>n.state).join(":")}`:String(t.sequence)).join(",")}function m_(e){if(e.runningCalls>0)return!0;switch(e.voicePhase){case"connecting":case"thinking":case"speaking":case"review":return!0;default:return!1}}function p_(e){if(!e.open||e.held)return()=>{};const t=e.setTimeoutFn??setTimeout,n=e.clearTimeoutFn??clearTimeout,o=t(e.onClose,e.delayMs??jc);return()=>{n(o)}}function g_(e,t,n){return t>0?!1:n?e==="off"||e===void 0:!0}const pi="videobook.voice-provider";function qc(){try{const e=localStorage.getItem(pi);return e==="openai"||e==="xai"?e:"auto"}catch{return"auto"}}function h_(e){const t=ne.c(31),[n,o]=_.useState("off"),[r,i]=_.useState("Voice input + spoken replies");let s;t[0]===Symbol.for("react.memo_cache_sentinel")?(s=[],t[0]=s):s=t[0];const[a,c]=_.useState(s),[l,u]=_.useState(!1),[m,d]=_.useState(!1),[f,g]=_.useState(!1),[p,y]=_.useState(qc),[v,S]=_.useState(null),[w,k]=_.useState(),I=_.useRef(null),E=_.useRef(null),C=_.useRef(e);let A;t[1]!==e?(A=()=>{C.current=e},t[1]=e,t[2]=A):A=t[2],_.useLayoutEffect(A);let $;t[3]===Symbol.for("react.memo_cache_sentinel")?($=()=>()=>{const U=E.current;E.current=null,U?.stop("Workspace changed. Start voice to resume."),c([]),S(null),k(void 0),d(!1),g(!1)},t[3]=$):$=t[3];let T;t[4]!==e.available||t[5]!==e.bookId||t[6]!==e.notebookId||t[7]!==e.scope?(T=[e.bookId,e.notebookId,e.scope,e.available],t[4]=e.available,t[5]=e.bookId,t[6]=e.notebookId,t[7]=e.scope,t[8]=T):T=t[8],_.useLayoutEffect($,T);let N;t[9]===Symbol.for("react.memo_cache_sentinel")?(N=()=>{d(!1),g(!1),E.current?.stop(),o("off"),i("Comms off."),u(!1),S(null),k(void 0)},t[9]=N):N=t[9];const M=N;let R;t[10]!==p?(R=()=>{if(E.current?.active){M();return}const U=C.current;if(!U.available||U.disabled)return;S(null),k(void 0),g(!1),o("connecting"),i("Connecting voice");const ke=new Set,Q=new Vc({bookId:U.bookId,notebookId:U.notebookId,mode:p,onProvider:(B,P)=>{E.current===Q&&(S(B),k(P))},onPhase:(B,P)=>{E.current!==Q&&B!=="off"||(o(B),(B==="off"||B==="error")&&d(!1),B!=="thinking"&&g(!1),P&&i(P))},onRetrying:B=>{E.current===Q&&g(B)},onCaption:B=>{E.current===Q&&(B.role==="user"&&B.final&&B.text.trim()&&!ke.has(B.id)&&(ke.add(B.id),C.current.onUserTurn?.()),c(P=>{const Y=P.findIndex(we=>we.id===B.id);if(Y<0)return[...P,{...B,sequence:B.sequence??Bt()}].slice(-256);const Me=P[Y]?.sequence??B.sequence;return P.map(we=>we.id===B.id?{...B,sequence:Me}:we)}))},onAction:async B=>{if(E.current!==Q||C.current.scope!==U.scope||C.current.bookId!==U.bookId||C.current.notebookId!==U.notebookId||!C.current.available)return{status:"cancelled",message:"Workspace changed. Repeat the command in the current workspace."};d(!0);const P=()=>E.current===Q&&Q.active&&C.current.bookId===U.bookId&&C.current.notebookId===U.notebookId&&C.current.scope===U.scope&&C.current.available,Y=await C.current.onAction(B,P).catch(Bc);return E.current===Q&&d(Y.status==="review"),Y},onReviewCommand:async B=>{if(E.current!==Q)return{status:"cancelled",message:"Workspace changed. The review is no longer on screen."};const P=await C.current.onReviewCommand(B).catch(Uc);return E.current===Q&&d(P.status==="review"),P},onLevel:B=>I.current?.style.setProperty("--voice-level",String(B)),onPlaybackBlocked:u});E.current=Q,Q.start()},t[10]=p,t[11]=R):R=t[11];const D=R;let z;t[12]!==p?(z=U=>{if(U!==p){d(!1),g(!1),E.current?.stop("Voice provider changed. Start voice to connect."),y(U),S(null),k(void 0);try{localStorage.setItem(pi,U)}catch{return}}},t[12]=p,t[13]=z):z=t[13];const q=e.disabled||!e.available,J=n!=="off"&&n!=="error";let pe,ge,K;t[14]===Symbol.for("react.memo_cache_sentinel")?(K=()=>{E.current?.resumePlayback()},pe=U=>{U.status!=="review"&&d(!1),E.current?.reportOutcome(U)},ge=(U,ke)=>E.current?.shareTypedTurn(U,ke),t[14]=pe,t[15]=ge,t[16]=K):(pe=t[14],ge=t[15],K=t[16]);let H;return t[17]!==a||t[18]!==w||t[19]!==r||t[20]!==p||t[21]!==m||t[22]!==n||t[23]!==l||t[24]!==v||t[25]!==f||t[26]!==z||t[27]!==q||t[28]!==J||t[29]!==D?(H={phase:n,message:r,captions:a,playbackBlocked:l,pendingReview:m,retrying:f,meterRef:I,toggle:D,stop:M,mode:p,provider:v,fallbackReason:w,selectMode:z,disabled:q,active:J,resumePlayback:K,reportOutcome:pe,shareTypedTurn:ge},t[17]=a,t[18]=w,t[19]=r,t[20]=p,t[21]=m,t[22]=n,t[23]=l,t[24]=v,t[25]=f,t[26]=z,t[27]=q,t[28]=J,t[29]=D,t[30]=H):H=t[30],H}function Uc(e){return{status:"failed",message:e instanceof Error?e.message:"The review command failed."}}function Bc(e){return{status:"failed",message:e instanceof Error?e.message:"Voice action failed."}}async function Hc(e){const{revision:t,...n}=e,o=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(n)));return[...new Uint8Array(o)].map(r=>r.toString(16).padStart(2,"0")).join("")}const Wc=1;function gi(e){if(e.planVersion!==Wc)throw new Error(`Unsupported CommandPlan version: ${e.planVersion}`);if(e.stages.length===0)throw new Error("A CommandPlan requires a stage");for(const t of e.stages){if(t.kind==="edit"){if(t.intent.sourceSurface!==e.sourceSurface)throw new Error("Edit stage source surface must match its CommandPlan");if(t.intent.actor!==e.actor)throw new Error("Edit stage actor must match its CommandPlan")}if(t.kind==="queued"&&t.insertsOutput&&!t.continuation)throw new Error("Queued insert stages require a revision-pinned continuation");if(t.kind==="queued"&&t.jobType==="generation"&&(!t.provider||!t.model))throw new Error("Generation stages require provider and model disclosure");if(t.kind==="queued"&&t.jobType==="generation"&&t.estimatedCostUsd===void 0&&t.estimateUnavailable!==!0)throw new Error("Generation stages require a cost estimate or unavailable warning")}}function b_(e){const{bookId:t,call:n,sequence:o}=e,r=_.useMemo(()=>({bookId:t}),[t]),i=_.useRef({key:r,active:!0,pending:!1}),[s,a]=_.useState({scope:r,busy:!1,error:""}),c=o?.sequenceId,[l,u]=_.useState({sequenceId:c,frame:0,selectedClipId:null}),m=_.useCallback(w=>{u(k=>({sequenceId:c,frame:w,selectedClipId:k.sequenceId===c?k.selectedClipId:null}))},[c]),[d,f]=_.useState(null),g=_.useRef(0);_.useEffect(()=>{const w={key:r,active:!0,pending:!1};return i.current=w,()=>{w.active=!1}},[r]);async function p(w){const k=i.current;if(!e.ready||k.key!==r||!k.active||k.pending)return;const I=()=>k.active&&i.current===k;k.pending=!0,a({scope:r,busy:!0,error:""});try{await w(I),I()&&a({scope:r,busy:!1,error:""})}catch(E){I()&&a({scope:r,busy:!1,error:E instanceof Error?E.message:String(E)})}finally{k.pending=!1}}async function y(w,k,I){const E=++g.current;await p(async C=>{const A=o?.tracks.find(R=>R.trackId===w);if(!A)throw new Error("The track is no longer available");const $=await n("list_assets",{book_id:t,browse_status:"ready",sort:"newest",offset:k,limit:100},{background:!0});if(!C()||E!==g.current)return;const T=e.parseAssets($);e.onAssets(T);const N=T.filter(R=>R.mediaUrl&&R.status==="ready"&&(A.kind==="audio"?R.type==="audio":R.type==="video"||R.type==="final")),M=h(h($)?.page);f(R=>({scope:r,trackId:w,items:I&&R?.scope===r&&R.trackId===w?[...R.items,...N]:N,offset:M?.hasMore===!0?k+100:null}))})}async function v(w){await p(async k=>{if(!o)throw new Error("The timeline is not ready");const I=await n("plan_sequence_edit",{book_id:t,source_surface:"ui",actor:"videobook-user",expected_revision:await Hc(o),edits:[w]});if(gi(I),!k())return;const E=I.stages.find(T=>T.kind==="edit");if(!E||E.kind!=="edit")throw new Error("The timeline plan has no edit");const C=await n("preview_edit_intent",{book_id:t,intent:E.intent});if(!C.valid)throw new Error(C.conflicts.map(T=>T.message).join(" · ")||"The timeline changed. Try again.");if(!k())return;const A=h(await n("commit_edit_intent",{book_id:t,intent:E.intent,preview_hash:C.previewHash})),$=e.parseSequence(A?.sequence);if(!$)throw new Error("The server returned an invalid timeline");k()&&(e.onSequence($),f(null))})}async function S(w,k){await p(async I=>{const E=e.parseSequence(await n(w,{book_id:t,...k}));if(!E)throw new Error("The server returned an invalid timeline");I()&&e.onSequence(E)})}return{frame:l.sequenceId===c?l.frame:0,selectedClipId:l.sequenceId===c?l.selectedClipId:null,seek:m,selectClip:w=>u(k=>({sequenceId:c,frame:k.sequenceId===c?k.frame:0,selectedClipId:w})),busy:s.scope===r&&s.busy,error:s.scope===r?s.error:"",picker:d?.scope===r?d:null,openPicker:w=>y(w,0,!1),loadMore:()=>d?.offset!==null&&d?y(d.trackId,d.offset,!0):Promise.resolve(),closePicker:()=>{g.current+=1,f(null)},append:(w,k)=>v({kind:"append",track_id:w,artifact_id:k}),removeClip:w=>v({kind:"remove_clip",clip_id:w,ripple:!0}),addTrack:()=>S("add_sequence_track",{kind:"audio"}),removeTrack:w=>S("remove_sequence_track",{track_id:w})}}const Vo=te({timeSeconds:V().finite().nonnegative(),confidence:V().min(0).max(1).nullable()}),Kc=te({algorithmId:j().min(1),algorithmVersion:j().min(1),hopSeconds:V().finite().positive(),values:ae(V().finite().min(0).max(1)).max(2e4)}),zc=te({id:j().min(1).max(100),timeSeconds:V().finite().nonnegative().max(3600),quality:V().min(0).max(1)}),Xc=te({algorithmId:j().min(1),algorithmVersion:j().min(1),candidates:ae(zc).max(200)}),Yc=te({analysisId:j(),artifactId:j().uuid(),objectHash:j(),streamId:j().uuid(),durationSeconds:V().finite().positive().max(3600),analyzerVersion:j(),beats:ae(Vo).max(24e3),bpm:V().finite().positive().nullable(),confidence:V().min(0).max(1).nullable(),bars:ae(Vo).max(24e3).nullable(),beatsPerBar:V().int().min(1).max(16).nullable(),barSource:Xe(["detected","estimated"]).nullable().default(null),waveform:ae(V().finite().min(0).max(1)).max(65536),lowConfidence:Te(),energy:Kc.nullable().default(null),sections:Xc.nullable().default(null)}),Jc=["intro","verse","chorus","drop","break","bridge","outro"];te({schemaVersion:Zr(1),analysisId:j(),artifactId:j().uuid(),objectHash:j(),streamId:j().uuid(),labeler:te({id:j(),version:j(),model:j()}),boundaries:te({algorithmId:j(),algorithmVersion:j()}),status:Xe(["ready","unavailable"]),reason:j().nullable().default(null),createdAt:V().finite().positive(),labels:ae(te({candidateId:j().min(1).max(100),label:Xe(Jc),confidence:V().min(0).max(1),rationale:j().max(500)})).max(200).default([])});const Zc=te({id:j().min(1).max(100),timeSeconds:V().finite().nonnegative().max(3600),bar:Te(),manual:Te()}),Qc=te({masterClipId:j().uuid().nullable(),correction:te({objectHash:j(),analysisId:j().nullable(),markers:ae(Zc).max(24e3),bpm:V().finite().min(20).max(400).nullable(),beatsPerBar:V().int().min(1).max(16).nullable()}).nullable()});function gn(e,t){const n=new Set(e.tracks.filter(r=>r.kind==="audio").map(r=>r.trackId)),o=e.clips.filter(r=>n.has(r.trackId)&&r.source.kind==="timed");return(t.masterClipId?o.find(r=>r.clipId===t.masterClipId):o.length===1?o[0]:null)??null}function el(e,t,n){if(!e)return[];if(t.correction)return t.correction.objectHash===e.source.range.objectHash?t.correction.markers:[];if(!n||n.objectHash!==e.source.range.objectHash||n.streamId!==e.source.range.streamId)return[];const o=new Set(n.bars?.map(r=>Math.round(r.timeSeconds*1e6)));return n.beats.map((r,i)=>({id:`${n.analysisId.slice(0,12)}-${i}`,timeSeconds:r.timeSeconds,bar:o.has(Math.round(r.timeSeconds*1e6)),manual:!1}))}function tl(e,t){if(!e.length)return[];const n=t!==null&&Number.isFinite(t)&&t>0?60/t:null,o=[0];for(let r=1;r<e.length;r+=1){const i=e[r].timeSeconds-e[r-1].timeSeconds;o.push(o[r-1]+(n===null?1:Math.max(1,Math.round(i/n))))}return o}function y_(e,t,n,o){const r=[...e].sort((a,c)=>a.timeSeconds-c.timeSeconds),i=r.findIndex(a=>a.id===t);if(i<0||!Number.isInteger(n)||n<1||n>16)throw new Error("Choose a first bar beat and 1–16 beats per bar");const s=tl(r,o);return r.map((a,c)=>({...a,bar:(s[c]-s[i])%n===0,manual:!0}))}function jo(e,t,n){const o=e.source.range,r=o.timeBase.numerator/o.timeBase.denominator,i=(t-e.timelineStartFrame)/n*e.speed.numerator/e.speed.denominator;return e.reverse?(o.startTick+o.durationTicks)*r-i:o.startTick*r+i}function nl(e,t,n){const o=e.source.range,r=o.timeBase.numerator/o.timeBase.denominator,i=e.reverse?(o.startTick+o.durationTicks)*r-t:t-o.startTick*r;return Math.round(e.timelineStartFrame+i*n*e.speed.denominator/e.speed.numerator)}function ol(e,t,n){if(!e||!e.enabled)return[];const o=n.frameRate.numerator/n.frameRate.denominator,r=e.source.range,i=r.timeBase.numerator/r.timeBase.denominator,s=r.startTick*i,a=(r.startTick+r.durationTicks)*i,c=new Set;return t.filter(l=>l.timeSeconds>=s&&l.timeSeconds<a).map(l=>({...l,frame:nl(e,l.timeSeconds,o)})).filter(l=>l.frame>=e.timelineStartFrame&&l.frame<e.timelineStartFrame+e.durationFrames).sort((l,u)=>l.frame-u.frame||Number(u.bar)-Number(l.bar)).filter(l=>c.has(l.frame)?!1:(c.add(l.frame),!0))}function __(e,t,n,o=1/0){if(n==="off")return Math.round(e);let r=Math.round(e),i=o;for(const s of t){if(n==="bars"&&!s.bar)continue;const a=Math.abs(s.frame-e);(a<i||a===i&&s.frame<r)&&(r=s.frame,i=a)}return r}function v_(e,t,n,o,r=256){if(e.source.kind!=="timed"||!n||!t.length)return[];const i=e;return Array.from({length:r},(s,a)=>{const c=jo(i,e.timelineStartFrame+a/r*e.durationFrames,o),l=jo(i,e.timelineStartFrame+(a+1)/r*e.durationFrames,o),u=Math.max(0,Math.floor(Math.min(c,l)/n*t.length)),m=Math.min(t.length,Math.max(u+1,Math.ceil(Math.max(c,l)/n*t.length)));let d=0;for(let f=u;f<m;f++)d=Math.max(d,t[f]??0);return d})}const Go={revision:"none",settings:{masterClipId:null,correction:null},canUndo:!1,canRedo:!1};function qo(e){const t=h(e);if(!t||typeof t.revision!="string")throw new Error("Invalid beat map response");return{revision:t.revision,settings:Qc.parse(t.settings),canUndo:t.canUndo===!0,canRedo:t.canRedo===!0}}function Uo(e){const t=h(e);if(!t||typeof t.status!="string"||!["missing","queued","analyzing","ready","no-beats","cancelled","failed"].includes(t.status))throw new Error("Invalid music analysis response");return{status:t.status,analysisId:String(t.analysisId),jobId:typeof t.jobId=="number"?t.jobId:null,error:typeof t.error=="string"?t.error:null,analysis:t.analysis?Yc.parse(t.analysis):null}}function k_({bookId:e,ready:t,sequence:n,call:o,onSequence:r}){const i=`${e}:${n?.sequenceId??""}`,s=_.useRef(0),[a,c]=_.useState({scope:i,rhythm:Go,analysis:null}),[l,u]=_.useState({scope:i,busy:!1,error:""});_.useEffect(()=>()=>{s.current+=1},[i]);const m=a.scope===i?a.rhythm:Go,d=n?gn(n,m.settings):null,f=a.scope===i&&a.analysis?.analysis?.artifactId===d?.source.artifactId?a.analysis?.analysis??null:null,g=_.useMemo(()=>el(d,m.settings,f),[d,m.settings,f]),p=_.useMemo(()=>n?ol(d,g,n):[],[d,g,n]),y=a.scope===i?a.analysis?.status??"missing":"missing";async function v(A,$=n){if(!$)return null;const T=gn($,A);return T?Uo(await o("get_music_analysis",{book_id:e,asset_id:T.source.artifactId,stream_id:T.source.range.streamId},{background:!0})):null}function S(A,$){const T=gn($,A.settings)?.source;c(N=>{const M=N.scope===i?N.analysis:null,R=M?.analysis&&T&&M.analysis.artifactId===T.artifactId&&M.analysis.objectHash===T.range.objectHash&&M.analysis.streamId===T.range.streamId;return{scope:i,rhythm:A,analysis:R?M:null}})}async function w(A,$,T){for(;A===s.current;){if(c({scope:i,rhythm:$,analysis:T}),u({scope:i,busy:!1,error:""}),T?.status!=="queued"&&T?.status!=="analyzing"||(await new Promise(N=>setTimeout(N,1e3)),A!==s.current))return;T=await v($.settings)}}async function k(){if(!t||!n)return;const A=++s.current;u({scope:i,busy:!0,error:""});try{const $=qo(await o("get_sequence_rhythm",{book_id:e,sequence_id:n.sequenceId},{background:!0}));if(A!==s.current)return;S($,n);const T=await v($.settings);await w(A,$,T)}catch($){A===s.current&&u({scope:i,busy:!1,error:$ instanceof Error?$.message:String($)});return}A===s.current&&u({scope:i,busy:!1,error:""})}async function I(A,$=n){if(!t||!$)return;const T=++s.current;u({scope:i,busy:!0,error:""});try{const N=h(await o("update_sequence_rhythm",{book_id:e,sequence_id:$.sequenceId,expected_revision:m.revision,operation:typeof A=="string"?A:"set",...typeof A=="string"?{}:{settings:A}},{background:!0}));if(T!==s.current)return;const M=qo(N?.state);S(M,$),r(N?.sequence);const R=await v(M.settings,$);await w(T,M,R)}catch(N){T===s.current&&u({scope:i,busy:!1,error:N instanceof Error?N.message:String(N)});return}T===s.current&&u({scope:i,busy:!1,error:""})}async function E(A=!1){if(!t||!d)return;const $=++s.current;u({scope:i,busy:!0,error:""});const T={book_id:e,asset_id:d.source.artifactId,stream_id:d.source.range.streamId};try{const N=Uo(await o("analyze_music",{...T,force:A},{background:!0}));await w($,m,N)}catch(N){$===s.current&&u({scope:i,busy:!1,error:N instanceof Error?N.message:String(N)})}}async function C(){if(!(!t||a.scope!==i||!a.analysis?.jobId)){s.current+=1;try{await o("cancel_job",{book_id:e,job_id:a.analysis.jobId},{background:!0}),await k()}catch(A){u({scope:i,busy:!1,error:A instanceof Error?A.message:String(A)})}}}return{rhythm:m,master:d,analysis:f,markers:g,mapped:p,status:y,load:k,save:I,analyze:E,cancel:C,stop:()=>{s.current+=1},busy:!t||l.scope===i&&l.busy,error:l.scope===i&&(l.error||a.analysis?.error)||""}}const Fn=[{kind:"cell.outputArtifact",one:"notebook cell",many:"notebook cells"},{kind:"cell.reference",one:"cell reference",many:"cell references"},{kind:"sequenceClip",one:"sequence clip",many:"sequence clips"},{kind:"pinnedSearchResult",one:"pinned result",many:"pinned results"},{kind:"stream",one:"media stream",many:"media streams"},{kind:"transcript",one:"transcript",many:"transcripts"},{kind:"captionCue",one:"caption cue",many:"caption cues"}];function rl(e,t){const n=Fn.find(o=>o.kind===e);return n?`${t} ${t===1?n.one:n.many}`:`${t} ${e}`}function il(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function sl(e){const t=new Map;for(const r of e)t.set(r.kind,(t.get(r.kind)??0)+1);const o=[...Fn.filter(r=>t.has(r.kind)).map(r=>r.kind),...[...t.keys()].filter(r=>!Fn.some(i=>i.kind===r))].map(r=>rl(r,t.get(r)??0));return o.length>0?il(o):"something else in this book"}function al(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"],n=Math.min(t.length-1,Math.floor(Math.log(e)/Math.log(1024))),o=e/1024**n;return`${n===0||o>=100?Math.round(o):Math.round(o*10)/10} ${t[n]}`}function w_(e,t){const n=[t.reclaimedBytes>0?`${al(t.reclaimedBytes)} reclaimed`:"",t.sharedObjects>0?`${t.sharedObjects} file${t.sharedObjects===1?"":"s"} kept for another asset`:"",t.clearedCells>0?`cleared ${t.clearedCells} cell${t.clearedCells===1?"":"s"}`:""].filter(o=>o!=="");return n.length>0?`Forgot ${e} · ${n.join(" · ")}`:`Forgot ${e}`}function S_(e){return`Forget ${e}?
7
+
8
+ This deletes the asset and destroys its stored content. Files shared with another asset are kept. This cannot be undone.`}function I_(e,t){return`${e} is still used by ${sl(t)}.
9
+
10
+ Clear those references and forget it anyway?`}const cl=[{label:"no people",aliases:["empty","unpopulated","nobody","no one"]},{label:"solo subject",aliases:["one person","single person","solo","individual"]},{label:"two people",aliases:["pair","couple","duo","two subjects"]},{label:"small group",aliases:["group","three people","few people","small gathering"]},{label:"crowd",aliases:["crowded","many people","audience","large group"]},{label:"interviewer",aliases:["questioner"]},{label:"interviewee",aliases:["subject being interviewed","respondent"]},{label:"presenter",aliases:["host"]}],ll=[{label:"interior",aliases:["indoors","inside","indoor"]},{label:"exterior",aliases:["outdoors","outside","outdoor"]},{label:"day",aliases:["daytime","daylight","morning","afternoon"]},{label:"night",aliases:["nighttime","after dark","evening"]},{label:"kitchen",aliases:["galley"]},{label:"street",aliases:["sidewalk","roadside","city street"]},{label:"studio",aliases:["soundstage"]},{label:"office",aliases:["workplace"]},{label:"bedroom",aliases:[]},{label:"living room",aliases:["lounge"]},{label:"restaurant",aliases:["cafe","diner","bar"]},{label:"store",aliases:["shop","market","supermarket"]},{label:"car",aliases:["vehicle interior"]},{label:"beach",aliases:["shore","seaside"]},{label:"park",aliases:["garden"]},{label:"forest",aliases:["woods","woodland"]},{label:"stage",aliases:["venue","concert stage"]},{label:"gym",aliases:["fitness studio"]},{label:"rooftop",aliases:["roof"]}],ul=[{label:"wide shot",aliases:["wide","long shot","full shot","establishing wide"]},{label:"medium shot",aliases:["medium","mid shot","waist up"]},{label:"close-up",aliases:["close up","closeup","tight shot","cu"]},{label:"extreme close-up",aliases:["extreme close up","extreme closeup","macro shot"]},{label:"establishing shot",aliases:["establishing","scene setter"]},{label:"insert",aliases:["insert shot","cutaway","detail shot"]},{label:"product shot",aliases:["product","packshot"]},{label:"static",aliases:["locked off","tripod","still camera","fixed camera"]},{label:"pan",aliases:["panning","whip pan"]},{label:"tilt",aliases:["tilting"]},{label:"handheld",aliases:["hand held","shaky","run and gun"]},{label:"tracking",aliases:["dolly","steadicam","follow shot","tracking shot"]},{label:"interview",aliases:["sit down interview"]},{label:"talking head",aliases:[]},{label:"dialogue",aliases:["conversation","speech","talking"]},{label:"ambience",aliases:["ambient","room tone","atmosphere","background sound"]},{label:"music",aliases:["musical","score","soundtrack"]},{label:"voiceover",aliases:["voice over","narration","narrator"]}],dl={people:cl,places:ll,editing:ul,custom:[]},Bo=new Set(["beautiful","stunning","amazing","gorgeous","great","good","nice","cool","epic","dramatic","moody","vibe","vibes","aesthetic","mood","cinematic","masterpiece","high quality","professional","hd","4k","video","footage","clip","content","scene","shot","media","image","photo","picture","frame","camera","misc","other","general","interesting","modern","classic","colorful","bright","dark","atmospheric","emotional","energetic","calm","peaceful","happy","sad"]);function hi(e){return e.normalize("NFKC").toLowerCase().replace(/[_/]+/gu," ").replace(/[^\p{L}\p{N}\s-]+/gu,"").replace(/\s+/gu," ").trim()}const fl=new Map(Object.entries(dl).flatMap(([e,t])=>t.flatMap(n=>[n.label,...n.aliases].map(o=>[`${e}:${hi(o)}`,{facet:e,label:n.label}]))));function bi(e,t=[]){const n=Fs(e.label),o=Ft(n),r=e.facet?[e.facet]:["people","places","editing"];for(const s of r){const a=pl(s,n);if(a)return{...a,label:Ft(a.label)===o?n:a.label}}const i=!e.facet&&t.find(s=>Ft(s.label)===o);return{facet:e.facet??(i?i.facet:"custom"),label:n}}function ml(e){if(Bo.has(e))return!1;const t=e.split(" ");return t.length===0||t.length>2?!1:t.every(n=>n.length>=3&&n.length<=20&&/^[\p{L}-]+$/u.test(n)&&!Bo.has(n)&&!["not","without","never","maybe","possibly"].includes(n))}function pl(e,t,n={}){const o=hi(t);if(!o||o.length>40)return null;const r=fl.get(`${e}:${o}`);return r||(n.allowUnlisted&&e==="places"&&ml(o)?{facet:e,label:o}:null)}const gl={effective:[],manual:[],automatic:[],dismissed:[],analysis:null,fingerprint:""};function so(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function Re(e){return typeof e=="string"&&e.trim()?e:null}function hl(e){return typeof e=="string"&&Wr.includes(e)?e:null}function Vt(e){const t=so(e),n=hl(t?.facet),o=Re(t?.key),r=Re(t?.label);return!t||!n||!o||!r?null:{facet:n,key:o,label:r,origin:t.origin==="automatic"?"automatic":"manual",entityId:Re(t.entity_id??t.entityId)}}function bl(e){const t=Vt(e);return t?{facet:t.facet,key:t.key,label:t.label}:null}function At(e,t){return Array.isArray(e)?e.flatMap(n=>{const o=t(n);return o?[o]:[]}):[]}function yl(e){const t=so(e),n=Re(t?.source_hash??t?.sourceHash),o=Re(t?.generator),r=Re(t?.extractor_version??t?.extractorVersion);if(!t||!n||!o||!r)return null;const i=Number(t.tag_count??t.tagCount),s=Number(t.analyzed_at??t.analyzedAt);return{sourceHash:n,generator:o,model:Re(t.model),extractorVersion:r,tagCount:Number.isFinite(i)?i:0,analyzedAt:Number.isFinite(s)?s:0,stale:t.stale===!0}}function yi(e){const t=so(e);return t?{effective:At(t.effective,Vt),manual:At(t.manual,Vt),automatic:At(t.automatic,Vt),dismissed:At(t.dismissed,bl),analysis:yl(t.analysis),fingerprint:Re(t.fingerprint)??""}:null}function hn(e){const t=new Map(Wr.map((n,o)=>[n,o]));return[...e].sort((n,o)=>(t.get(n.facet)??0)-(t.get(o.facet)??0)||n.label.localeCompare(o.label))}function _i(e,t){return`${e}/${t}`}function _l(e){return e.trim()?Ft(e):""}function le(e){return _i(e.facet,e.key)}function x_(e){return e.origin==="manual"?"Added by you":"From analysis"}function qe(e,t){return e.filter(n=>le(n)!==t)}function Ho(e,t,n){const o=e??gl;if(!t.label.trim())return o;t=bi(t,[...o.effective,...o.dismissed]);const r=_l(t.label);if(!r)return o;const i=t.facet??"custom",s=_i(i,r);if(n==="add"){if(o.manual.some(u=>le(u)===s))return o;const l={facet:i,key:r,label:t.label.trim(),origin:"manual",entityId:null};return{...o,dismissed:qe(o.dismissed,s),manual:hn([...o.manual,l]),effective:hn([...qe(o.effective,s),l])}}if(n==="remove"){const l=o.effective.find(m=>le(m)===s);if(!l)return o;const u=[{facet:l.facet,key:l.key,label:l.label}];return{...o,effective:qe(o.effective,s),manual:qe(o.manual,s),dismissed:[...qe(o.dismissed,s),...u]}}if(!o.dismissed.find(l=>le(l)===s))return o;const c=o.automatic.find(l=>le(l)===s);return{...o,dismissed:qe(o.dismissed,s),effective:c?hn([...o.effective,c]):o.effective}}function A_(e,t){const n=le(t);return e.some(r=>le(r)===n)?e.filter(r=>le(r)!==n):[...e,t]}function E_(e){return{facet:e.facet,key:e.key,label:e.label}}function C_(e){return e.length===0?{}:{tags_all:e.map(t=>({facet:t.facet,label:t.label}))}}function M_(e,t){if(e.length!==t.length)return!1;const n=new Set(e.map(le));return t.every(o=>n.has(le(o)))}function vl(e,t,n=8){const o=new Set(t.map(le));return e.filter(r=>!o.has(le(r))).slice(0,n)}const T_={calls:[]},R_=420,Wo=140,Ko=400,kl={chat:"Routing chat",chain:"Running chained actions",list_chat_models:"Loading chat models",list_prompt_history:"Loading prompt history",plan_chat_command:"Planning chat command",record_prompt:"Saving prompt",slash_commands:"Loading commands"},wl=new Set(["get_notebook","list_chat_models","list_jobs","list_prompt_history","list_workspace_actions","slash_commands"]);function $_(e){return!wl.has(e)}function N_(e){const t=kl[e];return t||e.split("_").filter(Boolean).map(n=>n[0]?.toUpperCase()+n.slice(1)).join(" ")}function Ht(e,t){const n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t)}… (${n.length} chars)`}function Sl(e){if(typeof e=="string")return Ht(e,Wo);if(typeof e=="number"||typeof e=="boolean")return String(e);try{return Ht(JSON.stringify(e)??String(e),Wo)}catch{return String(e)}}function P_(e){return Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>({name:t,value:Sl(n)}))}function O_(e){if(typeof e=="string")return Ht(e,Ko);if(Array.isArray(e))return e.length===1?"1 item":`${e.length} items`;if(!e||typeof e!="object")return"";const t=e;for(const n of["message","error","status"])if(typeof t[n]=="string"&&t[n])return Ht(t[n],Ko);return""}function Il(e){const t=Math.max(0,e);return t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}m ${Math.round(t%6e4/1e3)}s`}function L_(e){return e.phase==="running"?"working":e.phase==="failed"?"failed":Il(e.elapsedMs)}function F_(e,t){const n={id:t.id,...t.turnId===void 0?{}:{turnId:t.turnId},tool:t.tool,args:t.args,phase:"running",elapsedMs:0,detail:"",expanded:!1};return{calls:[...e.calls,n].slice(-256)}}function D_(e,t,n){return e.calls.some(o=>o.id===t)?{calls:e.calls.map(o=>o.id===t?{...o,phase:n.phase,elapsedMs:n.elapsedMs,detail:n.detail}:o)}:e}function V_(e,t){return e.calls.some(n=>n.id===t)?{calls:e.calls.map(n=>n.id===t?{...n,expanded:!n.expanded}:n)}:e}function j_(e){return e.calls.filter(t=>t.phase==="running").length}function G_(e){switch(e){case"connecting":return"Opening your voice channel…";case"listening":return"Listening… speak anytime.";case"thinking":return"Transcribing…";case"speaking":return"Waiting for captions…";case"review":return"Review is on screen.";case"error":return"No captions. Voice could not connect.";case"off":return"No captions this session."}}function q_(e,t){const n=new Map(e.map(i=>[ue(i.slot),i])),o=new Map(t.map(i=>[i.artifactId,i])),r=new Map;for(let i=0;i<de;i+=1)for(let s=0;s<X;s+=1){const a=ue({row:i,column:s}),c=n.get(a),l=c?.outputArtifactId?o.get(c.outputArtifactId)??null:null,u=c?.label?.trim()||l?.label?.trim()||null;r.set(a,{token:a,cellId:c?.id??null,label:u===l?.artifactId?null:u,type:l?.type??c?.type??"empty",status:l?.status??(c?.outputArtifactId?"missing":c?.status??(c?"":"empty")),asset:l})}return r}function U_(e){if(e.type==="empty")return"Empty grid square";const t=[e.type.replaceAll("_"," ").toUpperCase()],n=e.asset?.duration;return n&&Number.isFinite(n)&&n>0&&t.push(me(n)),e.status&&e.status!=="ready"&&t.push(e.status.replaceAll("_"," ")),t.join(" · ")}function vi(e,t=e.length,n=t){if(t!==n)return null;const o=Qt(e.slice(0,t));if(o===void 0)return null;let r=t;for(;r<e.length&&/[a-z0-9]/iu.test(e[r]);)r+=1;return{start:t-o.length-1,end:r,prefix:o}}function B_(e,t,n=t.length,o=n,r){const i=vi(t,n,o);return i?[...e.values()].filter(s=>s.token.slice(1).includes(i.prefix)&&(!r||!!(s.asset&&r.has(s.asset.artifactId)))).slice(0,12):[]}function H_(e,t,n=e.length,o=n){const r=vi(e,n,o);if(!r)return null;const i=`@${ve(t)}`,s=e.slice(r.end),a=!s||/^[\p{L}\p{N}@]/u.test(s)?" ":"";return{value:`${e.slice(0,r.start)}${i}${a}${s}`,caret:r.start+i.length+(a||s.startsWith(" ")?1:0)}}function W_(e,t,n){const o=t&&n?t/n:1.7777777777777777,[r=1,i=1]=e.split(":").map(Number),s=r/i,a=Math.min(1,s/o),c=Math.min(1,o/s);return{ratio:e,x:(1-a)/2,y:(1-c)/2,w:a,h:c}}function K_(e){return e.handler.kind==="tool"&&["list_entities","list_notebooks","asset_history","list_book_actions","search_archive"].includes(e.handler.tool)}function ao(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function z_(e){const t=ao(e);if(!Array.isArray(t?.actions)||!Array.isArray(t.tools))throw new Error("The action catalog could not be loaded. Reconnect and try again.");return e}function X_(e,t){const n=new Set(e.flatMap(i=>[i.command,...i.aliases]).map(i=>i.toLowerCase())),o=t.filter(i=>i.category!=="project"||!n.has(i.command.toLowerCase())),r=new Set(o.flatMap(i=>[i.command,...i.aliases??[]]).map(i=>i.toLowerCase()));return[...o,...e.filter(i=>!r.has(i.command.toLowerCase())).map(i=>({command:i.command,description:i.description,aliases:i.aliases,workspaceActionId:i.id,category:"action",icon:"Play",size:"default",variant:"default",chevron:"right",params:Object.entries(i.inputSchema.properties??{}).filter(([s])=>s!=="book_id").map(([s,a])=>({name:s,description:a.description??xl(s),required:i.inputSchema.required?.includes(s)??!1,type:a.type==="number"||a.type==="integer"?"number":a.type==="boolean"?"boolean":"string"}))}))]}function Y_(e,t){return t?[...e,...["apply","cancel"].map(n=>({command:`/${n}`,description:n==="apply"?"Apply the reviewed action":"Cancel the pending action",category:"action",icon:n==="apply"?"Check":"X",size:"default",variant:"default",chevron:"right",params:[]}))]:[...e]}function xl(e){const t=e.replace(/([a-z])([A-Z])/gu,"$1 $2").replaceAll(/[_-]/gu," ").replace(/\b(?:artifact|asset) (?:id|ref)\b/gu,"media").replace(/\bbook id\b/gu,"project").replace(/\b(notebook|cell|clip|track|entity) id\b/gu,"$1").replace(/\brefs\b/gu,"references").replace(/\bdb\b/gu,"dB");return t.charAt(0).toUpperCase()+t.slice(1)}function ki(e){const t=e.oneOf??e.anyOf;return t?t.flatMap(n=>{const o=ki(n);return o.length?o:[n]}):[]}function Al(e,t){if("const"in e)return e.const===t;if(e.enum)return e.enum.includes(t);if(e.type==="null")return t===null;if(e.type==="array")return Array.isArray(t);if(e.type==="object"){const n=ao(t);return n?Object.entries(e.properties??{}).every(([o,r])=>!("const"in r)||r.const===n[o]):!1}return e.type==="integer"?Number.isInteger(t):!e.type||typeof t===e.type}function El(e,t){const n=ki(e);if(!n.length)return e;const o=n.find(a=>Al(a,t))??n.find(a=>a.type!=="null")??n[0],{anyOf:r,oneOf:i,...s}=e;return{...s,...o}}function Dn(e,t=!1){if("const"in e)return e.const;if(e.default!==void 0)return structuredClone(e.default);if(!t)return;const n=El(e,void 0);if("const"in n)return n.const;if(n.type==="object"){const o=new Set(n.required??[]);return Object.fromEntries(Object.entries(n.properties??{}).map(([r,i])=>[r,Dn(i,o.has(r))]).filter(([,r])=>r!==void 0))}if(n.type==="array")return Array.from({length:n.minItems??0},()=>Dn(n.items??{},!0));if(n.enum?.length===1)return n.enum[0];if(n.type==="boolean")return!1;if(n.type==="null")return null}function J_(e,t){const n=ao(Dn(e.inputSchema,!0))??{},o=e.inputSchema.properties??{},r={...n,...e.initialArgs};o._provider&&e.generation&&(r._provider=e.generation.provider);for(const[i,s]of[["book_id",t.bookId],["notebook_id",t.notebookId],["sequence_id",t.sequenceId],["cell_id",t.cellId],["base_revision",t.sequenceRevision],["sequence_revision",t.sequenceRevision],["source_surface","ui"],["actor","videobook-user"]])s&&o[i]&&(r[i]=s);if(e.target.kind==="asset"&&e.target.argument&&t.assetId){const i=t.choices.asset_id?.find(s=>s.value===t.assetId)?.detail;(!e.target.mediaKinds||e.target.mediaKinds.some(s=>s===i))&&(r[e.target.argument]=e.target.multiple?t.assetIds??[t.assetId]:t.assetId)}return e.target.kind==="cell"&&e.target.multiple&&e.target.argument&&t.cellIds?.length&&(r[e.target.argument]=t.cellIds),e.target.kind==="cell"&&!e.target.multiple&&e.target.argument&&t.cellId&&(r[e.target.argument]=t.cellId),o.object_hash&&t.assetId&&t.media?.[t.assetId]?.objectHash&&(r.object_hash=t.media[t.assetId].objectHash),r}function Z_(e,t){return e.scope!=="global"&&!t.bookId?"Open or create a project first.":e.scope==="notebook"&&!t.notebookId?"Open a notebook first.":e.scope==="sequence"&&!t.sequenceId?"Open a project with a sequence first.":null}function Q_(e,t){const n=t.trim().toLowerCase().replace(/^\//u,"").split(/\s+/u).filter(Boolean);return e.filter(o=>{const r=[o.title,o.command,o.description,o.group,...o.aliases,...o.keywords].join(" ").toLowerCase();return n.every(i=>r.includes(i))}).sort((o,r)=>{const i=s=>[s.command,...s.aliases].some(a=>a.replace(/^\//u,"").toLowerCase()===n.join(" "));return Number(i(r))-Number(i(o))||o.group.localeCompare(r.group)||o.title.localeCompare(r.title)})}const Et=new Ds({nodes:{doc:{content:"inline*"},text:{group:"inline"},reference:{inline:!0,group:"inline",atom:!0,selectable:!0,attrs:{token:{}},leafText:e=>String(e.attrs.token),toDOM:e=>["span",{"data-reference":String(e.attrs.token),contenteditable:"false"},String(e.attrs.token)],parseDOM:[{tag:"span[data-reference]",getAttrs:e=>{const t=e.getAttribute("data-reference")??"";return Kr(t)?{token:t}:!1}}]}}});function Cl(e,t=!0){const n=[];let o=0;if(t)for(const r of to(e))r.index>o&&n.push(Et.text(e.slice(o,r.index))),n.push(Et.nodes.reference.create({token:r.raw})),o=r.end;return o<e.length&&n.push(Et.text(e.slice(o))),Et.nodes.doc.create(null,n)}function zo(e,t=0,n=e.content.size){return e.textBetween(t,n,"",o=>String(o.attrs.token??""))}function ev(e,t,n){return{start:zo(e,0,Math.min(t,n)).length,end:zo(e,0,Math.max(t,n)).length,backward:t>n}}function Xo(e,t,n=1){let o=0,r=e.content.size;return e.forEach((i,s)=>{const a=i.isText?i.text.length:String(i.attrs.token??"").length;t>=o&&t<=o+a&&(r=i.isText?s+t-o:t===o||t<o+a&&n<0?s:s+i.nodeSize),o+=a}),Math.max(0,Math.min(e.content.size,r))}function Ml(e,t,n=1){const o=Xo(e.doc,t.start,t.start===t.end?n:-1),r=Xo(e.doc,t.end,n);return e.setSelection(Vs.create(e.doc,t.backward?r:o,t.backward?o:r))}function tv(e,t,n,o=!0){const r=Cl(t,o),i=e.doc.content.findDiffStart(r.content);if(i!==null){const s=e.doc.content.findDiffEnd(r.content),a=Math.max(0,i-Math.min(s.a,s.b));e.replaceWith(i,s.a+a,r.content.cut(i,s.b+a))}return Ml(e,n)}function Ct(e,t,n,o){const r=e.slice(0,t)+o+e.slice(n),i=t+o.length;return{value:r,selectionStart:i,selectionEnd:i}}function Yo(e,t){return e.lastIndexOf(`
11
+ `,Math.max(0,t-1))+1}function Jo(e,t){const n=e.indexOf(`
12
+ `,t);return n===-1?e.length:n}function Zo(e,t){let n=t;for(;n>0&&/\s/.test(e[n-1]);)n-=1;for(;n>0&&!/\s/.test(e[n-1]);)n-=1;return n}function Tl(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]);)n+=1;for(;n<e.length&&!/\s/.test(e[n]);)n+=1;return n}function nv(e){const{value:t,selectionStart:n,selectionEnd:o,key:r,ctrlKey:i,altKey:s,yankText:a}=e,c=r.toLowerCase();if(s&&c==="b"){const l=Zo(t,n);return{value:t,selectionStart:l,selectionEnd:l}}if(s&&c==="f"){const l=Tl(t,o);return{value:t,selectionStart:l,selectionEnd:l}}if(!i)return null;if(c==="a"){const l=Yo(t,n);return{value:t,selectionStart:l,selectionEnd:l}}if(c==="e"){const l=Jo(t,o);return{value:t,selectionStart:l,selectionEnd:l}}if(c==="b"){const l=Math.max(0,n-1);return{value:t,selectionStart:l,selectionEnd:l}}if(c==="f"){const l=Math.min(t.length,o+1);return{value:t,selectionStart:l,selectionEnd:l}}if(c==="y")return Ct(t,n,o,a);if(c==="k"){const l=n===o?Math.min(t.length,Jo(t,o)+1):o;return{...Ct(t,n,l,""),killedText:t.slice(n,l)}}if(c==="u"){const l=n===o?Yo(t,n):n;return{...Ct(t,l,o,""),killedText:t.slice(l,o)}}if(c==="w"){const l=n===o?Zo(t,n):n;return{...Ct(t,l,o,""),killedText:t.slice(l,o)}}return null}const wi="videobook.elevenlabs-voice",Rl="/speak ";function $l(e){return/^\/speak(\s|$)/.test(e)}function ov(e,t){return t&&e.some(n=>n.voiceId===t)?t:e[0]?.voiceId??""}function Qo(e,t,n){if(e.length===0)return t;const o=e.findIndex(s=>s.voiceId===t),i=((o<0?0:o)+n+e.length)%e.length;return e[i].voiceId}function rv(){return typeof window>"u"?null:window.localStorage.getItem(wi)}function iv(e){typeof window>"u"||!e||window.localStorage.setItem(wi,e)}function sv(e,t,n){return e.key==="ArrowDown"?{type:"select",voiceId:Qo(t,n,1)}:e.key==="ArrowUp"?{type:"select",voiceId:Qo(t,n,-1)}:e.key==="Tab"?n?{type:"select",voiceId:n}:{type:"ignore"}:e.ctrlKey&&e.code==="Space"?{type:"toggle"}:e.key==="Escape"?{type:"dismiss"}:{type:"ignore"}}function av(e,t){if(!(!$l(e)||!t))return{speakVoiceId:t}}function cv(e){if(e.command==="/voices")return{kind:"prefill",nextInput:Rl,message:"Choose a voice, then type the speech text."};if(!e.hasNotebook)return{kind:"error",message:"Open a notebook before speaking."};const t=e.text.trim(),n=e.voiceId?.trim()??"";return t?n?{kind:"generate",text:t,voiceId:n}:{kind:"error",message:"Select a voice before speaking."}:{kind:"error",message:"Type the text to speak after /speak."}}function lv(e,t){const n=e.trim().toLowerCase();return t.some(o=>[o.label,...o.aliases??[]].some(r=>r.toLowerCase()===n))}function uv(e,t,n=Number.POSITIVE_INFINITY){const o=t.toLowerCase(),r=e.filter(s=>[s.command,...s.aliases??[],s.description??""].join(" ").toLowerCase().includes(o)).sort((s,a)=>{const c=l=>[l.command,...l.aliases??[]].some(u=>u.slice(1).toLowerCase()===o);return Number(c(a))-Number(c(s))});if(o)return r.slice(0,n);const i=r.find(s=>s.command==="/download");return i?[i,...r.filter(s=>s!==i)].slice(0,n):r.slice(0,n)}function dv(e){const t=e.match(/^\s*\/apply(?:\s+([\s\S]*?))?\s*$/iu);return t?{promptOverride:(t[1]?.trim()??"")||null}:null}function fv(e,t){const n=e.nextInput??(e.ok?void 0:t);return n===void 0?null:{value:n,select:e.selectInput??!e.ok}}function mv(e,t){return t.ok?e.trim().toLowerCase()==="/cancel"?{status:"cancelled",message:t.message}:t.nextInput?.startsWith("/apply")?{status:"review",message:t.message}:{status:/queued|started|running|processing/i.test(t.message)?"queued":"completed",message:t.message}:{status:"review",message:t.message}}const jt="videobook.composer-drafts.v1",Nl=50,Si=1e6;function Ii(e){const t=[],n=new Set;let o=0;for(const r of[...e].reverse()){if(!Array.isArray(r)||r.length!==2)continue;const[i,s]=r;if(!(typeof i!="string"||!i.startsWith("chat:")||i.length<=5||i.length>128||n.has(i))&&(n.add(i),!(typeof s!="string"||!s||o+s.length>Si)&&(t.push([i,s]),o+=s.length,t.length===Nl)))break}return t.reverse()}function pv(){if(typeof window>"u")return new Map;try{const e=window.sessionStorage.getItem(jt);if(!e||e.length>Si*6+1e4)return new Map;const t=JSON.parse(e);return new Map(Array.isArray(t)?Ii(t):[])}catch{return new Map}}function gv(e,t,n){if(typeof window>"u")return;const o=new Map(e);o.delete(t),o.set(t,n);const r=Ii([...o]);try{r.length===0?window.sessionStorage.removeItem(jt):window.sessionStorage.setItem(jt,JSON.stringify(r))}catch{try{window.sessionStorage.removeItem(jt)}catch{return}}}const er=new WeakMap,rn='.command-composer [aria-label="Videobook command input"]',xi='input:not([type="file"]), textarea, select, [contenteditable="true"], video[controls], audio[controls]',Pl='dialog[open], :popover-open, [aria-modal="true"], [role="menu"], details.canvas-add-menu[open]';function tt(e){const t=er.get(e);if(t)return t;const n={epoch:0,scope:"",enabled:!1,composerOwnedFocus:!1,modality:"initial",pending:null,frame:null};return er.set(e,n),n}function Ol(e,t){const n=t.pending;if(!n)return;const o=n.resolve();if(!(!t.enabled&&(!(o instanceof HTMLElement)||o.closest(".command-composer")))&&(t.pending=null,!(n.epoch!==t.epoch||n.scope!==t.scope)&&!(!o||e.visibilityState==="hidden"))){if(o instanceof HTMLElement){if(!o.isConnected||o.matches(':disabled, [aria-disabled="true"]')||o.closest("[inert], [hidden]"))return;const r=[...e.querySelectorAll(Pl)].at(-1);if(r&&!r.contains(o))return;const i=e.activeElement;if(i&&i!==o&&i.matches(xi)&&!i.closest("[hidden], [inert]")||r&&i instanceof Element&&r.contains(i)&&!i.closest(".command-composer")&&i!==o)return}o.focus({preventScroll:!0}),n.afterFocus?.()}}function co(e,t){t.frame!==null&&e.defaultView?.cancelAnimationFrame(t.frame),t.frame=e.defaultView?.requestAnimationFrame(()=>{t.frame=null,Ol(e,t)})??null}function Vn(e,t){t.pending={epoch:t.epoch,scope:t.scope,resolve:()=>e.querySelector(rn)},co(e,t)}function sn(e=()=>document.querySelector(rn),t){const n=document,o=tt(n),r={epoch:o.epoch,scope:o.scope,resolve:e,afterFocus:t};return()=>{o.epoch!==r.epoch||o.scope!==r.scope||(o.pending=r,co(n,o))}}function hv(){return tt(document).modality==="pointer"?sn():()=>{}}function bv(e){const t=tt(document).modality==="pointer",n=!!e?.closest(".command-composer");return sn(()=>{const o=document.querySelector(rn);return!(t||n||e===document.body||!e?.isConnected)||!o||o.closest("[hidden]")?e:o.matches('[aria-disabled="true"]')?o.closest(".command-composer")?.querySelector('button[aria-label="Open actions"]:not(:disabled)')??null:o})}function yv(e,t){const n=ne.c(5);let o;n[0]===Symbol.for("react.memo_cache_sentinel")?(o=[],n[0]=o):o=n[0],_.useLayoutEffect(Ll,o);let r,i;n[1]!==t||n[2]!==e?(r=()=>{const s=tt(document),a=s.scope!==e,c=!s.enabled&&t;if(s.scope=e,s.enabled=t,a&&(s.pending=null),!!t){if(s.pending){co(document,s);return}if(a||c){if(c&&s.composerOwnedFocus&&s.modality!=="touch"&&document.activeElement===document.body){Vn(document,s);return}s.modality==="initial"&&document.activeElement!==document.body||s.modality!=="initial"&&!(a&&s.modality==="pointer")||window.matchMedia("(pointer: fine)").matches&&Vn(document,s)}}},i=[t,e],n[1]=t,n[2]=e,n[3]=r,n[4]=i):(r=n[3],i=n[4]),_.useLayoutEffect(r,i)}function Ll(){const e=tt(document),t=()=>{e.epoch=e.epoch+1,e.pending=null},n=s=>{t(),e.modality=s.pointerType==="touch"?"touch":"pointer"},o=()=>{t(),e.modality="keyboard"},r=s=>{const a=s.target;e.composerOwnedFocus=a instanceof Element&&a.matches(rn)},i=s=>{if(s.detail===0||e.modality!=="pointer")return;const a=s.target;!(a instanceof Element)||a.closest(xi)||a.closest("[data-composer-focus]")?.getAttribute("data-composer-focus")==="return"&&Vn(document,e)};return document.addEventListener("pointerdown",n,!0),document.addEventListener("keydown",o,!0),document.addEventListener("focusin",r,!0),document.addEventListener("click",i,!0),document.defaultView?.addEventListener("blur",t),()=>{t(),document.removeEventListener("pointerdown",n,!0),document.removeEventListener("keydown",o,!0),document.removeEventListener("focusin",r,!0),document.removeEventListener("click",i,!0),document.defaultView?.removeEventListener("blur",t),e.frame!==null&&document.defaultView?.cancelAnimationFrame(e.frame),e.frame=null}}function Fl(){const e=tt(document);e.epoch+=1,e.pending=null}function _v(e){Fl();const t=e?.getAttribute("aria-label");if(!!t?.includes("fullscreen")){if(e?.isConnected){e.focus();return}t&&document.querySelector(`[aria-label="${CSS.escape(t)}"]`)?.focus();return}if(e?.isConnected){e.focus();return}document.querySelector('[aria-label="Videobook command input"]')?.focus()}function vv(e,t=n=>window.requestAnimationFrame(n)){if(typeof document>"u"){t(()=>e()?.focus({preventScroll:!0}));return}sn(e)()}function Dl(e){const t=h(e),o=(Array.isArray(t?.content)?t.content:[]).map(h).find(r=>r?.type==="text");return typeof o?.text=="string"?o.text:null}function kv(e){const t=Dl(e);let n=e;if(t)try{n=JSON.parse(t)}catch{return{values:[],offset:0,hasMore:!1}}const o=h(n),r=Array.isArray(o?.entries)?o.entries:[],i=h(o?.page);return{values:r.flatMap(s=>{const a=h(s);return typeof a?.prompt=="string"?[a.prompt]:[]}),offset:typeof i?.offset=="number"?i.offset:0,hasMore:i?.has_more===!0}}function wv(e){if(e.values.length===0)return null;let t=e.cursor,n=e.draft;if(t===-1){if(e.direction===1)return null;n=e.current,t=e.values.length-1}else if(t+=e.direction,t<0&&(t=0),t>=e.values.length)return{cursor:-1,draft:n,value:n};return{cursor:t,draft:n,value:e.values[t]??e.current}}const Vl=/page is hidden|paused for media playback|You are offline/i;function jl(e,t){return t?e==="connecting"||e==="thinking"||e==="listening"||e==="speaking":!1}function Gl(e){const t=e.voicePhase;return e.sending?{kind:"sending",label:"Sending",busy:!0}:t==="error"?{kind:"error",label:"Connection error",busy:!1}:t==="review"?{kind:"review",label:"Review on screen",busy:!1}:e.retrying?{kind:"retrying",label:"Retrying reply",busy:!0}:e.mcpRunning>0||jl(t,e.pendingReview)?{kind:"preparing",label:"Preparing an action",busy:!0}:t==="connecting"?/allow microphone/i.test(e.voiceMessage??"")?{kind:"permission",label:"Allow microphone access",busy:!0}:{kind:"connecting",label:"Connecting voice",busy:!0}:t==="thinking"?{kind:"waiting",label:"Waiting for reply",busy:!0}:t==="speaking"?{kind:"speaking",label:"Speaking",busy:!1}:t==="listening"?{kind:"listening",label:"Listening",busy:!1}:t==="off"&&Vl.test(e.voiceMessage??"")?{kind:"paused",label:"Voice paused. Start voice to resume.",busy:!1}:{kind:"idle",label:t==="off"?"Offline":"",busy:!1}}const ql=new Set(["idle","listening","review"]);function Ul(e){return!ql.has(e.kind)&&e.label!==""}function Sv(e){if(!e)return null;const t=Gl({sending:!1,mcpRunning:0,voicePhase:e.phase,voiceMessage:e.message,retrying:e.phase!=="off"&&e.retrying,pendingReview:e.pendingReview}),n=Ul(t)&&t.kind!=="connecting"&&t.kind!=="permission",o=n?t.kind==="error"&&e.message||t.label:null,r=e.phase==="off"||e.phase==="error"?null:e.fallbackReason??null;return!o&&!r&&!e.playbackBlocked?null:{message:o,busy:n&&t.busy,error:t.kind==="error",fallbackReason:r,playbackBlocked:e.playbackBlocked}}const Ai=e=>new Audio(e);function Bl(e=Ai){let t=null,n=null;const o=new Set,r=()=>{for(const a of o)a(n)},i=()=>{t?.pause(),t=null,n=null,r()};return{get playingVoiceId(){return n},toggle:(a,c)=>{if(!c)return;if(n===a){i();return}t?.pause();const l=e(c);t=l,n=a,r(),l.play().catch(()=>{t===l&&i()}),l.onended=()=>{t===l&&i()}},stop:i,subscribe(a){return o.add(a),()=>{o.delete(a)}},dispose(){t?.pause(),t=null,n=null,o.clear()}}}function Iv(e){const t=ne.c(13),n=Ai;let o;t[0]!==n?(o=()=>Bl(n),t[0]=n,t[1]=o):o=t[1];const[r]=_.useState(o),[i,s]=_.useState(null);let a,c;t[2]!==r?(a=()=>{const g=r.subscribe(s);return()=>{g(),r.dispose()}},c=[r],t[2]=r,t[3]=a,t[4]=c):(a=t[3],c=t[4]),_.useEffect(a,c);let l;t[5]!==r?(l=(g,p)=>{r.toggle(g,p)},t[5]=r,t[6]=l):l=t[6];const u=l;let m;t[7]!==r?(m=()=>{r.stop()},t[7]=r,t[8]=m):m=t[8];const d=m;let f;return t[9]!==i||t[10]!==d||t[11]!==u?(f={playingVoiceId:i,toggle:u,stop:d},t[9]=i,t[10]=d,t[11]=u,t[12]=f):f=t[12],f}const Hl=["auto","openai","xai"],Ei={auto:"Auto",openai:"OpenAI",xai:"xAI"},Wl={auto:"Tries OpenAI, then xAI if it cannot connect",openai:null,xai:null};function xv(e){return Ei[e]}function Kl(e){return e.modelSelectable?e.chatModels.map((t,n)=>({id:`model:${t.id}`,position:n,label:t.label,detail:t.id,note:t.description,checked:t.id===e.selectedModel,choice:{kind:"model",model:t.id}})):[]}function zl(e,t){const n=e.voiceMode;return n?Hl.map((o,r)=>({id:`speech:${o}`,position:t+r,label:Ei[o],detail:null,note:Wl[o],checked:o===n,choice:{kind:"speech",mode:o}})):[]}function Av(e){const t=[],n=Kl(e);n.length>0&&t.push({id:"model",label:"Chat model",items:n});const o=zl(e,n.length);return o.length>0&&t.push({id:"speech",label:"Speech",items:o}),t}function Ev(e){return e.flatMap(t=>t.items)}function Cv(e){const t=e.findIndex(n=>n.checked);return t===-1?0:t}function Mv(e,t,n){return e.length===0?null:n==="ArrowDown"?(t+1)%e.length:n==="ArrowUp"?(t-1+e.length)%e.length:n==="Home"?0:n==="End"?e.length-1:null}const Tv="Collapse chat";function Rv(e){return e==="selection"||e==="action"||e==="expand"||e==="reopen"}function $v(e,t){if(!e||!t||e.id!==t.id)return!1;const n=new Set(e.cells.map(o=>o.id));return t.cells.some(o=>!n.has(o.id))}function Nv(e){return e}function Pv(e){e.stopVoice?.(),e.pauseMedia?.(),e.setOpen(!1)}function Ov(e){if(e)for(const t of e.querySelectorAll("video, audio"))t instanceof HTMLMediaElement&&t.pause()}function Lv(e){return e==="applied"||e==="timeline"?"media":"music"}function Fv(e){return e.dockOpen&&e.panelHasHeader&&!e.reviewPriority}function Dv(e){return e.musicSession?!1:e.cellInspector}const O={originX:0,originY:0,squareSize:240,gap:24,columnPitch:264,rowPitch:264,columnCount:X,maximumRowCount:de,minimumRowCount:3,trailingRowCount:1,detailZoomFloor:.5};function Ci(e){return{row:Math.round(e.row),column:Math.round(e.column)}}function Fe(e){const t=Ci(e);return{row:Math.min(de-1,Math.max(0,t.row)),column:Math.min(X-1,Math.max(0,t.column))}}function _e(e){return`${e.row}:${e.column}`}function Xl(e){return Fe({row:Math.round((e.y-O.originY)/O.rowPitch),column:Math.round((e.x-O.originX)/O.columnPitch)})}function Ze(e){const t=Fe(e);return{x:O.originX+t.column*O.columnPitch,y:O.originY+t.row*O.rowPitch}}function Vv(e,t,n){const o=e.find(i=>i.id===t),r=Fe(o?.data.kind==="timeline"?{...n,column:0}:n);return e.map(i=>i.id===t?{...i,position:Ze(r)}:i)}function Yl(e,t,n){const o=e.find(c=>c.id===t);if(!o)return[...e];const r=Fe(o.data.kind==="timeline"?{...n,column:0}:n),i=o.data.slot,s=new Set(Ee({type:String(o.data.kind),slot:r}).map(_e)),a=e.find(c=>c.id!==t&&Ee({type:String(c.data.kind),slot:c.data.slot}).some(l=>s.has(_e(l))));return a&&(o.data.kind==="timeline"||a.data.kind==="timeline")?e.map(c=>c.id===t?{...c,position:Ze(i)}:c):e.map(c=>{const l=c.id===t?r:c.id===a?.id?i:null;return l?{...c,position:Ze(l),data:{...c.data,slot:l}}:c})}function jv(e,t,n,o){const r=new Set(n);r.add(t);const i=e.filter(f=>r.has(f.id));if(i.length<=1)return Yl(e,t,o);const s=i.find(f=>f.id===t);if(!s)return[...e];const a=Ci(o),c=a.row-s.data.slot.row,l=a.column-s.data.slot.column,u=new Map(i.map(f=>{const g={row:f.data.slot.row+c,column:f.data.slot.column+l};return[f.id,g]})),m=new Set(i.flatMap(f=>Ee({type:String(f.data.kind),slot:u.get(f.id)})).map(_e));return[...u.values()].some(f=>!qs(f))||i.some(f=>f.data.kind==="timeline"&&l!==0)||e.some(f=>!r.has(f.id)&&Ee({type:String(f.data.kind),slot:f.data.slot}).some(g=>m.has(_e(g))))?e.map(f=>r.has(f.id)?{...f,position:Ze(f.data.slot)}:f):e.map(f=>{const g=u.get(f.id);return g?{...f,position:Ze(g),data:{...f.data,slot:g}}:f})}function Gv(e,t){const n=new Map(e.map(o=>[o.id,_e(o.data.slot)]));return t.filter(o=>n.get(o.id)!==_e(o.data.slot))}const Jl=new Set(["image","generate_image","character"]);function Zl(e){return Jl.has(e)}function lo(e){return e?Fe(e):null}const Ql=new Set(["generate_image","generate_audio","extract_audio"]);function uo(e,t=[],n=null){const o=We(e);if(t.length>0){const s=Math.max(...t.map(l=>l.row))+1,c=t.every(l=>l.row===0)?0:t[0].column;return To(s,c,o)}const r=lo(n);if(r)return Nn(r,o);let i=-1;for(const s of e)Zl(s.type)&&s.slot.row>i&&(i=s.slot.row);return To(i+1,0,o)}function an(e,t=[],n=null){const o=We(e);if(t.length===0){const a=lo(n);return $n(a??{row:0,column:0},o)}const r=Math.max(...t.map(a=>a.column)),s={row:Math.min(...t.map(a=>a.row)),column:Math.min(r+1,X-1)};return $n(s,o)}function qv(e,t,n=null){if(e==="timeline")return js(We(t));if(e==="generate_video")return uo(t,[],n);if(Ql.has(e))return an(t,[],n);const o=lo(n);return o?$n(o,We(t)):Gs(We(t))}function cn(e){return Number.isFinite(e)&&e>0?e:1}function Uv(e){return 1/Math.max(cn(e),O.detailZoomFloor)}function eu(e,t=0){return!Number.isFinite(e)||e<=0?1:Math.max(Number.isFinite(t)?t:0,e/Mi())}function Mi(){return O.originX*2+X*O.squareSize+(X-1)*O.gap}function tu(e,t){if(!Number.isFinite(e)||e<=0)return O.minimumRowCount;const n=e/cn(t);return Math.max(O.minimumRowCount,Math.ceil((n-O.originY*2+O.gap)/O.rowPitch))}function Bv(e,t){const n=cn(t);return{width:e.width*n,height:e.height*n}}function Hv(e,t,n=0){return{x:0,y:Number.isFinite(n)?n:0,zoom:cn(t)}}function Wv(e,t){return Xl(e)}function Kv(e,t){const n=e.x-O.originX,o=e.y-O.originY;if(n<0||o<0)return null;const r=Math.floor(n/O.columnPitch),i=Math.floor(o/O.rowPitch);if(r<0||r>=t.columnCount||i<0||i>=t.rowCount)return null;const s=t.minColumn+r;return s>t.maxColumn||n-r*O.columnPitch>=O.squareSize||o-i*O.rowPitch>=O.squareSize?null:{row:i,column:s}}function zv(e,t={}){const n=t.preview?[...e,Fe(t.preview)]:e,o=Math.max(-1,...n.map(a=>Fe(a).row)),r=Math.min(de,Math.max(O.minimumRowCount,tu(t.viewportHeight??0,t.zoom??1),o+2)),i=Mi(),s=O.originY*2+r*O.squareSize+Math.max(0,r-1)*O.gap;return{rowCount:r,columnCount:X,minColumn:0,maxColumn:X-1,centerX:i/2,width:i,height:s}}const Ti="post_to_x";function Ve(e){return e?.inputs?.sourceOperation===Ti}function nu(){return"X · POSTED"}function ou(e){const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString().replace("T"," ").replace(/\.\d{3}Z$/," UTC"):e}function ru(e){const t=h(e);if(!t)return null;const n=W(t.tweetId??t.tweet_id),o=W(t.tweetUrl??t.tweet_url);return!n||!o?null:{tweetId:n,tweetUrl:o}}function iu(e){const t=h(e);if(!t)return null;const n=typeof t.replyNumber=="number"?t.replyNumber:typeof t.reply_number=="number"?t.reply_number:null,o=W(t.message);return n===null||!o?null:{replyNumber:n,message:o}}function Xv(e){if(e?.sourceOperation!==Ti)return null;const t=W(e.tweetId??e.tweet_id),n=W(e.tweetUrl??e.tweet_url),o=W(e.postedAt??e.posted_at);if(!t||!n||!o)return null;const r=Array.isArray(e.replies)?e.replies.flatMap(s=>{const a=ru(s);return a?[a]:[]}):[],i=e.status==="partially_posted"?"partially_posted":"posted";return{badge:"Posted to X",tweetId:t,tweetUrl:n,postedAt:o,postedAtLabel:ou(o),replyCount:r.length,replyLabel:r.length===1?"1 reply":`${r.length} replies`,replies:r,status:i,followupError:iu(e.followupError??e.followup_error)}}const su={run_notebook:"Run notebook",semantic_index:"Semantic index",extract_waveform:"Extract waveform",extract_video_poster:"Create video poster",extract_audio:"Extract audio",transcribe:"Transcribe"},au={attention:"Needs attention",running:"Running",queued:"Queued",finished:"Finished"},cu=["attention","running","queued","finished"];function fo(e){const t=su[e];if(t)return t;const n=e.replace(/[_-]+/g," ").trim();return n.length===0?e:n.charAt(0).toUpperCase()+n.slice(1)}function tr(e){const t=Math.max(0,e);if(t<1e4)return`${(t/1e3).toFixed(1)}s`;const n=Math.round(t/1e3);if(n<60)return`${n}s`;const o=Math.floor(n/60),r=n%60;return o<60?`${o}m ${String(r).padStart(2,"0")}s`:`${Math.floor(o/60)}h ${String(o%60).padStart(2,"0")}m`}function mo(e){return e.slice(0,8)}function lu(e){switch(e){case"queued":return"queued";case"running":case"completing":return"running";case"failed":return"failed";case"aborted":return"cancelled";default:return"done"}}function uu(e,t){switch(e){case"awaiting-output":return t?"review":"running";case"failed":return"failed";case"queued":return"queued";case"omitted":return"omitted";default:return"done"}}function Ri(e){switch(e){case"review":case"failed":return"attention";case"running":return"running";case"queued":return"queued";default:return"finished"}}function $i(e){return e.toUpperCase()}function Ni(e){return e?{tag:ue(e.slot),label:e.label??e.prompt??null}:{tag:null,label:null}}function du(e,t){if(!e.artifactId)return{tag:null,label:null};const n=t.find(o=>!Ve(o)&&o.outputArtifactId===e.artifactId);return n?Ni(n):{tag:null,label:`artifact ${mo(e.artifactId)}`}}function nr(e,t){const n=e?.[t];return typeof n=="string"&&n.trim().length>0?n:null}function fu(e){const t=[nr(e.payload,"provider"),nr(e.payload,"model")].filter(n=>n!==null);return t.length>0?t.join(" · "):null}function mu(e){return e==="queued"||e==="running"||e==="completing"?["cancel"]:e==="failed"||e==="aborted"?["retry"]:[]}function pu(e,t){const n=e.startedAt===null?null:tr((e.finishedAt??t)-e.startedAt);switch(e.state){case"queued":return{summary:"Waiting for a worker",note:`waiting ${tr(t-e.enqueuedAt)}`,duration:null,live:!1};case"running":return{summary:`${fo(e.type)} in progress`,note:n?`${n} elapsed`:null,duration:null,live:!0};case"completing":return{summary:"Finishing up",note:n?`${n} elapsed`:null,duration:null,live:!0};case"failed":return{summary:e.error?.message??"Failed without an error message",note:null,duration:n,live:!1};case"aborted":return{summary:e.error?.message??"Cancelled",note:"nothing was written",duration:n,live:!1};default:return{summary:"Completed",note:null,duration:n,live:!1}}}function gu(e){const t=e.error?.code??null;return t&&t!=="Error"?t:null}function hu(e,t,n){const o=lu(e.state),r=o==="done"&&e.state!=="done"?e.state.toUpperCase():$i(o),i=e.error?[`${e.error.code?`${e.error.code} · `:""}${e.error.message}`,`operation ${e.operationId} · enqueued ${new Date(e.enqueuedAt).toLocaleString()}`].join(`
13
+ `):null;return{key:`job:${e.id}`,providerTask:e.providerTask,source:{kind:"job",jobId:e.id},tone:o,band:Ri(o),statusLabel:r,title:fo(e.type),detail:fu(e),target:du(e,t),...pu(e,n),errorCode:gu(e),errorDetail:i,attempt:`${e.attempts}/${e.maxAttempts}`,timestamp:e.enqueuedAt,sortAt:e.finishedAt??e.startedAt??e.enqueuedAt,actions:mu(e.state)}}function Pi(e){const t=e.plan.stages.find(n=>n.kind==="queued"&&n.jobType==="generation");return t?.kind==="queued"?t:null}function bu(e,t){const n=[];return t&&e.status!=="continued"&&e.status!=="omitted"&&n.push("continue"),(e.status==="failed"||e.status==="awaiting-output"&&t)&&n.push("retry","switch","omit"),n}function yu(e){const t=Pi(e),n=[];return t?.estimatedCostUsd!==void 0&&n.push(`est. $${t.estimatedCostUsd.toFixed(2)}`),e.outputArtifactId&&n.push(`output ${mo(e.outputArtifactId)}`),n.length>0?n.join(" · "):null}function _u(e,t){const n=yu(e);switch(e.status){case"awaiting-output":return{summary:t?"Output ready — review before inserting":"Waiting for generated media",note:n};case"failed":return{summary:e.error??"Generation failed",note:n};case"queued":return{summary:"Generation queued",note:n};case"continued":return{summary:"Generation complete",note:n};case"omitted":return{summary:"Left out of the sequence",note:e.outputArtifactId?`output kept as ${mo(e.outputArtifactId)}`:null};default:return{summary:"Generation finished",note:n}}}function bn(e){const t=Date.parse(e);return Number.isFinite(t)?t:0}function vu(e,t,n){return t?.type.startsWith("generate_")?fo(t.type):n?"Generate":e.plan.summary}function ku(e,t,n){const o=n.some(c=>c.artifactId===e.outputArtifactId&&c.status==="ready"&&!!c.mediaUrl),r=uu(e.status,o),i=Pi(e),s=t.find(c=>c.id===e.cellId),a=i?[i.provider,i.model??i.tool].filter(c=>!!c).join(" · "):null;return{key:`plan:${e.planId}`,source:{kind:"plan",planId:e.planId},tone:r,band:Ri(r),statusLabel:$i(r),title:vu(e,s,i),detail:a&&a.length>0?a:null,target:Ni(s),..._u(e,o),errorCode:null,errorDetail:e.error,attempt:"1/1",timestamp:bn(e.createdAt),sortAt:bn(e.updatedAt)||bn(e.createdAt),duration:null,live:r==="running",actions:bu(e,o)}}function Yv({jobs:e,plans:t,cells:n,assets:o=[],now:r}){return[...t.map(i=>ku(i,n,o)),...e.map(i=>hu(i,n,r))]}function wu(e){return e.map((t,n)=>({...t,summary:n===0?"Next up":`${n} ahead in queue`}))}function Su(e,t){switch(e){case"running":return[...t].sort((n,o)=>n.sortAt-o.sortAt);case"queued":return wu([...t].sort((n,o)=>n.timestamp-o.timestamp));default:return[...t].sort((n,o)=>o.sortAt-n.sortAt)}}function Jv(e){return cu.map(t=>({id:t,label:au[t],rows:Su(t,e.filter(n=>n.band===t))}))}function Zv(e){const t=i=>e.find(s=>s.id===i)?.rows.length??0,n=t("attention"),o=t("running")+t("queued"),r=t("finished");return{total:n+o+r,attention:n,active:o,finished:r}}function Qv(e,t){if(t==="all")return e.filter(o=>o.rows.length>0);const n=t==="attention"?["attention"]:t==="active"?["running","queued"]:["finished"];return e.filter(o=>n.includes(o.id)&&o.rows.length>0)}const Ae=[O.gap*.25,O.gap*.5,O.gap*.75],Iu=[.25,.5,.75],Oi={sourceSide:"bottom",sourcePortIndex:1,targetSide:"top",targetPortIndex:1,sourceBusOffset:Ae[1],targetBusOffset:Ae[1],riverOffset:Ae[1],riverSide:"right",directRowGutter:!1,targetPrimary:!0};function kt(e,t){return e.sourceRow-t.sourceRow||e.sourceColumn-t.sourceColumn||e.targetRow-t.targetRow||e.targetColumn-t.targetColumn||e.targetInput.localeCompare(t.targetInput)||e.id.localeCompare(t.id)}function po(e,t){return t===1?1:t===2?e%2===0?0:2:e%Ae.length}function Li(e,t){return Ae[po(e,t)]}function xu(e,t){const n=new Map;for(const r of e)for(const i of t(r)){const s=n.get(i)??new Map;s.set(r.id,r),n.set(i,s)}const o=new Map;for(const[r,i]of n){const s=[...i.values()].sort(kt);o.set(r,new Map(s.map((a,c)=>[a.id,Li(c,s.length)])))}return o}function wt(e){return e.targetColumn<e.sourceColumn?"left":e.targetColumn>e.sourceColumn?"right":"bottom"}function Au(e){const t=new Map;for(const o of e){const r=`${o.sourceId}:${wt(o)}`,i=t.get(r)??[];i.push(o),t.set(r,i)}const n=new Map;for(const o of t.values())o.sort(kt),o.forEach((r,i)=>{n.set(r.id,po(i,o.length))});return n}function Wt(e){return e.sourceColumn<e.targetColumn?"left":"top"}function Eu(e){const t=new Map;for(const o of e){const r=`${o.targetId}:${Wt(o)}`,i=t.get(r)??[];i.push(o),t.set(r,i)}const n=new Map;for(const o of t.values())o.sort(kt),o.forEach((r,i)=>{n.set(r.id,po(i,o.length))});return n}function Cu(e){const t=new Map;for(const o of e){const r=t.get(o.targetId)??[];r.push(o),t.set(o.targetId,r)}const n=new Set;for(const o of t.values()){o.sort(kt);const r=o[0];r&&n.add(r.id)}return n}function Mu(e){const t=new Map;for(const o of e){if(wt(o)!=="bottom")continue;const r=t.get(o.sourceId)??[];r.push(o),t.set(o.sourceId,r)}const n=new Map;for(const o of t.values())o.sort(kt),o.forEach((r,i)=>{n.set(r.id,o.length===1||i%2===1?"right":"left")});return n}function Fi(e,t){const n=wt(e);return n==="bottom"?t.get(e.id)??"right":n}function or(e,t){return Fi(e,t)==="right"?e.sourceColumn:e.sourceColumn-1}function Kt(e){return e.targetRow===e.sourceRow+1&&e.targetColumn===e.sourceColumn}function Tu(e){const t=new Map,n=(i,s,a,c,l)=>{const u=t.get(i)??new Map,m=u.get(s)??{id:s,column:a,kind:c,candidates:[]};m.candidates.push(l),u.set(s,m),t.set(i,u)};for(const i of e)wt(i)==="bottom"&&!Kt(i)&&n(i.sourceRow,`source:${i.id}`,i.sourceColumn,"source",i),Wt(i)==="top"&&n(i.targetRow-1,`target:${i.targetId}`,i.targetColumn,"target",i);const o=new Map,r=new Map;for(const i of t.values()){const s=[...i.values()].sort((a,c)=>a.column-c.column||a.kind.localeCompare(c.kind)||a.id.localeCompare(c.id));s.forEach((a,c)=>{const l=Li(c,s.length);for(const u of a.candidates)a.kind==="source"?o.set(u.id,l):r.set(u.id,l)})}for(const i of e)Kt(i)&&o.set(i.id,r.get(i.id)??Ae[1]);return{source:o,target:r}}function Ru(e,t,n){return e.get(String(t))?.get(n)??Ae[1]}function Di(e){const t=new Map(e.cells.map(u=>[u.id,u])),n=e.edges.flatMap(u=>{const m=t.get(u.source),d=t.get(u.target);return!m||!d?[]:[{id:u.id,sourceId:m.id,targetId:d.id,sourceRow:m.slot.row,sourceColumn:m.slot.column,targetRow:d.slot.row,targetColumn:d.slot.column,targetInput:u.targetInput}]}),o=Au(n),r=Eu(n),i=Cu(n),s=Mu(n),a=Tu(n),c=xu(n.filter(u=>!Kt(u)),u=>[String(Wt(u)==="left"?u.targetColumn-1:or(u,s))]),l=new Map;for(const u of n){const m=Fi(u,s),d=Wt(u),f=d==="left"?u.targetColumn-1:or(u,s);l.set(u.id,{sourceSide:wt(u),sourcePortIndex:o.get(u.id)??1,targetSide:d,targetPortIndex:r.get(u.id)??1,sourceBusOffset:a.source.get(u.id)??Ae[1],targetBusOffset:a.target.get(u.id)??Ae[1],riverOffset:Ru(c,f,u.id),riverSide:m,directRowGutter:Kt(u),targetPrimary:i.has(u.id)})}return l}function $u(e,t){const n=e.sourceBottomY+t.sourceBusOffset,o=e.targetTopY-O.gap+t.targetBusOffset,r=t.riverSide==="right"?e.sourceRightX+t.riverOffset:e.sourceLeftX-O.gap+t.riverOffset;if(t.targetSide==="left"){if(e.sourceY===e.targetY)return[{x:e.sourceX,y:e.sourceY},{x:e.targetX,y:e.targetY}];const i=e.targetLeftX-O.gap+t.riverOffset;return[{x:e.sourceX,y:e.sourceY},{x:i,y:e.sourceY},{x:i,y:e.targetY},{x:e.targetX,y:e.targetY}]}if(t.directRowGutter&&e.targetTopY>e.sourceBottomY){const i=e.targetTopY-e.sourceBottomY,s=e.sourceBottomY+i*(t.targetBusOffset/O.gap);return[{x:e.sourceX,y:e.sourceY},{x:e.sourceX,y:s},{x:e.targetX,y:s},{x:e.targetX,y:e.targetY}]}return t.sourceSide!=="bottom"?[{x:e.sourceX,y:e.sourceY},{x:r,y:e.sourceY},{x:r,y:o},{x:e.targetX,y:o},{x:e.targetX,y:e.targetY}]:[{x:e.sourceX,y:e.sourceY},{x:e.sourceX,y:n},{x:r,y:n},{x:r,y:o},{x:e.targetX,y:o},{x:e.targetX,y:e.targetY}]}const Nu=8;function yn(e,t){return t.x===e.x?`V ${t.y}`:t.y===e.y?`H ${t.x}`:`L ${t.x} ${t.y}`}function ek(e,t){const n=$u(e,t),o=[`M ${n[0].x} ${n[0].y}`];let r=n[0];for(let i=1;i<n.length-1;i+=1){const s=n[i],a=n[i+1],c=Math.hypot(s.x-r.x,s.y-r.y),l=Math.hypot(a.x-s.x,a.y-s.y),u=Math.min(Nu,c/2,l/2);if(u<1){o.push(yn(r,s)),r=s;continue}const m={x:s.x-(s.x-r.x)/c*u,y:s.y-(s.y-r.y)/c*u},d={x:s.x+(a.x-s.x)/l*u,y:s.y+(a.y-s.y)/l*u};o.push(yn(r,m),`Q ${s.x} ${s.y} ${d.x} ${d.y}`),r=d}return o.push(yn(r,n[n.length-1])),o.join(" ")}function Vi(e,t){return`route-${e}-${t%Iu.length}`}function tk(e){const t=ne.c(8),{bookId:n,notebook:o,ready:r,call:i}=e,[s,a]=_.useState(null),c=_.useRef(null),l=`${n}:${o?.id}`;let u;t[0]!==n||t[1]!==i||t[2]!==o||t[3]!==r?(u=(g,p,y)=>{const v=y===void 0?o:y,S=v?.cells.find(C=>C.id===g);if(!n||!v||!g||p===void 0&&(!S||!vt(S.type))){c.current=null,a(null);return}const w=`${n}:${v.id}`,k={scope:w,cellId:g};if(p!==void 0){c.current=null,a({...k,value:p,loading:!1,error:null});return}if(!S||!r)return;const I=JSON.stringify([w,S,v.edges.filter(C=>C.target===g)]);if(c.current?.key===I)return;const E={key:I};c.current=E,a({...k,value:null,loading:!0,error:null}),i("preview_notebook_generation",{book_id:n,notebook_id:v.id,cell_id:S.id},{background:!0}).then(C=>{c.current===E&&a({...k,value:C,loading:!1,error:null})}).catch(C=>{c.current===E&&(c.current=null,a({...k,value:null,loading:!1,error:C instanceof Error?C.message:String(C)}))})},t[0]=n,t[1]=i,t[2]=o,t[3]=r,t[4]=u):u=t[4];const m=u,d=s?.scope===l?s:null;let f;return t[5]!==m||t[6]!==d?(f={preview:d,select:m},t[5]=m,t[6]=d,t[7]=f):f=t[7],f}function nk(e,t){const n=ne.c(11),o=_.useRef(null);let r;n[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{o.current!==null&&clearTimeout(o.current),o.current=null},n[0]=r):r=n[0];const i=r;let s;n[1]===Symbol.for("react.memo_cache_sentinel")?(s=()=>i,n[1]=s):s=n[1];let a;n[2]!==t?(a=[i,t],n[2]=t,n[3]=a):a=n[3],_.useEffect(s,a);let c;n[4]!==e?(c=(...f)=>{const g=f;i(),o.current=setTimeout(()=>{o.current=null,e(...g)},350)},n[4]=e,n[5]=c):c=n[5];const l=c;let u;n[6]!==e?(u=(...f)=>{const g=f;i(),e(...g)},n[6]=e,n[7]=u):u=n[7];const m=u;let d;return n[8]!==m||n[9]!==l?(d={schedule:l,cancel:i,run:m},n[8]=m,n[9]=l,n[10]=d):d=n[10],d}const Pu=720;function ji(e){return Math.abs(e)}function Ou(e,t){const n=[];for(let o=0;o<e.length;o+=t)n.push(Math.max(...e.slice(o,o+t).map(ji)));return n}function Lu(e,t){const n=[];for(let o=0;o<t;o+=1){const r=Math.floor(o*e.length/t),i=Math.max(r+1,Math.floor((o+1)*e.length/t));n.push(Math.max(...e.slice(r,i).map(ji)))}return n}function ok(e){if(e.length===0)return"";const t=Math.max(1,Math.ceil(e.length/Pu)),n=Ou(e,t);return n.map((o,r)=>{const i=n.length===1?50:r/(n.length-1)*100,s=Math.max(2,Math.min(46,o*46));return`M${i.toFixed(3)} ${50-s}V${50+s}`}).join("")}function rk(e,t){const{width:n,height:o,pitch:r,minimumBarHeight:i}=t,s=Math.floor(n/r);if(e.length===0||s<1)return"";const a=Lu(e,s),c=Math.max(...a),l=o/2,u=o-i;return a.map((m,d)=>{const f=r*d+r/2,g=c>0?m/c:0,p=Math.max(i,g*u),y=l-p/2,v=l+p/2;return`M${f.toFixed(2)} ${y.toFixed(2)}V${v.toFixed(2)}`}).join("")}function ik(e){const{width:t,height:n,pitch:o,minimumBarHeight:r}=e,i=Math.floor(t/o);if(i<1)return"";const s=n/2,a=(s-r/2).toFixed(2),c=(s+r/2).toFixed(2);return Array.from({length:i},(l,u)=>`M${(o*u+o/2).toFixed(2)} ${a}V${c}`).join("")}function sk(e,t){return Us(e,t)}function ak(e){if(e.value===null)return{kind:"null"};if(!e.column.endsWith("_json")||typeof e.value!="string")return{kind:"raw",value:e.value};try{return{kind:"json",value:JSON.parse(e.value)}}catch{return{kind:"raw",value:e.value}}}function ck(e){const t=ne.c(3),[n,o]=_.useState(null);let r,i;return t[0]!==e?(r=()=>{if(!e)return;const s=Date.parse(e);if(!Number.isFinite(s))return;const a=()=>o(Math.max(0,Math.round((Date.now()-s)/1e3))),c=window.setTimeout(a,0),l=window.setInterval(a,1e3);return()=>{window.clearTimeout(c),window.clearInterval(l)}},i=[e],t[0]=e,t[1]=r,t[2]=i):(r=t[1],i=t[2]),_.useEffect(r,i),e?n:null}const Fu={image:9/16,video:16/9,audio:16/9},Du={image:"Image",video:"Video",audio:"Audio"};function ut(e){return e!=null&&Number.isFinite(e)&&e>0}function lk(e){return e==="image"||e==="video"||e==="audio"?e:null}function uk(e){return Du[e]}function dk(e,t){return e!=="audio"&&t&&ut(t.width)&&ut(t.height)?t.width/t.height:Fu[e]}function Pe(e,t,n,o="plain"){return n===null?null:{key:e,term:t,value:n,emphasis:o}}function Vu(e){return ut(e.width)&&ut(e.height)?`${e.width} × ${e.height}`:null}function ju(e){return ut(e)?me(e):null}function fk(e,t,n,o){const r=Pe("address","Address",`@${t}`,"address");if(e==="audio"){const i=io({audioInfo:n.audioInfo,durationSeconds:n.duration,hasOutput:!0,inputs:o});return[r,Pe("role","Role",i.role),Pe("duration","Duration",i.duration),Pe("format","Format",i.details.length>0?i.details.join(" · "):null)].filter(s=>s!==null)}return[r,Pe("dimensions","Dimensions",Vu(n)),Pe("aspect","Aspect",on(n.width,n.height)),e==="video"?Pe("duration","Duration",ju(n.duration)):null].filter(i=>i!==null)}async function mk(e){e.onStarting?.();try{const t=await e.start();return e.onAccepted?.(),t}catch(t){throw e.onRejected?.(),t}}async function pk(e){return!e.valid||e.dirty&&await e.onUpdate(e.patch)===!1?!1:(await e.onRun(e.cellId),!0)}function _n(e){return e!==null&&Number.isFinite(e)&&e>0}function gk(e,t){const n=new Map(t.map(r=>[r.artifactId,r])),o=new Map;for(const r of e){const i=r.outputArtifactId;if(!i)continue;const s=n.get(i);if(!s)continue;const a=o.get(i);(!a||a.type!==s.type&&r.type===s.type)&&o.set(i,r)}return[...o.entries()].map(([r,i])=>{const s=n.get(r),{id:a,...c}=s;return{...c,cellAddress:yt(i.slot)}})}function hk(e,t){return zr(e,t.map(n=>({reference:n.cellAddress,replacement:`@${n.artifactId}`})))}function Gu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gi(e,t){let n=e;for(const{token:o,replacement:r}of t){const i=ve(o);i&&(n=n.replace(new RegExp(`(?<![\\w./-])@?${Gu(i)}(?![\\w-])`,"giu"),r))}return n}function bk(e,t){return Gi(e,t.map(n=>({token:n.artifactId,replacement:`@${n.cellAddress}`})))}function yk(e,t,n){const o=new Map(n.flatMap(r=>r.outputArtifactId?[[r.outputArtifactId,r]]:[]));return Gi(e,t.flatMap(r=>{const i=o.get(r.artifactId);return i?[{token:r.artifactId,replacement:`@${yt(i.slot)}`}]:[]}))}function qi(e){const t=[e.type.toUpperCase()];_n(e.width)&&_n(e.height)&&t.push(`${e.width}×${e.height}`),_n(e.duration)&&t.push(me(e.duration));const n=e.status.trim().toLowerCase();return n&&n!=="ready"&&t.push(n.replaceAll("_"," ").toUpperCase()),t}function Ui(e){return e.thumbnailUrl??(e.type==="image"?e.mediaUrl:null)}function jn(e){const t=e.toLowerCase();return t.includes("audio")?"audio":t.includes("image")?"image":t.includes("video")||t==="final"||t==="concat"||t==="splice"?"video":"other"}function qu(e,t,n=new Set){const o=Qt(t);if(o===void 0)return[];const r=t.slice(0,t.lastIndexOf("@")).trim(),i=/\b(?:generate|create|make)\s+(?:an?\s+)?(?:image|photo|picture)s?(?:\s+(?:of|from|using|with))?$/iu.test(r)?"image":null;return e.filter(s=>(!i||s.type.toLowerCase()===i)&&s.cellAddress.toLowerCase().includes(o)&&!n.has(`@${s.cellAddress}`)).sort((s,a)=>/^\s*\/goal\b/u.test(t)?+(a.type==="image")-+(s.type==="image"):0).slice(0,12).map(s=>({value:`@${s.cellAddress}`,label:`@${s.cellAddress}`,asset:s,type:"asset"}))}function Uu(e,t,n=new Set){const o=Qt(t);if(o===void 0)return[];const r=new Map(e.flatMap(s=>Ee(s).map(a=>[`${a.row}:${a.column}`,s]))),i=[];for(let s=0;s<de;s+=1)for(let a=0;a<X;a+=1){const c=ue({row:s,column:a});if(!c.slice(1).includes(o)||n.has(c))continue;const l=r.get(`${s}:${a}`);if(!(l?.type==="timeline"&&a!==l.slot.column)&&(i.push({value:c,label:c,description:l?`${l.type.replaceAll("_"," ").toUpperCase()} cell`:"Empty grid square",cellType:l?.type??null,empty:!l,type:"cell"}),i.length===12))return i}return i}const Bu=8,Hu=16;function _k(e,t,n,o=new Set,r={}){const i=new Map(t.map(c=>[ue(c.slot),c.label?.trim()||null])),s=new Set,a=[];for(const c of qu(e,n,o))s.has(c.value)||(s.add(c.value),a.push({value:c.value,label:c.label,description:qi(c.asset).join(" · "),caption:i.get(c.value)??null,thumbnailUrl:Ui(c.asset),mediaKind:jn(c.asset.type),empty:!1}));for(const c of Uu(t,n,o))s.has(c.value)||(s.add(c.value),a.push({value:c.value,label:c.label,description:c.description,caption:i.get(c.value)??null,thumbnailUrl:null,mediaKind:c.cellType?jn(c.cellType):null,empty:c.empty}));return[...a.filter(c=>!c.empty).sort((c,l)=>/^\s*\/goal\b/u.test(n)?+(l.mediaKind==="image")-+(c.mediaKind==="image"):0).slice(0,r.rows??Bu),...a.filter(c=>c.empty).slice(0,r.empties??Hu)]}function vk(e,t,n){const o=Qt(n);if(o===void 0)return[];const r=new Map(t.map(i=>[i.cellAddress,i]));return e.filter(({token:i})=>i.includes(o)).map(({token:i,cell:s})=>{const a=yt(s.slot),c=r.get(a);return{value:`@${i}`,label:`@${i}`,description:[`@${a}`,...c?qi(c):[s.type.replaceAll("_"," ").toUpperCase()]].join(" · "),caption:s.label?.trim()||null,thumbnailUrl:c?Ui(c):null,mediaKind:jn(c?.type??s.type),empty:!1}})}const Bi={first_frame:"firstframe",last_frame:"lastframe"},Wu=new Set(["replace_audio"]),Ku=["image","video","audio"];function zu(e){return e==="image"||e==="generate_image"?"image":e==="audio"||e==="extract_audio"||e==="generate_audio"?"audio":e==="video"||e==="split_video"||e==="generate_video"||e==="concat"||e==="splice"?"video":null}function rr(e,t){if(e===t)return 1;const n=`${t}_`;if(!e.startsWith(n))return null;const o=e.slice(n.length);return/^\d+$/.test(o)?Number(o):null}function Xu(e,t){return[...e].sort((n,o)=>{const r=rr(n.targetInput,t)??Number.MAX_SAFE_INTEGER,i=rr(o.targetInput,t)??Number.MAX_SAFE_INTEGER;return r-i})}function Yu(e,t,n){const o=new Map(t.map(r=>[r.id,r]));return n.flatMap(r=>{if(r.target!==e)return[];const i=o.get(r.source),s=i?zu(i.type):null;return s?[{kind:s,sourceCellId:r.source,targetInput:r.targetInput}]:[]})}function Ju(e){return Object.entries(Bi).flatMap(([t,n])=>{const o=e.find(r=>r.kind==="image"&&r.targetInput===t);return o?[{...o,token:n}]:[]})}function Zu(e,t,n){const o=e.filter(r=>r.kind===t&&!(n!=="r2v"&&t==="image"&&r.targetInput in Bi)&&!Wu.has(r.targetInput));return Xu(o,t).map((r,i)=>({...r,token:`${t}${i+1}`}))}function Qu(e,t,n,o){const r=t.find(a=>a.id===e)?.inputs?.generationMode,i=o??r,s=Yu(e,t,n);return[...i==="r2v"?[]:Ju(s),...Ku.flatMap(a=>Zu(s,a,typeof i=="string"?i:void 0))]}function kk(e,t,n){const o=new Set([...t,...n].map(i=>i.token)),r=new Map(t.map(i=>{const s=n.find(l=>l.sourceCellId===i.sourceCellId&&l.targetInput===i.targetInput)??n.find(l=>l.targetInput===i.targetInput);if(s)return[i.token,s.token];if(!n.some(l=>l.token===i.token))return[i.token,i.token];let a=1;for(;o.has(`${i.kind}${a}`);)a+=1;const c=`${i.kind}${a}`;return o.add(c),[i.token,c]}));return e.replace(/@((?:image|video|audio)\d+|firstframe|lastframe)(?![\w-])/giu,(i,s)=>{const a=r.get(s.toLowerCase());return a&&a!==s.toLowerCase()?`@${a}`:i})}function Hi(e,t,n){return e==="r2v"&&t==="image"&&(n==="first_frame"||n==="last_frame")?"image":n}function ed(e,t){const n=t.map(i=>({...i,target:Hi(e.id,i.kind,i.target)}));if(e.id!=="i2v"||e.slots.some(i=>i.targets.includes("image")))return n;const o=e.slots.flatMap(i=>i.targets).filter(i=>i==="first_frame"||i==="last_frame").filter(i=>!t.some(s=>s.target===i));let r=0;return n.map(i=>{if(i.kind!=="image"||i.target!=="image")return i;const s=o[r++];return s?{...i,target:s}:i})}function Mt(e){return e==="replace_audio"?"replacement audio":e==="first_frame"?"first frame":e==="last_frame"?"last frame":`${e} reference`}function go(e,t){const n=e.id==="default"||e.id==="text"?"this model":e.id.toUpperCase(),o=n==="this model"?"This model":n,r=new Map(e.slots.map(l=>[l.field,0])),i=ed(e,t).sort((l,u)=>+(u.target!==u.kind)-+(l.target!==l.kind));for(const l of i){const u=e.slots.filter(f=>f.kind===l.kind&&f.targets.includes(l.target));if(u.length===0)return`${o} does not accept ${Mt(l.target)} inputs. Change the type or remove that input.`;const d=u.filter(f=>f.max===null||(r.get(f.field)??0)<f.max).sort((f,g)=>{const p=+((r.get(f.field)??0)<f.min);return+((r.get(g.field)??0)<g.min)-p||f.targets.length-g.targets.length})[0];if(!d){const f=u.reduce((g,p)=>g+(p.max??0),0);return`${o} accepts at most ${f} ${Mt(l.target)} input${f===1?"":"s"}. Remove an input or change the model.`}r.set(d.field,(r.get(d.field)??0)+1)}const s=e.slots.find(l=>(r.get(l.field)??0)<l.min);if(s)return`Add at least ${s.min} ${Mt(s.targets[0]??s.kind)} input${s.min===1?"":"s"} for ${n}.`;const a=e.requiredGroups.find(l=>!l.some(u=>(r.get(u)??0)>0));return a?`Add at least one ${[...new Set(e.slots.filter(l=>a.includes(l.field)).flatMap(l=>l.targets).map(Mt))].join(" or ")} input for ${n}.`:null}function td(e){const t=h(e),n=h(t?.mentions),o=Array.isArray(n?.prompt_leaks)?n.prompt_leaks.flatMap(i=>{const s=h(i),a=x(s?.token),c=x(s?.code),l=x(s?.message);return a&&c&&l?[{token:a,code:c,message:l}]:[]}):[],r=Array.isArray(n?.url_placeholders)?n.url_placeholders.flatMap(i=>{const s=h(i),a=x(s?.path),c=x(s?.reference),l=x(s?.url);return a&&c&&l?[{path:a,reference:c,url:l}]:[]}):[];return{promptLeaks:o,urlPlaceholders:r}}function wk(e){const t=td(e).promptLeaks;return t.length===0?null:`Fix prompt references before generating: ${t.map(o=>o.message).join("; ")}`}function nd(e){return e.length>0&&e.every(t=>t.includes("historical average per call"))}function Sk(e){const t=h(h(e)?.estimate),n=Array.isArray(t?.warnings)?t.warnings.filter(r=>typeof r=="string"):[],o=nd(n);return{usd:typeof t?.usd=="number"?t.usd:null,currency:typeof t?.currency=="string"?t.currency:"USD",warnings:n,unknown:!o&&n.some(r=>/not found|unavailable|no cost adapter|unknown/iu.test(r))}}function vn(e,t,n){if(t===n)return!0;const o=new Map;for(const s of e){const a=o.get(s.source)??[];a.push(s.target),o.set(s.source,a)}const r=new Set,i=[n];for(;i.length>0;){const s=i.pop();if(!(!s||r.has(s))){if(s===t)return!0;r.add(s),i.push(...o.get(s)??[])}}return!1}function nt(e,t,n,o){if(!vn(t,n,o))return t;const r=e.find(s=>s.id===n);if(n===o||r?.type!=="image"||!r.outputArtifactId)return null;const i=t.filter(s=>s.target!==n||!vn(t,s.source,o));return vn(i,n,o)?null:i}function Ik(e,t,n=[]){const o=t.source,r=t.target;return!o||!r?!1:nt(n,e,o,r)!==null}function xk(e,t,n){return new Set(e.filter(o=>nt(e,t,o.id,n)===null).map(o=>ue(o.slot)))}function Wi(e,t){return t[e.name]??e.defaultValue}function Ak(e,t){return Object.fromEntries(e.flatMap(n=>{const o=Wi(n,t);return o===void 0?[]:[[n.name,o]]}))}function od(e,t){return e.minimum===void 0?!1:e.exclusiveMinimum?t<=e.minimum:t<e.minimum}function rd(e,t){return e.maximum===void 0?!1:e.exclusiveMaximum?t>=e.maximum:t>e.maximum}function id(e,t){const n=Wi(e,t);return n===void 0||n===""?e.required?`${e.label}: Required`:null:e.options.length>0&&!e.options.some(o=>o===n)?`${e.label}: Choose one of the listed values`:e.valueType==="number"?typeof n!="number"||!Number.isFinite(n)?`${e.label}: Enter a number`:od(e,n)?e.exclusiveMinimum?`${e.label}: Must be greater than ${e.minimum}`:`${e.label}: Must be at least ${e.minimum}`:rd(e,n)?e.exclusiveMaximum?`${e.label}: Must be less than ${e.maximum}`:`${e.label}: Must be at most ${e.maximum}`:null:typeof n===e.valueType?null:`${e.label}: Required`}function Ek(e,t){const n=e.flatMap(o=>{const r=id(o,t);return r?[r]:[]});return n.length>0?n.join("; "):null}function dt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function sd(e){return e==="image"||e==="video"||e==="audio"?e:null}function Ki(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function ir(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:void 0}function ad(e){const t=h(e),n=x(t?.name),o=x(t?.label),r=x(t?.description),i=t?.kind,s=t?.valueType;if(!n||!o||!r||i!=="select"&&i!=="boolean"&&i!=="number"&&i!=="text"||s!=="string"&&s!=="number"&&s!=="boolean")return null;const a=ir(t?.defaultValue),c=Array.isArray(t?.options)?t.options.flatMap(m=>{const d=ir(m);return d===void 0?[]:[d]}):[],l=dt(t?.minimum),u=dt(t?.maximum);return{name:n,label:o,kind:i,valueType:s,required:t?.required===!0,...a===void 0?{}:{defaultValue:a},options:c,...l===null?{}:{minimum:l},...u===null?{}:{maximum:u},...t?.exclusiveMinimum===!0?{exclusiveMinimum:!0}:{},...t?.exclusiveMaximum===!0?{exclusiveMaximum:!0}:{},description:r}}function cd(e){const t=h(e),n=x(t?.field),o=sd(t?.kind),r=Ki(t?.targets),i=dt(t?.min),s=t?.max,a=s===null?null:dt(s);return!n||!o||r.length===0||i===null||s!==null&&a===null?null:{field:n,kind:o,targets:r,min:i,max:a}}function ld(e){const t=h(e),n=x(t?.id);if(!n||!Array.isArray(t?.slots))return null;const o=t.slots.map(cd).filter(i=>i!==null),r=Array.isArray(t.requiredGroups)?t.requiredGroups.map(Ki).filter(i=>i.length>0):[];return{id:n,slots:o,requiredGroups:r}}function ud(e){const t=h(e);if(!Array.isArray(t?.modes))return null;const n=t.modes.map(ld).filter(o=>o!==null);return n.length>0?{modes:n}:null}function dd(e){const n=h(e)?.actions;return Array.isArray(n)?n.flatMap(o=>{const r=h(o);if(!r||r.kind!=="generation")return[];const i=x(r.provider),s=x(r.model),a=x(r.operation),c=x(r.tool),l=x(r.title),u=ud(r.inputContract),m=Array.isArray(r.controls)?r.controls.map(ad).filter(g=>g!==null):[],d=Array.isArray(r.cellTypes)?r.cellTypes.filter(g=>typeof g=="string"&&vt(g)):[];if(!i||!s||!a||!c||!u||d.length===0)return[];const f=dt(r.defaultPriority);return[{id:x(r.id)??`generation.${c}`,cellTypes:d,provider:i,providerLabel:x(r.providerLabel)??i,model:s,operation:a,tool:c,title:l??c,isDefault:r.isDefault===!0,defaultPriority:f,inputContract:u,controls:m,...r.existingCellOnly===!0?{existingCellOnly:!0}:{}}]}):[]}function ho(e,t,n=!1){return e.filter(o=>o.cellTypes.includes(t)&&(n||!o.existingCellOnly))}function Gn(e){return{provider:e.provider,model:e.model,operation:e.operation,tool:e.tool}}function fd(e){return{provider:e.provider?.trim()??"",model:e.model?.trim()??"",operation:e.operation?.trim()??"",tool:e.tool?.trim()??""}}function Tt(e,t){return["provider","model","operation","tool"].reduce((n,o)=>t[o]&&e[o]===t[o]?n+1:n,0)}function zi(e,t,n){const o=ho(e,t,!0).filter(c=>!c.existingCellOnly||c.tool===n.tool&&c.model===n.model),r=n.model?o.find(c=>c.model===n.model&&(!n.tool||c.tool===n.tool)):void 0;if(r)return r;const i=n.tool?o.filter(c=>c.tool===n.tool).sort((c,l)=>Tt(l,n)-Tt(c,n))[0]:void 0;if(i)return i;const s=n.model?o.find(c=>c.tool===n.model):void 0;return s||(n.model?o.filter(c=>c.model===n.model):n.operation?o.filter(c=>c.operation===n.operation):n.provider?o.filter(c=>c.provider===n.provider):[]).reduce((c,l)=>!c||Tt(l,n)>Tt(c,n)?l:c,null)}function qn(e){return e.type==="image"||e.type==="generate_image"?"image":e.type==="video"||e.type==="split_video"||e.type==="generate_video"||e.type==="concat"||e.type==="splice"?"video":e.type==="audio"||e.type==="extract_audio"||e.type==="generate_audio"?"audio":null}function Xi(e,t){return t==="first_frame"||t==="last_frame"||e==="audio"&&t==="replace_audio"?t:e}function Ck(e,t,n){const o=new Map(t.map(r=>[r.id,r]));return n.flatMap(r=>{if(r.target!==e)return[];const i=o.get(r.source),s=i?qn(i):null;return s?[{kind:s,target:Xi(s,r.targetInput)}]:[]})}function md(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}_${n}`);)n+=1;return`${e}_${n}`}function Mk(e,t,n,o,r){const i=e.inputContract.modes.find(f=>f.id===t);if(!i)return[];const s=new Map(o.map(f=>[f.id,f])),a=r.filter(f=>f.target===n),c=a.flatMap(f=>{const g=s.get(f.source),p=g?qn(g):null;return p?[{sourceCellId:f.source,targetInput:f.targetInput,target:Hi(t,p,Xi(p,f.targetInput)),kind:p}]:[]}),l=new Set(a.map(f=>f.source)),u=new Set(a.map(f=>f.targetInput)),m=[],d=new Set;for(const f of o.filter(g=>g.id!==n).sort((g,p)=>g.slot.row-p.slot.row||g.slot.column-p.slot.column)){if(l.has(f.id)||nt(o,r,f.id,n)===null)continue;const g=qn(f);if(g)for(const p of i.slots){if(p.kind!==g)continue;const y=c.filter(v=>v.kind===p.kind&&p.targets.includes(v.target)).length;if(!(p.max!==null&&y>=p.max))for(const v of p.targets){const S=`${f.id}:${v}`;d.has(S)||(d.add(S),m.push({sourceCellId:f.id,targetInput:md(v,u),target:v,kind:g}))}}}return m}function St(e,t){return e.inputContract.modes.filter(n=>go(n,t)===null)}function Tk(e,t,n){const o=e.inputContract.modes.find(r=>r.id===t);return!!(o&&go(o,n)===null)}function Rk(e,t,n=""){return n&&e.inputContract.modes.some(o=>o.id===n)?n:St(e,t)[0]?.id??e.inputContract.modes[0]?.id??""}function $k(e){return{t2v:"T2V · Text to video",i2v:"I2V · Image to video",r2v:"R2V · Reference to video",v2v:"V2V · Video to video",t2i:"T2I · Text to image",i2i:"I2I · Image to image",t2a:"T2A · Text to audio"}[e]??e.replaceAll("-"," ").replace(/^./,n=>n.toUpperCase())}function ln(e,t){return e.inputContract.modes.some(n=>go(n,t)===null)}function pd(e,t){const n=e.defaultPriority??Number.POSITIVE_INFINITY,o=t.defaultPriority??Number.POSITIVE_INFINITY;if(n!==o)return n-o;const r=e.title.localeCompare(t.title);if(r!==0)return r;const i=e.providerLabel.localeCompare(t.providerLabel);return i!==0?i:e.model.localeCompare(t.model)}function gd(e,t,n,o=!1){return ho(e,t,o).filter(r=>ln(r,n)).sort(pd)}function hd(e,t,n=[]){if(!vt(e.type))return null;const o=fd(e),r=zi(t,e.type,o);if(r)return Gn(r);if(Object.values(o).every(Boolean))return o;const i=gd(t,e.type,n)[0];return i?Gn(i):null}function bo(e){return Gn(e)}function bd(e){return e.replace(/\b(image|text|reference|video|audio|frame)[\s-]+to[\s-]+(video|image|audio|text)\b/gi,(t,n,o)=>`${n[0]}2${o[0]}`.toUpperCase())}const Nk="Edit video follows the source aspect ratio and duration. Connect one 4–30 second video plus optional image or audio references.";function Yi(e,t){return e==="kie:bytedance/seedance-2-5"&&t==="v2v"}const kn=[{id:"t2v",label:"Text to video",roles:[]},{id:"i2v",label:"Frames",roles:["first_frame","last_frame"],requireAny:["first_frame","last_frame"]},{id:"r2v",label:"References",roles:["image","video","audio"],requireAny:["image","video","audio"]}],Rt=[{id:"i2v",label:"Frames",roles:["first_frame","last_frame"]}],wn={aspect_ratio:"auto",duration:5,generate_audio:!0,resolution:"720p",reasoning_level:"high"},yd=[{id:"r2v",label:"References",roles:["image","video","audio"],requireAny:["image","video","audio"]},{id:"v2v",label:"Edit video",roles:["video","image","audio"],requireAny:["video"],defaults:{task:"editing"}},{id:"extend",label:"Extend video",roles:["video","image","audio"],requireAny:["video"],defaults:{task:"extension"}}],_d=[{id:"i2v",label:"Image to video",roles:["first_frame"]},{id:"r2v",label:"References",roles:["image"]},{id:"v2v",label:"Edit video",roles:["video"],requireAny:["video"]}],zt="Speaker 1";function sr(e,t){return{id:e,media:"audio",operations:["speech"],title:t,prompt:"dialogue_turns.0.text",aliases:{voice:"speakers.0.voice_name",accent:"speakers.0.accent",style:"speakers.0.style",pace:"speakers.0.pace"},defaults:{speakers:[{speaker_id:zt,voice_name:"Kore",accent:"Neutral"}],dialogue_turns:[{speaker_id:zt}]}}}function ar(e,t){return{id:e,media:"audio",operations:["speech"],title:t,prompt:"dialogue_turns.0.text",aliases:{voice:"speakers.0.voice_name",style:"dialogue_turns.0.style"},defaults:{speakers:[{speaker_id:zt,voice_name:"Fola"}],dialogue_turns:[{speaker_id:zt}]}}}function cr(e,t){return{id:e,media:"audio",operations:["speech"],title:t,defaults:{voice:"Rachel"}}}function ot(e){return{id:`fal:minimax/h3-max/styles/${e}`,media:"video",operations:["text_to_video","image_to_video"],dialect:"strip_frames"}}const vd=[{id:"kie:nano-banana-2-1",media:"image",operations:["text_to_image","edit_image"],dialect:"natural_numbered",defaults:{...ua}},{id:"kie:flux-3/klein-text-to-image",media:"image",operations:["text_to_image"],dialect:"natural",defaults:{resolution:"1K"}},{id:"kie:flux-3/klein-edit-image",media:"image",operations:["edit_image"],dialect:"natural",defaults:{resolution:"1K"}},{id:"kie:nano-banana-pro",media:"image",operations:["text_to_image","edit_image"],guide:"nano_banana",dialect:"natural"},{id:"kie:gpt-image-2-5-flare-text-to-image",media:"image",operations:["text_to_image"],guide:"gpt_image",dialect:"natural",defaults:{resolution:"2K"}},{id:"kie:gpt-image-2-5-flare-image-to-image",media:"image",operations:["edit_image"],guide:"gpt_image",dialect:"natural",defaults:{resolution:"2K"}},{id:"kie:gpt-image-2-5-sunburst-text-to-image",media:"image",operations:["text_to_image"],guide:"gpt_image",dialect:"natural",defaults:{resolution:"2K"}},{id:"kie:gpt-image-2-5-sunburst-image-to-image",media:"image",operations:["edit_image"],guide:"gpt_image",dialect:"natural",defaults:{resolution:"2K"}},{id:"kie:gpt-image-2-image-to-image",media:"image",operations:["edit_image"],title:"GPT Image 2 Edit",dialect:"natural",hidden:!0},{id:"kie:seedream/5-pro-image-to-image",media:"image",operations:["edit_image"],dialect:"natural",hidden:!0},{id:"kie:grok-imagine/text-to-image",media:"image",operations:["text_to_image"],guide:"grok_image"},{id:"kie:grok-imagine/image-to-image",media:"image",operations:["edit_image"],guide:"grok_image",dialect:"natural"},{id:"kie:qwen2/image-edit",media:"image",operations:["edit_image"],dialect:"natural"},{id:"kie:qwen3/image-to-image",media:"image",operations:["edit_image"],dialect:"natural"},{id:"kie:qwen2-1/text-to-image",media:"image",operations:["text_to_image"],dialect:"natural"},{id:"kie:qwen2-1/image-to-image",media:"image",operations:["edit_image"],dialect:"natural"},{id:"kie:seedream/5-lite-text-to-image",media:"image",operations:["text_to_image"]},{id:"kie:seedream/5-lite-image-to-image",media:"image",operations:["edit_image"],dialect:"natural"},{id:"kie:seedream/5-flash-text-to-image",media:"image",operations:["text_to_image"]},{id:"kie:seedream/5-flash-image-to-image",media:"image",operations:["edit_image"]},{id:"kie:seedream/5-flash-layer-decomposition",media:"image",operations:["layer_image"]},{id:"alibaba:qwen-image-2.0-pro",media:"image",operations:["text_to_image"],title:"Qwen Image 2.0 Pro (Alibaba)"},{id:"alibaba:qwen-image-edit-plus",media:"image",operations:["edit_image"],title:"Qwen Image Edit Plus (Alibaba)"},{id:"fal:fal-ai/nano-banana",media:"image",operations:["text_to_image"],guide:"nano_banana",hidden:!0},{id:"fal:fal-ai/nano-banana/edit",media:"image",operations:["edit_image"],guide:"nano_banana",hidden:!0},{id:"fal:fal-ai/nano-banana-2",media:"image",operations:["text_to_image"],guide:"nano_banana",hidden:!0},{id:"fal:fal-ai/nano-banana-2/edit",media:"image",operations:["edit_image"],guide:"nano_banana",hidden:!0},{id:"fal:google/nano-banana-2-lite",media:"image",operations:["text_to_image"],guide:"nano_banana",hidden:!0},{id:"fal:google/nano-banana-lite/edit",media:"image",operations:["edit_image"],guide:"nano_banana",hidden:!0},{id:"fal:fal-ai/nano-banana-pro",media:"image",operations:["text_to_image"],guide:"nano_banana",hidden:!0},{id:"fal:fal-ai/nano-banana-pro/edit",media:"image",operations:["edit_image"],guide:"nano_banana",hidden:!0},{id:"fal:google/nano-banana-2.1",media:"image",operations:["text_to_image"],guide:"nano_banana",hidden:!0},{id:"fal:google/nano-banana-2.1/edit",media:"image",operations:["edit_image"],guide:"nano_banana",hidden:!0},{id:"fal:fal-ai/bytedance/seedream/v5/lite/text-to-image",media:"image",operations:["text_to_image"],hidden:!0},{id:"fal:fal-ai/bytedance/seedream/v5/lite/edit",media:"image",operations:["edit_image"],hidden:!0},{id:"fal:xai/grok-imagine-image",media:"image",operations:["text_to_image"],guide:"grok_image",hidden:!0},{id:"fal:xai/grok-imagine-image/edit",media:"image",operations:["edit_image"],guide:"grok_image",hidden:!0},{id:"fal:fal-ai/qwen-image",media:"image",operations:["text_to_image"],hidden:!0},{id:"fal:fal-ai/qwen-image-edit",media:"image",operations:["edit_image"],hidden:!0},{id:"fal:alibaba/qwen-image-3/edit",media:"image",operations:["edit_image"]},{id:"fal:fal-ai/wan/v2.7/edit",media:"image",operations:["edit_image"],rules:{maxPromptChars:500},hidden:!0},{id:"fal:bria/fibo-edit-1.5/product-holding",media:"image",operations:["edit_image"],prompt:"instruction",refs:{image:["person_image_url","product_image_urls"]}},{id:"fal:bria/fibo-edit-1.5/virtual-try-on",media:"image",operations:["edit_image"],prompt:"instruction",refs:{image:["person_image_url","garment_image_urls"]}},{id:"fal:recraft/v4.1/flash/text-to-image",media:"image",operations:["text_to_image"]},{id:"fal:bytedance/seedream/v5/flash/text-to-image",media:"image",operations:["text_to_image"]},{id:"fal:bytedance/seedream/v5/flash/edit",media:"image",operations:["edit_image"]},{id:"fal:bytedance/seedream/v5/flash/layerize",media:"image",operations:["layer_image"]},{id:"fal:ideogram/v4.5",media:"image",operations:["text_to_image"]},{id:"fal:ideogram/v4.5/edit",media:"image",operations:["edit_image"],refs:{image:["image_url","reference_image_urls"]}},{id:"fal:blackforestlabs/flux-3/text-to-image",media:"image",operations:["text_to_image"]},{id:"fal:blackforestlabs/flux-3/edit-image",media:"image",operations:["edit_image"]},{id:"fal:bria/fibo-2/generate",media:"image",operations:["text_to_image"]},{id:"fal:bria/fibo-2/edit",media:"image",operations:["edit_image"],prompt:"instruction"},{id:"fal:fal-ai/flux-2-flex",media:"image",operations:["text_to_image"]},{id:"fal:bria/guided-remove-background",media:"image",operations:["edit_image"]},{id:"fal:bria/fibo-edit-1.5/expand",media:"image",operations:["edit_image"]},{id:"fal:fal-ai/marigold-v2",media:"image",operations:["edit_image"]},{id:"kie:bytedance/seedance-2-5",media:"video",operations:["text_to_video","image_to_video","reference_to_video","edit_video"],guide:"seedance25",dialect:"seedance",modes:[...kn,{id:"v2v",label:"Edit video",roles:["video","image","audio"],requireAny:["video"]}],defaults:{...la},frameOptions:{aspect_ratio:"adaptive"}},{id:"kie:grok-imagine/image-to-video",media:"video",operations:["image_to_video"],guide:"grok_imagine"},{id:"kie:grok-imagine/text-to-video",media:"video",operations:["text_to_video"],guide:"grok_imagine",defaults:{duration:6,resolution:"480p"}},{id:"kie:grok-imagine/extend",media:"video",operations:["extend_video"],hidden:!0},{id:"kie:grok-imagine/upscale",media:"video",operations:["upscale_video"],hidden:!0},{id:"kie:kling-3.0-omni/text-to-video",media:"video",operations:["text_to_video"],guide:"kling30",dialect:"natural",defaults:{customize_multi_shots:!1}},{id:"kie:kling-3.0-omni/image-to-video",media:"video",operations:["image_to_video"],guide:"kling30",dialect:"natural"},{id:"kie:kling-3.0-omni/reference-to-video",media:"video",operations:["reference_to_video"],guide:"kling30",dialect:"natural",defaults:{audio:!1}},{id:"kie:kling-3.0-omni/transformation",media:"video",operations:["edit_video"],guide:"kling30",dialect:"natural",modes:[{id:"v2v",label:"Edit video",roles:["video"],requireAny:["video"],defaults:{aspect_ratio:"auto"}},{id:"v2v_refs",label:"Edit with references",roles:["video","image"],requireAny:["video"]}]},{id:"kie:kling-3.0/motion-control",media:"video",operations:["motion_control"],guide:"kling30",dialect:"natural",defaults:{mode:"720p"}},{id:"kie:gemini-omni-video",media:"video",operations:["image_to_video","edit_video"],dialect:"natural_source_video",defaults:{duration:"8"},modes:[{id:"i2v",label:"Image to video",roles:["image"]},{id:"v2v",label:"Edit video",roles:["video","image"],requireAny:["video"]}],refItem:{video:{start:0,ends:8}},aliases:{clip_start:"video_list.0.start",clip_end:"video_list.0.ends"}},{id:"kie:wan/3-0-video",media:"video",operations:["text_to_video","image_to_video","reference_to_video"],dialect:"seedance",modes:kn},{id:"kie:wan/3-0-video-prime",media:"video",operations:["text_to_video","image_to_video","reference_to_video"],dialect:"seedance",modes:kn},{id:"kie:happyhorse-1-1/text-to-video",media:"video",operations:["text_to_video"]},{id:"kie:happyhorse-1-1/image-to-video",media:"video",operations:["image_to_video"],dialect:"strip_frames"},{id:"kie:happyhorse-1-1/reference-to-video",media:"video",operations:["reference_to_video"],dialect:"brackets"},{id:"kie:happyhorse/video-edit",media:"video",operations:["edit_video"],dialect:"happyhorse_edit"},{id:"kie:minimax-h3/text-to-video",media:"video",operations:["text_to_video"]},{id:"kie:minimax-h3/image-to-video",media:"video",operations:["image_to_video"],dialect:"strip_frames"},{id:"kie:minimax-h3/reference-to-video",media:"video",operations:["reference_to_video"],dialect:"natural",rules:{refDurationMs:Bs}},{id:"kie:volcengine/video-to-video-lip-sync",media:"video",operations:["lip_sync"]},{id:"kie:omnihuman-1-5",media:"video",operations:["image_to_video","lip_sync"],dialect:"natural"},{id:"kie:vidu-q4/image-to-video",media:"video",operations:["image_to_video"],dialect:"natural_kinds"},{id:"kie:vidu-q4/reference-to-video",media:"video",operations:["reference_to_video"],dialect:"natural_kinds"},{id:"kie:veo3",media:"video",operations:["text_to_video","image_to_video"],title:"Veo 3 (Kie)"},{id:"kie:veo3_fast",media:"video",operations:["text_to_video","image_to_video"],title:"Veo 3 Fast (Kie)"},{id:"xai:grok-imagine-video",media:"video",operations:["text_to_video","image_to_video","reference_to_video","edit_video"],guide:"grok_imagine",title:"Grok Imagine Video (xAI)",dialect:"natural",refs:{first_frame:"image",audio:null},modes:_d},{id:"fal:xai/grok-imagine-video/image-to-video",media:"video",operations:["image_to_video"],guide:"grok_imagine",hidden:!0},{id:"fal:xai/grok-imagine-video/reference-to-video",media:"video",operations:["reference_to_video"],guide:"grok_imagine",hidden:!0},{id:"fal:xai/grok-imagine-video/extend-video",media:"video",operations:["extend_video"],hidden:!0},{id:"fal:xai/grok-imagine-video/edit-video",media:"video",operations:["edit_video"],guide:"grok_imagine",hidden:!0},{id:"fal:xai/grok-imagine-video/v1.5/lite/image-to-video",media:"video",operations:["image_to_video"]},{id:"fal:xai/grok-imagine-video/v1.5/lite/text-to-video",media:"video",operations:["text_to_video"]},{id:"fal:alibaba/wan-3.0/text-to-video",media:"video",operations:["text_to_video"],hidden:!0},{id:"fal:alibaba/wan-3.0/image-to-video",media:"video",operations:["image_to_video"],hidden:!0},{id:"fal:alibaba/wan-3.0/reference-to-video",media:"video",operations:["reference_to_video"],hidden:!0},{id:"fal:alibaba/wan-3.0-prime/text-to-video",media:"video",operations:["text_to_video"],hidden:!0},{id:"fal:alibaba/wan-3.0-prime/image-to-video",media:"video",operations:["image_to_video"],hidden:!0},{id:"fal:alibaba/wan-3.0-prime/reference-to-video",media:"video",operations:["reference_to_video"],hidden:!0},{id:"fal:blackforestlabs/flux-3-max/text-to-video",media:"video",operations:["text_to_video"],title:"FLUX 3 Max",defaults:wn},{id:"fal:blackforestlabs/flux-3-max/image-to-video",media:"video",operations:["image_to_video"],title:"FLUX 3 Max Image",refs:{first_frame:"image_url"},modes:Rt,defaults:wn},{id:"fal:blackforestlabs/flux-3-max/keyframes-to-video",media:"video",operations:["image_to_video"],title:"FLUX 3 Max Keyframes",refs:{image:"keyframes"},keyframeFps:24,defaults:wn},{id:"fal:minimax/h3-max/reframe-video",media:"video",operations:["edit_video"]},{id:"fal:minimax/h3-max/insert-video",media:"video",operations:["edit_video"],refs:{video:["video_url","reference_video_urls"]}},{id:"fal:minimax/h3-max/recast",media:"video",operations:["edit_video"]},{id:"fal:minimax/h3-max-turbo/extend-video",media:"video",operations:["extend_video"]},{id:"fal:minimax/h3-max/relight",media:"video",operations:["edit_video"]},ot("16bit-pixel"),ot("hand-drawn"),ot("low-poly"),ot("retro-toon-70s"),ot("vhs"),{id:"fal:bytedance/seedance-2.5/us/text-to-video",media:"video",operations:["text_to_video"],guide:"seedance25",dialect:"seedance",hidden:!0},{id:"fal:bytedance/seedance-2.5/us/image-to-video",media:"video",operations:["image_to_video"],guide:"seedance25",dialect:"seedance",refs:{first_frame:"image_url"},modes:Rt,hidden:!0},{id:"fal:bytedance/seedance-2.5/us/reference-to-video",media:"video",operations:["reference_to_video","edit_video","extend_video"],guide:"seedance25",dialect:"seedance",modes:yd,hidden:!0},{id:"fal:bytedance/seedance-2.5/draft/complete",media:"video",operations:["upscale_video"],title:"Seedance 2.5 Draft Complete",hidden:!0},{id:"fal:bytedance/seedance-2.0/us/text-to-video",media:"video",operations:["text_to_video"],guide:"seedance2",dialect:"seedance"},{id:"fal:bytedance/seedance-2.0/us/image-to-video",media:"video",operations:["image_to_video"],guide:"seedance2",dialect:"seedance",refs:{first_frame:"image_url"},modes:Rt},{id:"fal:bytedance/seedance-2.0/us/reference-to-video",media:"video",operations:["reference_to_video"],guide:"seedance2",dialect:"seedance",modes:[{id:"r2v",label:"References",roles:["image","video","audio"],requireAny:["image","video"]}]},{id:"fal:fal-ai/kling-video/o3/standard/image-to-video",media:"video",operations:["image_to_video"],guide:"kling30",dialect:"strip_frames",refs:{first_frame:"image_url"},modes:Rt},{id:"fal:fal-ai/kandinsky6-pro/text-to-video",media:"video",operations:["text_to_video"]},{id:"fal:fal-ai/kandinsky6-pro/image-to-video",media:"video",operations:["image_to_video"],dialect:"strip_frames"},{id:"fal:fal-ai/kandinsky6-lite/text-to-video",media:"video",operations:["text_to_video"]},{id:"fal:fal-ai/kandinsky6-lite/image-to-video",media:"video",operations:["image_to_video"],dialect:"strip_frames"},{id:"fal:fal-ai/kandinsky6-vsr",media:"video",operations:["upscale_video"]},{id:"fal:fal-ai/kandinsky6-vsr/lite",media:"video",operations:["upscale_video"]},{id:"fal:fal-ai/vidu/q4/image-to-video",media:"video",operations:["image_to_video"],dialect:"natural_kinds",hidden:!0},{id:"fal:fal-ai/vidu/q4/reference-to-video",media:"video",operations:["reference_to_video"],dialect:"vidu",hidden:!0},{id:"fal:pixverse/music-video/vibemv",media:"video",operations:["reference_to_video"],refs:{image:["image_url","style_image_url"]}},{id:"fal:pixelcut/looping-video",media:"video",operations:["image_to_video"],dialect:"strip_frames"},{id:"fal:creatify/boreal",media:"video",operations:["text_to_video","image_to_video","lip_sync"]},{id:"fal:mirelo-ai/sfx2.0/video-to-video",media:"video",operations:["edit_video"],prompt:"text_prompt",defaults:{num_samples:1}},{id:"elevenlabs:text-to-speech",media:"audio",operations:["speech"],title:"ElevenLabs Text to Speech",defaults:{model_id:"eleven_multilingual_v2"}},{id:"elevenlabs:sound-generation",media:"audio",operations:["sfx"],title:"ElevenLabs Sound Effects"},{id:"elevenlabs:music",media:"audio",operations:["music"],title:"ElevenLabs Music",defaults:{force_instrumental:!0}},{id:"elevenlabs:video-to-music",media:"audio",operations:["video_to_music"],title:"ElevenLabs Video to Music"},{id:"kie:elevenlabs/sound-effect-v2",media:"audio",operations:["sfx"]},cr("kie:elevenlabs/text-to-speech-multilingual-v2","ElevenLabs Multilingual v2 (Kie)"),cr("kie:elevenlabs/text-to-speech-turbo-2-5","ElevenLabs Turbo 2.5 (Kie)"),{id:"kie:elevenlabs/text-to-dialogue-v3",media:"audio",operations:["dialogue"],title:"ElevenLabs v3 Dialogue (Kie)",prompt:"dialogue.0.text",aliases:{voice:"dialogue.0.voice"},defaults:{dialogue:[{voice:"Rachel"}]}},sr("kie:google/gemini-2-5-pro-tts","Gemini 2.5 Pro TTS (Kie)"),sr("kie:google/gemini-3-1-flash-tts","Gemini 3.1 Flash TTS (Kie)"),ar("kie:google/gemini-3-8-flash-tts","Gemini 3.8 Flash TTS (Kie)"),ar("kie:google/gemini-3-8-flash-lite-tts","Gemini 3.8 Flash Lite TTS (Kie)"),{id:"kie:suno/generate",media:"audio",operations:["music"],title:"Suno (Kie)",defaults:{model:"V5_5",instrumental:!0,customMode:!1}},{id:"kie:suno/sounds-generate",media:"audio",operations:["sfx"],title:"Suno Sounds (Kie)",defaults:{model:"V5_5"}},{id:"fal:elevenlabs/music/v2.5",media:"audio",operations:["music"],defaults:{force_instrumental:!0,output_format:"mp3_48000_192"}},{id:"fal:minimax/music-3",media:"audio",operations:["music"],defaults:{lyrics:"[Instrumental]"}},{id:"fal:elevenlabs/tts/eleven-v4",media:"audio",operations:["speech"],defaults:{voice:"Rachel",output_format:"mp3_44100_128"}},{id:"fal:elevenlabs/tts/eleven-v4-turbo",media:"audio",operations:["speech"],defaults:{voice:"Rachel",output_format:"mp3_44100_128"}},{id:"fal:google/gemini-3.8-flash-tts",media:"audio",operations:["speech"],defaults:{voice:"Kore"}},{id:"fal:google/gemini-3.8-flash-lite-tts",media:"audio",operations:["speech"],defaults:{voice:"Kore"}},{id:"fal:alibaba/qwen-audio-3-tts",media:"audio",operations:["speech"],defaults:{voice:"Cherry",language:"Auto"}},{id:"fal:fal-ai/bytedance/seed-speech/tts/v2",media:"audio",operations:["speech"],defaults:{output_format:"mp3"}}],kd=new Map(vd.map(e=>[e.id,e]));function wd(e){return kd.get(e)}const Pk="Frame mode follows the first image’s aspect ratio (adaptive).";function Sd(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=e;return[t.first_frame,t.last_frame].some(n=>typeof n=="string"&&n.trim()!==""||Array.isArray(n)&&n.some(o=>typeof o=="string"&&o.trim()!==""))}function Ji(e,t){const n=wd(e)?.frameOptions?.aspect_ratio;if(typeof n!="string")return;const o=t.generationMode??t.mode;if(o!=="r2v")return o==="i2v"||Sd(t.refs)?n:void 0}const Id=200,xd={chat:"chat",image_rewrite:"image rewrite",video_rewrite:"video rewrite",script_rewrite:"script rewrite",post:"post",image_generate:"image",video_generate:"video",audio_generate:"audio"};function Ad(e){const t=h(e),o=(Array.isArray(t?.content)?t.content:[]).map(h).find(r=>r?.type==="text");return typeof o?.text=="string"?o.text:null}function Ed(e){const t=Ad(e);if(!t)return e;try{return JSON.parse(t)}catch{return null}}function Cd(e){const t=h(e);return typeof t?.model=="string"&&t.model?t.model:typeof t?.tool=="string"&&t.tool?t.tool:""}function Md(e){const t=h(e);return!t||typeof t.prompt!="string"||!t.prompt.trim()?[]:[{id:String(t.id??""),surface:typeof t.surface=="string"?t.surface:"",prompt:t.prompt,book:typeof t.book=="string"?t.book:"",model:Cd(t.params),createdAt:typeof t.created_at=="number"?t.created_at:0}]}function Td(e){const t=h(Ed(e));return(Array.isArray(t?.entries)?t.entries:[]).flatMap(Md)}function Rd(e){const t=new Set;return e.filter(n=>{const o=n.prompt.trim();return t.has(o)?!1:(t.add(o),!0)})}function Ok(e,t){const n=t.trim().toLowerCase();return n?e.filter(o=>o.prompt.toLowerCase().includes(n)):[...e]}function Lk(e,t){const n=e.filter(r=>t.has(r.prompt)),o=e.filter(r=>!t.has(r.prompt));return[...n,...o]}function $d(e){return{book_id:e.bookId,scope:e.scope,limit:Id,...e.surfaceFilter==="surface"?{surface:e.surface}:{}}}function Fk(e){return xd[e]??e.replaceAll("_"," ")}function Nd(e){return e<1e12?e*1e3:e}function Dk(e,t){if(!e)return"";const n=Math.max(0,Math.floor((t-Nd(e))/6e4));if(n<1)return"just now";if(n<60)return`${n}m ago`;const o=Math.floor(n/60);if(o<24)return`${o}h ago`;const r=Math.floor(o/24);return r===1?"yesterday":`${r}d ago`}function Zi(e,t){return e.cells.find(n=>n.slot.row===t.row&&n.slot.column===t.column)}function Z(e){return ue(e.slot)}function Qi(e){const t=to(e).map(n=>n.reference);return[...new Set(t)]}function yo(e,t){const n=ve(t),o=Xr(n);if(o){const a=Zi(e,o);if(!a)throw new Error(`Notebook cell ${ue(o)} is empty`);return a}const r=e.cells.find(a=>a.id.toLowerCase()===n),i=r?[]:e.cells.filter(a=>a.id.toLowerCase().startsWith(n));if(i.length>1)throw new Error(`Cell reference @${n} is ambiguous`);const s=r??i[0];if(!s)throw new Error(`Notebook cell @${n} was not found`);return s}function es(e){return Qi(e)}function _o(e){return e.type==="image"||e.type==="generate_image"?"image":e.type==="video"||e.type==="split_video"||e.type==="generate_video"||e.type==="concat"||e.type==="splice"?"video":e.type==="audio"||e.type==="extract_audio"||e.type==="generate_audio"?"audio":null}function Pd(e,t){return t==="first_frame"||t==="last_frame"||e==="audio"&&t==="replace_audio"?t:e}function ts(e){const t=new Map;return e.map(n=>{const o=(t.get(n.target)??0)+1;return t.set(n.target,o),o===1?n.target:`${n.target}_${o}`})}function ns(e){const t=e.map(s=>({kind:s.kind,target:s.kind})),n=["first_frame","last_frame"],o=e.map((s,a)=>({kind:s.kind,target:s.kind==="image"?n[a]??"image":s.kind})),r=e.map(s=>({kind:s.kind,target:s.kind==="audio"?"replace_audio":s.kind})),i=[t,o,r];return i.filter((s,a)=>i.findIndex(c=>JSON.stringify(c)===JSON.stringify(s))===a)}function os(e){const t=e.preferredModel?ho(e.actions,e.cellType).find(o=>o.model===e.preferredModel):void 0;if(t&&ln(t,e.connectedInputs))return t;const n=hd({type:e.cellType},e.actions,e.connectedInputs);return n?zi(e.actions,e.cellType,n):null}function Od(e,t){if(!t)return{};const n=t.options&&typeof t.options=="object"&&!Array.isArray(t.options)?t.options:{};return Object.fromEntries(e.controls.flatMap(o=>{const r=n[o.name]??t[o.name];return typeof r=="string"||typeof r=="number"||typeof r=="boolean"?[[o.name,r]]:[]}))}function Vk(e){return es(e)}function lr(e){return typeof e=="string"?[e]:Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function jk(e){const n=[...e.refs&&typeof e.refs=="object"&&!Array.isArray(e.refs)?Object.values(e.refs).flatMap(lr):[],...Object.entries(e).flatMap(([o,r])=>/(?:^|_)(?:ref|refs)$/u.test(o)?lr(r):[])];return es(n.map(o=>o.startsWith("@")?o:`@${o}`).join(" "))}function Gk(e,t,n){const o=n.find(i=>i.tool===e);if(o?.cellTypes[0])return o.cellTypes[0];const r=`${t} ${e}`.toLowerCase();return/audio|music|speech|t2a|voice/iu.test(r)?"generate_audio":/image|photo|picture|qart|qr/iu.test(r)?"generate_image":"generate_video"}function rs(e,t){const n=_o(t);if(!n)throw new Error(`${Z(t)} is not a media-producing cell`);if(!Le(e,t))throw new Error(`${Z(t)} does not have media output yet`);return{cell:t,kind:n}}function Ld(e,t){return t.map(n=>rs(e,yo(e,n)))}function qk(e,t=[],n){const o=new Set(t);return e.cells.flatMap(r=>{if(o.has(r.id))return[];if(n&&nt(e.cells,e.edges,r.id,n)===null)return[];const i=_o(r);return!i||!Le(e,r)?[]:[{cell:r,kind:i}]})}function Uk(e){const t=Ld(e.document,e.command.sourceReferences),n=t.find(g=>nt(e.document.cells,e.document.edges,g.cell.id,e.cellId)===null);if(n)throw new Error(`Connecting ${Z(n.cell)} would create a cycle`);let o=null,r=[];for(const g of ns(t)){const p=os({actions:e.actions,cellType:e.command.cellType,connectedInputs:g,...e.preferredModel?{preferredModel:e.preferredModel}:{}});if(p){o=p,r=g;break}}if(!o)throw new Error(`No available ${e.command.mediaKind} generation action accepts these references`);const i=bo(o),s=St(o,r)[0],a=Od(o,e.routedParams),c={...s?{generationMode:s.id}:{},...Object.keys(a).length>0?{generationSettings:a}:{}},l=t.map(g=>g.cell.slot),u=e.lastWorkSlot??null,m=e.command.cellType==="generate_video"?uo(e.document.cells,l,u):e.command.cellType==="generate_image"||e.command.cellType==="generate_audio"?an(e.document.cells,l,u):e.fallbackSlot,d={id:e.cellId,type:e.command.cellType,slot:m,prompt:e.command.prompt,...i,...Object.keys(c).length>0?{inputs:c}:{}},f=ts(r);return{action:o,cell:d,connections:t.map((g,p)=>({sourceCellId:g.cell.id,targetInput:f[p]??g.kind})),sourceCellIds:t.map(g=>g.cell.id),sourceAddresses:t.map(g=>Z(g.cell))}}function Bk(e,t){const n=new Set(e.sourceCellIds);for(const o of Qi(e.cell.prompt??"")){const r=yo(t,o);if(!n.has(r.id))throw new Error(`@${o} is referenced but not connected`)}}function Fd(e,t){const n=e.connections.map(r=>({source:r.sourceCellId,target:e.cell.id,targetInput:r.targetInput})),o=new Map(Qu(e.cell.id,t.cells,n,x(e.cell.inputs?.generationMode)??void 0).map(r=>[r.sourceCellId,r.token]));return zr(e.cell.prompt??"",t.cells.flatMap(r=>{const i=o.get(r.id);return i?[{reference:yt(r.slot),replacement:`@${i}`}]:[]}))}function Hk(e,t){return e.connections.flatMap(n=>{const o=t.cells.find(i=>i.id===n.sourceCellId),r=o?_o(o):null;return r?[{kind:r,target:Pd(r,n.targetInput)}]:[]})}function vo(e){const t=h(e.cell.inputs),n=h(t?.generationSettings),o=Object.fromEntries(Object.entries(n??{}).flatMap(([i,s])=>typeof s=="string"||typeof s=="number"||typeof s=="boolean"?[[i,s]]:[]));if(Yi(e.action.model,t?.generationMode))return{...o,aspect_ratio:"adaptive",duration:-1};const r=Ji(e.action.model,t??{});return r?{...o,aspect_ratio:r}:o}function Wk(e,t){return{...e,cell:{...e.cell,prompt:t}}}function Kk(e,t,n){if(!t.cellTypes.includes(e.cell.type)||!ln(t,n))throw new Error("The selected generation model does not accept these inputs");const o=St(t,n),r=h(e.cell.inputs)??{},i=x(r.generationMode),s=o.find(l=>l.id===i)??o[0];if(!s)throw new Error("The selected generation model does not have a compatible mode");const a=vo(e),c=Object.fromEntries(t.controls.flatMap(l=>{const u=a[l.name];return u===void 0?[]:[[l.name,u]]}));return{...e,action:t,cell:{...e.cell,...bo(t),inputs:{...r,generationMode:s.id,generationSettings:c}}}}function zk(e,t,n){const o=St(e.action,n).find(r=>r.id===t);if(!o)throw new Error("The selected generation type does not accept these inputs");return{...e,cell:{...e.cell,inputs:{...h(e.cell.inputs)??{},generationMode:o.id}}}}function Xk(e,t,n){if(!e.action.controls.some(r=>r.name===t))throw new Error(`The selected generation model does not support ${t}`);const o=vo(e);return n===void 0?delete o[t]:o[t]=n,{...e,cell:{...e.cell,inputs:{...h(e.cell.inputs)??{},generationSettings:o}}}}function Yk(e){const t=e.draft.cell.type,n=[...new Set(e.sourceCellIds)].map(f=>{const g=e.document.cells.find(p=>p.id===f);if(!g)throw new Error("The selected source cell is no longer available");if(nt(e.document.cells,e.document.edges,g.id,e.draft.cell.id)===null)throw new Error(`Connecting ${Z(g)} to ${Z(e.draft.cell)} would create a cycle`);return rs(e.document,g)}),o=ns(n);let r=null,i=[];for(const f of o)if(ln(e.draft.action,f)){r=e.draft.action,i=f;break}if(!r)for(const f of o){const g=os({actions:e.actions,cellType:t,connectedInputs:f});if(g){r=g,i=f;break}}if(!r){const f=t==="generate_audio"?"audio":t==="generate_image"?"image":"video";throw new Error(`No available ${f} generation action accepts these references`)}const s=St(r,i),a=h(e.draft.cell.inputs)??{},c=x(a.generationMode),l=s.find(f=>f.id===c)??s[0];if(!l)throw new Error("The selected generation model does not have a compatible mode");const u=vo(e.draft),m=Object.fromEntries(r.controls.flatMap(f=>{const g=u[f.name];return g===void 0?[]:[[f.name,g]]})),d=ts(i);return{action:r,cell:{...e.draft.cell,...bo(r),inputs:{...a,generationMode:l.id,generationSettings:m}},connections:n.map((f,g)=>({sourceCellId:f.cell.id,targetInput:d[g]??f.kind})),sourceCellIds:n.map(f=>f.cell.id),sourceAddresses:n.map(f=>Z(f.cell))}}async function Jk(e){let t=!1;try{const n=h(await e.callTool("create_notebook_cell",{book_id:e.bookId,notebook_id:e.document.id,...e.expectedRevision?{expected_revision:e.expectedRevision}:{},cell:{id:e.draft.cell.id,type:e.draft.cell.type,slot:e.draft.cell.slot,prompt:Fd(e.draft,e.document),provider:e.draft.cell.provider,model:e.draft.cell.model,operation:e.draft.cell.operation,tool:e.draft.cell.tool,inputs:e.draft.cell.inputs}})),o=x(n?.id);if(!o||o!==e.draft.cell.id)throw new Error("The server did not preserve the planned generation cell");t=!0;for(const r of e.draft.connections)await e.callTool("connect_notebook_cells",{book_id:e.bookId,notebook_id:e.document.id,source_cell_id:r.sourceCellId,target_cell_id:o,target_input:r.targetInput});return{cellId:o,cellAddress:x(n?.address)??Z(e.draft.cell),sourceCellIds:e.draft.sourceCellIds,sourceAddresses:e.draft.sourceAddresses}}catch(n){throw t&&await e.callTool("delete_notebook_cell",{book_id:e.bookId,notebook_id:e.document.id,cell_id:e.draft.cell.id}).catch(()=>{}),n}}const Dd=new Set(["","text","number","url","search","email","tel","date","time","datetime-local","password"]);function Vd(e){return!e||e.tagName.toLowerCase()!=="input"?!1:Dd.has((e.type??"").toLowerCase())}function Zk(e,t){return e.defaultPrevented?"none":e.key==="Escape"?t.busy?"none":"cancel":e.key!=="Enter"||e.altKey||t.busy?"none":e.metaKey||e.ctrlKey||Vd(e.target)?"apply":"none"}const Qk={transcribing:!1,analyzing:!1,error:null};function ew(e,t){return t==="transcript"?e.transcribing:e.analyzing}function tw(e,t){return e==="transcript"?{transcribing:t}:{analyzing:t}}const nw="GPT-4o Translation",ow="ElevenLabs Transcript";function jd(e){return e==="timed"||e==="plain"||e==="silence"?e:null}function ur(e){return Array.isArray(e)?e.flatMap(t=>{const n=x(t);return n?[n]:[]}):[]}function is(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function Gd(e){return Array.isArray(e)?e.flatMap(t=>{const n=h(t);return!n||typeof n.text!="string"?[]:typeof n.start!="number"||!Number.isFinite(n.start)?[]:typeof n.end!="number"||!Number.isFinite(n.end)?[]:[{text:n.text,start:n.start,end:n.end}]}):[]}function Sn(e){const t=h(e),n=t&&jd(t.kind);return!t||!n?null:{kind:n,languageCode:x(t.language_code??t.languageCode),text:typeof t.text=="string"?t.text:"",wordCount:is(t.word_count??t.wordCount),words:Gd(t.words)}}function qd(e){const t=h(e);if(!t)return null;if("elevenlabs"in t||"plain"in t){const o=Sn(t.elevenlabs),r=Sn(t.plain);return!o&&!r?null:{elevenlabs:o,plain:r}}const n=Sn(t);return n?n.kind==="plain"?{elevenlabs:null,plain:n}:{elevenlabs:n,plain:null}:null}function Ud(e){const t=h(e);return t?{summary:typeof t.summary=="string"?t.summary:"",mood:x(t.mood),setting:x(t.setting),tags:ur(t.tags),subjects:ur(t.subjects),sceneCount:is(t.scene_count??t.sceneCount)}:null}function rw(e){return e==="video"||e==="audio"||e==="final"}function iw(e){return!!(e&&e.kind!=="silence"&&e.text.trim())}function Bd(e){if(e.kind==="silence")return"No dialog detected";const t=[e.kind==="timed"?"Word-timed":"Plain text",`${e.wordCount} ${e.wordCount===1?"word":"words"}`];return e.languageCode&&t.push(e.languageCode),t.join(" · ")}const Hd=.4,Wd=12;function Kd(e){const t=[];let n=[];for(const o of e){const r=n.at(-1),i=r?o.start-r.end:0,s=r?/[.!?]$/.test(r.text.trim()):!1;if(n.length>0&&(i>Hd||s||n.length>=Wd)){const a=n.map(c=>c.text).join(" ").replace(/\s+/g," ").trim();a&&t.push({start:n[0].start,text:a}),n=[]}n.push(o)}if(n.length>0){const o=n.map(r=>r.text).join(" ").replace(/\s+/g," ").trim();o&&t.push({start:n[0].start,text:o})}return t}function zd(e){const t=Math.max(0,Math.floor(e)),n=Math.floor(t/60),o=t%60;return`${n}:${String(o).padStart(2,"0")}`}function Xd(e){return Kd(e).map(t=>`${zd(t.start)} ${t.text}`).join(`
14
+ `)}function sw(e,t){return t==="json"&&e?"json":"text"}function Yd(e){const t=e.transcript;return!t||t.kind==="silence"?"":e.source==="elevenlabs"&&t.kind==="timed"&&t.words.length>0?Xd(t.words):t.text}function Jd(e){return e.view==="json"?e.jsonText??"":Yd(e)}function aw(e){return Jd(e)}function cw(e){return e.view==="json"?e.jsonFile?`Raw sidecar · ${e.jsonFile}`:"Raw sidecar":e.transcript?Bd(e.transcript):null}function lw(e){return e.view==="json"&&e.jsonLoading?"Loading sidecar…":e.view==="json"&&e.jsonError?e.jsonError:e.transcript?.kind==="silence"?"This clip has a transcript but no spoken dialog.":e.body?null:e.source==="plain"?"No GPT-4o translation yet.":"No transcript yet."}function uw(e){return e?.kind==="timed"}async function Zd(e,t,n,o){const r=h(await e("export_asset_file",{book_id:n,asset_id:o,to:t==="copy"?"clipboard":"downloads"},{background:!0})),i=t==="copy"?"copied":"exported";if(r?.status!==i||typeof r.path!="string")throw new Error("The server did not confirm the file action. Try again.");return t==="copy"?"File copied to clipboard":`Saved ${r.path}`}function dw({call:e,bookId:t,artifactId:n}){const[o,r]=_.useState({phase:"idle"}),i=_.useRef(!1),s=!!(e&&t&&n);async function a(c){if(!(!e||!t||!n||i.current)){i.current=!0,r({phase:"running",action:c});try{const l=await Zd(e,c,t,n);r({phase:"done",message:l})}catch(l){r({phase:"failed",message:l instanceof Error?l.message:String(l)})}finally{i.current=!1}}}return{state:o,available:s,run:a}}function Qd(e){const t=e;return t?yi(t.tags):null}function ef(e){const t=e;return!t||!Array.isArray(t.suggestions)?[]:t.suggestions.flatMap(n=>{const o=n,r=typeof o.facet=="string"?o.facet:null,i=typeof o.key=="string"?o.key:null,s=typeof o.label=="string"?o.label:null;if(!r||!i||!s)return[];const a=Number(o.assets);return[{facet:r,key:i,label:s,assets:Number.isFinite(a)?a:0}]})}function fw({call:e,target:t,tags:n}){const o=t?`${t.bookId}/${t.assetId}`:"",r=JSON.stringify(n),[i,s]=_.useState({targetKey:o,source:r,canonical:n,pending:[],error:null}),[a,c]=_.useState({targetKey:o,tags:[]}),l=_.useRef(Promise.resolve()),u=_.useRef(0),m=_.useRef(0);let d=i;(i.targetKey!==o||i.source!==r)&&(d={targetKey:o,source:r,canonical:n,pending:i.targetKey===o?i.pending:[],error:i.targetKey===o?i.error:null},s(d));const f=d.pending.reduce((I,E)=>Ho(I,E.edit,E.action),d.canonical),g=_.useCallback((I,E)=>{if(!e||!t)return Promise.resolve();let C;try{C=bi(I,[...f?.effective??[],...f?.dismissed??[],...a.targetKey===o?a.tags:[]])}catch(T){return s(N=>({...N,error:T instanceof Error?T.message:String(T)})),Promise.resolve()}const A=++u.current;s(T=>({...T,pending:[...T.pending,{id:A,edit:C,action:E}],error:null}));const $=l.current.then(async()=>{try{const T=await e("edit_asset_tag",{op:E,book_id:t.bookId,asset_id:t.assetId,facet:C.facet,label:C.label}),N=Qd(T);if(!N)throw new Error("The server returned no tag state");s(M=>M.targetKey!==o||!M.pending.some(R=>R.id===A)?M:{...M,canonical:M.source===r?N:Ho(M.canonical,C,E),pending:M.pending.filter(R=>R.id!==A)})}catch(T){s(N=>N.targetKey!==o||!N.pending.some(M=>M.id===A)?N:{...N,pending:N.pending.filter(M=>M.id!==A),error:T instanceof Error?T.message:String(T)})}});return l.current=$,$},[e,f,a,r,t,o]),p=_.useCallback(I=>g(I,"add"),[g]),y=_.useCallback(I=>g(I,"remove"),[g]),v=_.useCallback(I=>g(I,"restore"),[g]),S=_.useCallback(async(I,E)=>{if(!e||!t)return;const C=++m.current;try{const A=await e("suggest_asset_tags",{book_id:t.bookId,...I.trim()?{prefix:I.trim()}:{},...E?{facet:E}:{},limit:20},{background:!0});m.current===C&&c({targetKey:o,tags:ef(A)})}catch{m.current===C&&c({targetKey:o,tags:[]})}},[e,t,o]),w=_.useMemo(()=>vl(a.targetKey===o?a.tags:[],f?.effective??[]),[f,a,o]),k=_.useCallback(()=>s(I=>({...I,error:null})),[]);return{tags:f,busy:d.pending.length>0,error:d.error,canEdit:!!(e&&t),suggestions:w,addTag:p,removeTag:y,restoreTag:v,loadSuggestions:S,clearError:k}}const ss="videobook.prompt-history.pins";function tf(){try{const e=window.localStorage.getItem(ss),t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(n=>typeof n=="string"):[])}catch{return new Set}}function nf(e){try{window.localStorage.setItem(ss,JSON.stringify([...e]))}catch{return}}function of(e){return e instanceof Error?e.message:String(e)}function mw({call:e,bookId:t,surface:n,prompt:o,onApply:r}){const[i,s]=_.useState(!1),[a,c]=_.useState(!1),[l,u]=_.useState(null),[m,d]=_.useState(null),[f,g]=_.useState(0),[p,y]=_.useState("book"),[v,S]=_.useState("surface"),[w,k]=_.useState(""),[I,E]=_.useState(tf),[C,A]=_.useState(-1),[$,T]=_.useState(""),N=_.useRef(0),M=!!(e&&t&&n),R=C>=0&&m?.[C]?.prompt===o,D=R?C:-1,z=async(P,Y)=>{if(!e||!t||!n)return null;const Me=N.current+1;N.current=Me;const we={bookId:t,surface:n,scope:P,surfaceFilter:Y};c(!0),u(null);try{const xt=Rd(Td(await e("list_prompt_history",$d(we))));return N.current!==Me?null:(d(xt),g(Date.now()),xt)}catch(xt){return N.current===Me&&u(of(xt)),null}finally{N.current===Me&&c(!1)}},q=(P,Y,Me)=>{if(Y<0){A(-1),r(Me);return}const we=P[Y];we&&(A(Y),r(we.prompt))},J=()=>{if(!M)return;if(D>=0&&m){q(m,D+1,$);return}const P=o;T(P),z(p,v).then(Y=>{Y&&q(Y,0,P)})},pe=()=>{!R||!m||q(m,D-1,$)},ge=()=>{A(-1),r($)},K=()=>{if(i){s(!1);return}s(!0),k(""),z(p,v)},H=P=>{y(P),A(-1),z(P,v)},U=P=>{S(P),A(-1),z(p,P)},ke=P=>{const Y=new Set(I);Y.has(P)?Y.delete(P):Y.add(P),E(Y),nf(Y)},Q=P=>{A(-1),s(!1),r(P)},B=P=>P.altKey&&P.key==="ArrowUp"?(P.preventDefault(),J(),!0):P.altKey&&P.key==="ArrowDown"?(P.preventDefault(),pe(),!0):P.key==="Escape"&&R?(P.preventDefault(),P.stopPropagation(),ge(),!0):!1;return{available:M,open:i,loading:a,error:l,entries:m,loadedAt:f,scope:p,surfaceFilter:v,surface:n??"",query:w,pins:I,stepping:R,position:D+1,canOlder:M&&(m===null||!R||D<m.length-1),canNewer:R,toggleOpen:K,close:()=>s(!1),setQuery:k,setScope:H,setSurfaceFilter:U,togglePin:ke,use:Q,older:J,newer:pe,handlePromptKeyDown:B}}const rf={generate_image:"image_generate",generate_video:"video_generate",generate_audio:"audio_generate"};function pw(e){return rf[e]??null}function sf(e){return e==="image-reverse"?"image":"video"}async function gw(e,{sourceBookId:t,sourceArtifactId:n,mode:o,previewUrl:r,sourceRange:i}){const s=await e("prepare_search_reference",{source_book_id:t,source_artifact_id:n,kind:sf(o),...i?{source_start_seconds:i.startSeconds,source_duration_seconds:i.durationSeconds}:{}});return as(s,r)}function af(e,t){if(e.type.startsWith(`${t}/`))return!0;const n=e.name.split(".").at(-1)?.toLowerCase()??"";return t==="image"?["jpg","jpeg","png","webp","heic","heif"].includes(n):["mp4","mov","webm","mkv","avi"].includes(n)}function hw(e,t,n){const o=Number(e||"0");if(!Number.isFinite(o)||o<0)throw new Error("Reference start must be a non-negative number");const r=t.trim()?Number(t):void 0;if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new Error("Reference duration must be a positive number");const i=n.durationMs===void 0?void 0:n.durationMs/1e3;if(i!==void 0&&o>=i)throw new Error("Reference start must fall within the video");if(i!==void 0&&r!==void 0&&o+r>i)throw new Error("Reference range extends past the end of the video");if(!(o===0&&r===void 0))return{start_seconds:o,...r===void 0?{}:{duration_seconds:r}}}async function bw(e,t,n){if(!af(e,n))throw new Error(`Choose a compatible ${n} file`);const o=e.name.trim()||`${n}-reference.${n==="image"?"png":"mp4"}`,r=new URLSearchParams({filename:o,bookId:t,kind:n}),i=await fetch(`/api/search-references?${r}`,{method:"POST",headers:e.type?{"Content-Type":e.type}:{},body:e}),s=await i.json();if(!i.ok)throw new Error(rt(s,"error")??"Could not prepare search reference");const a=as(s);return a.previewUrl?a:{...a,previewUrl:URL.createObjectURL(e),localPreview:!0}}async function cf(e){e&&(e.localPreview&&e.previewUrl&&URL.revokeObjectURL(e.previewUrl),await fetch(`/api/search-references/${encodeURIComponent(e.referenceId)}`,{method:"DELETE"}).catch(()=>{}))}function as(e,t){const n=rt(e,"reference_id"),o=rt(e,"kind"),r=rt(e,"name"),i=dr(e,"expires_at");if(!n||o!=="image"&&o!=="video"||!r||i===null)throw new Error("The server returned an invalid search reference");const s=dr(e,"duration_ms"),a=rt(e,"preview_url")??t;return{referenceId:n,kind:o,name:r,expiresAt:i,...s===null?{}:{durationMs:s},...a?{previewUrl:a}:{}}}function rt(e,t){if(typeof e!="object"||e===null)return null;const n=e[t];return typeof n=="string"?n:null}function dr(e,t){if(typeof e!="object"||e===null)return null;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null}const cs=.25,fr=.01;function Un(e){return Math.min(1,Math.max(0,e))}function $t(e){return Math.round(Un(e)*1e6)/1e6}function lf(e,t){const n=Math.max(e.x,t.x),o=Math.max(e.y,t.y),r=Math.min(e.x+e.width,t.x+t.width),i=Math.min(e.y+e.height,t.y+t.height),s=Math.max(0,r-n)*Math.max(0,i-o),a=e.width*e.height+t.width*t.height-s;return a>0?s/a:0}function yw(e,t){const n=$t(Math.min(e.x,t.x)),o=$t(Math.min(e.y,t.y)),r=$t(Math.min(1-n,Math.abs(t.x-e.x))),i=$t(Math.min(1-o,Math.abs(t.y-e.y)));return r<fr||i<fr?null:{x:n,y:o,width:r,height:i}}function _w(e,t,n){return n.width<=0||n.height<=0?{x:0,y:0}:{x:Un((e-n.left)/n.width),y:Un((t-n.top)/n.height)}}function uf(e,t,n=cs){return t.flatMap(r=>{if(!r.box)return[];const i=lf(e,r.box);return i>=n?[{subjectId:r.id,iou:i,box:r.box}]:[]}).sort((r,i)=>i.iou-r.iou)[0]??null}function vw(e,t,n=cs){const o=uf(e.box,t,n);return o?{...e,box:o.box,matchedSubjectId:o.subjectId}:e}function kw(e,t,n={}){return{subjectIds:[...e],regions:t.map(o=>({id:o.id,box:o.box,...o.matchedSubjectId?{matchedSubjectId:o.matchedSubjectId}:{}})),replacements:{...n}}}const df="Mention a replacement image (for example @g7) or assign one in the panel.",ff="Mention one image for every region, or one image to use for all of them.",mf="Draw a region or select a person or object to replace.";function ls(e){const t=new Set,n=[];for(const o of e){const r=o.trim();if(!r)continue;const i=r.toLowerCase();t.has(i)||(t.add(i),n.push(r))}return n}function ww(e,t,n=e){const o=new Set(e.flatMap(s=>s.matchedSubjectId?[s.matchedSubjectId]:[])),r=e.map(s=>({key:s.id,box:s.box,...s.matchedSubjectId?{subjectId:s.matchedSubjectId}:{},label:s.matchedSubjectId?t.find(a=>a.id===s.matchedSubjectId)?.label??`Region ${n.findIndex(a=>a.id===s.id)+1}`:`Region ${n.findIndex(a=>a.id===s.id)+1}`})),i=t.flatMap(s=>o.has(s.id)?[]:[{key:s.id,...s.box?{box:s.box}:{},subjectId:s.id,label:s.label}]);return[...r,...i]}function Sw(e,t){return e.length>0&&e.every(n=>!!t[n.key]?.trim())}function Iw(e,t){return e.flatMap(n=>{const o=t[n.key]?.trim();return o?[{replacementArtifactId:o,...n.box?{box:n.box}:{},...n.subjectId?{subjectId:n.subjectId}:{}}]:[]})}function xw(e,t,n){if(e.length===0)return{ok:!1,error:mf};const o={};for(const s of e){const a=t[s.key]?.trim();a&&(o[s.key]=a)}const r=ls(n),i=e.filter(s=>!o[s.key]);if(r.length===1){const s=r[0];for(const a of i)o[a.key]=s}else if(r.length>1){if(r.length!==i.length)return{ok:!1,error:ff};i.forEach((s,a)=>{o[s.key]=r[a]})}return e.every(s=>!!o[s.key])?{ok:!0,replacements:o}:{ok:!1,error:df}}function Aw(e,t){const n=new Map(t.map(i=>[i.cellAddress.toLowerCase(),i])),o=[],r=new Set;for(const i of ls(e)){const s=n.get(i.toLowerCase());if(!s)return{ok:!1,error:`@${i.toLowerCase()} is not an image on this notebook.`};if(s.type.toLowerCase()!=="image")return{ok:!1,error:`@${s.cellAddress} is a ${s.type}, not an image.`};r.has(s.artifactId)||(r.add(s.artifactId),o.push(s.artifactId))}return{ok:!0,artifactIds:o}}function Ew(e){return`region-${e.length+1}-${Math.random().toString(36).slice(2,8)}`}function Cw(e,t,n=!1){if(t.length>0)return`${t.map(r=>r.label).join(", ")}${n?" · replaced with another image":""}`;if(e.length===0)return null;const o=e.slice(0,3).map(r=>r.label).join(", ");return e.length>3?`${o} +${e.length-3}`:o}function Mw(e,t,n=!1){return n?"Optional notes for the replacement. Pick an image below, or mention one like @g7.":t.length>0?`Describe how to change ${t.map(o=>o.label).join(" and ")}, e.g. "remove the glass door". To replace with an image, pick one below or mention @g7.`:e.length===0?'Describe a whole-image edit, e.g. "make it look like a snowy night", or select a subject to scope the change.':`Describe how to change ${e.slice(0,2).map(o=>o.label).join(" and ")}, e.g. "make it smooth porcelain".`}function pf(e){if(e<60)return`${e.toFixed(1)}s`;const t=Math.floor(e/60),n=Math.round(e%60);return`${t}:${String(n).padStart(2,"0")}`}function Tw(e){const t=[];return e.width&&e.height&&t.push(`${e.width} × ${e.height}`),e.duration&&e.type!=="image"&&t.push(pf(e.duration)),t.push(e.type==="final"?"VIDEO":e.type.toUpperCase()),t}const gf=["button","input","select","textarea","[href]",'[contenteditable="true"]',"[tabindex]"].join(", ");function hf(e){const t=e.getAttribute("tabindex");return!e.hidden&&!e.matches(':disabled, [type="hidden"]')&&(t===null||!Number.isFinite(Number(t))||Number(t)>=0)&&e.closest('[hidden], [aria-hidden="true"], [inert]')===null}function bf(e){return[...e.querySelectorAll(gf)].filter(hf)}function yf(e,t,n){const o=e[0],r=e.at(-1);return!o||!r?null:e.includes(t)?n&&t===o?r:!n&&t===r?o:null:n?r:o}function Rw(e,t){if(e.key==="Escape"){t.busy||(e.preventDefault(),t.onClose());return}if(e.key!=="Tab"||!t.container)return;const n=bf(t.container),o=t.activeElement===void 0?document.activeElement:t.activeElement,r=yf(n,o,e.shiftKey);r&&(e.preventDefault(),r.focus())}async function mr(e,t,n,o){await e("delete_notebook_cell",{book_id:t,notebook_id:n,cell_id:o}).catch(()=>{})}function _f(e){const t=h(e);return x(t?.id)}async function vf(e,t,n,o){const r=h(await e("get_notebook",{book_id:t,notebook_id:n}).catch(()=>null));if(!r)return null;const i=Array.isArray(r.cells)?r.cells:[],s=Array.isArray(r.edges)?r.edges:[];for(const a of s){const c=h(a),l=x(c?.source),u=x(c?.target),m=x(c?.targetInput??c?.target_input);if(l===o&&m==="media"&&u)return u}for(const a of i){const c=h(a);if(x(c?.type)!=="audio")continue;const l=h(c?.inputs);if(x(l?.producerCellId)===o)return _f(c)}return null}async function $w(e){const t=e.text.trim(),n=e.voiceId.trim();if(!t)throw new Error("Speak text is required");if(!n)throw new Error("Speak voice is required");const o=an(e.document.cells,[],e.lastWorkSlot??null);let r=null,i=null;try{const s=h(await e.callTool("create_notebook_cell",{book_id:e.bookId,notebook_id:e.document.id,...e.expectedRevision?{expected_revision:e.expectedRevision}:{},cell:{type:"generate_audio",label:"Speak",slot:o,prompt:t,inputs:{generationSettings:{voice_id:n}}}}));r=x(s?.id),i=x(h(s?.output_cell)?.id);const a=x(s?.address)??ue(o);if(!r)throw new Error("The server did not return the Speak cell");if(!i)throw new Error("The server did not return the Speak output cell");return{cellId:r,cellAddress:a,outputCellId:i}}catch(s){let a=i;throw r&&!a&&(a=await vf(e.callTool,e.bookId,e.document.id,r)),a&&await mr(e.callTool,e.bookId,e.document.id,a),r&&await mr(e.callTool,e.bookId,e.document.id,r),s}}function kf(e){const t=h(e);return{voices:Array.isArray(t?.voices)?t.voices.flatMap(o=>{const r=h(o),i=x(r?.voice_id)??x(r?.voiceId),s=x(r?.name),a=x(r?.source);if(!i||!s||a!=="custom"&&a!=="generic")return[];const c=x(r?.category),l=x(r?.preview_url)??x(r?.previewUrl);return[{voiceId:i,name:s,source:a,...c?{category:c}:{},...l?{previewUrl:l}:{}}]}):[],status:t?.status==="live"?"live":"fallback",warning:W(t?.warning)}}async function wf(e){return kf(await e("list_elevenlabs_voices",{},{background:!0}))}function pr(){return{voices:[],status:"fallback",warning:null,loading:!1,error:null}}function Sf(e){let t=e.ready,n=e.load,o=0,r=!1,i=pr(),s=null;const a=new Set,c=m=>{i=m;for(const d of a)d()},l=()=>{o+=1,r=!1,s=null,c(pr())},u=()=>{if(!t)return Promise.resolve(null);if(s)return s;const m=o,d=Promise.resolve().then(()=>n()).then(f=>o!==m||s!==d?null:(r=!0,s=null,c({...f,loading:!1,error:null}),f),f=>(o!==m||s!==d||(r=!1,s=null,c({...i,loading:!1,error:f instanceof Error?f.message:String(f)})),null));return s=d,c({...i,loading:!0,error:null}),d};return{configure(m){t===m.ready&&n===m.load||(t=m.ready,n=m.load,l())},ensureLoaded(){return t?s||(r?Promise.resolve({voices:i.voices,status:i.status,warning:i.warning}):u()):Promise.resolve(null)},getSnapshot(){return i},refresh:u,reset:l,subscribe(m){return a.add(m),()=>a.delete(m)}}}function Nw(e){const t=ne.c(25),{callTool:n,ready:o}=e;let r;t[0]!==n?(r=()=>wf(n),t[0]=n,t[1]=r):r=t[1];const i=r;let s;t[2]!==i||t[3]!==o?(s=()=>Sf({ready:o,load:i}),t[2]=i,t[3]=o,t[4]=s):s=t[4];const[a]=_.useState(s);let c,l;t[5]!==a||t[6]!==i||t[7]!==o?(c=()=>{a.configure({ready:o,load:i})},l=[a,i,o],t[5]=a,t[6]=i,t[7]=o,t[8]=c,t[9]=l):(c=t[8],l=t[9]),_.useEffect(c,l);let u,m;t[10]!==a?(u=()=>()=>a.reset(),m=[a],t[10]=a,t[11]=u,t[12]=m):(u=t[11],m=t[12]),_.useEffect(u,m);const d=_.useSyncExternalStore(a.subscribe,a.getSnapshot,a.getSnapshot);let f;t[13]!==a?(f=()=>a.ensureLoaded(),t[13]=a,t[14]=f):f=t[14];const g=f;let p;t[15]!==a?(p=()=>a.refresh(),t[15]=a,t[16]=p):p=t[16];const y=p;let v;return t[17]!==g||t[18]!==y||t[19]!==d.error||t[20]!==d.loading||t[21]!==d.status||t[22]!==d.voices||t[23]!==d.warning?(v={voices:d.voices,status:d.status,warning:d.warning,loading:d.loading,error:d.error,ensureLoaded:g,refresh:y},t[17]=g,t[18]=y,t[19]=d.error,t[20]=d.loading,t[21]=d.status,t[22]=d.voices,t[23]=d.warning,t[24]=v):v=t[24],v}function If(e){const t=h(e);if(!t)return null;const n=o=>t[o]===!0;return{semantic:n("semantic"),regionReplace:n("regionReplace"),wholeImage:n("wholeImage"),exactMask:n("exactMask")}}function xf(e){const t=h(e),n=Array.isArray(t?.models)?t.models:[],o=[];for(const r of n){const i=h(r),s=x(i?.id),a=x(i?.label),c=x(i?.provider),l=If(i?.capabilities);if(!s||!a||c!=="kie"&&c!=="fal"||!l)continue;const u=typeof i?.max_input_images=="number"&&Number.isFinite(i.max_input_images)?i.max_input_images:null;o.push({id:s,label:a,provider:c,capabilities:l,maxInputImages:u,available:i?.available===!0})}return{models:o,defaultModelId:x(t?.default_model)??o[0]?.id??ci,lastUsedModelId:x(t?.last_used_model)}}function Pw(e){const t=ne.c(13),{callTool:n,ready:o}=e,[r,i]=_.useState(null),[s,a]=_.useState(!1),[c,l]=_.useState(null),u=_.useRef(null),m=_.useRef(null);let d;t[0]!==n||t[1]!==r||t[2]!==o?(d=S=>{if(!o||u.current||m.current===S&&r)return;a(!0),l(null);const w=n("list_image_edit_models",{book_id:S},{background:!0}).then(k=>{u.current===w&&(u.current=null,m.current=S,i(xf(k)),a(!1))}).catch(k=>{u.current===w&&(u.current=null,l(k instanceof Error?k.message:String(k)),a(!1))});u.current=w},t[0]=n,t[1]=r,t[2]=o,t[3]=d):d=t[3];const f=d;let g;t[4]!==r?.models?(g=r?.models??[],t[4]=r?.models,t[5]=g):g=t[5];const p=r?.defaultModelId??ci,y=r?.lastUsedModelId??null;let v;return t[6]!==f||t[7]!==c||t[8]!==s||t[9]!==g||t[10]!==p||t[11]!==y?(v={models:g,defaultModelId:p,lastUsedModelId:y,loading:s,error:c,ensureLoaded:f},t[6]=f,t[7]=c,t[8]=s,t[9]=g,t[10]=p,t[11]=y,t[12]=v):v=t[12],v}function Ow(e,t,n){const o=t.find(s=>s.id===e.cell_id)??t.find(s=>s.outputArtifactId!==void 0&&s.outputArtifactId===e.asset_id);if(!o)return{ok:!1,message:"That cell is no longer in this notebook."};const r=ue(o.slot),i=n.find(s=>s.artifactId===o.outputArtifactId);return i?i.type==="audio"?{ok:!1,message:`${r} holds audio; fullscreen shows images and video.`}:!i.mediaUrl&&!i.thumbnailUrl?{ok:!1,message:`${r} is still processing. Try again when it is ready.`}:{ok:!0,cell:o,asset:i,address:r}:{ok:!1,message:`${r} has no media yet.`}}function Lw(e,t,n,o){const r=e?.trim()||t?.outputArtifactId;if(!r)return{ok:!1,message:"Select a video cell or pass a target: /watermark @a1"};const i=n.find(a=>a.artifactId===r);if(!i)return{ok:!1,message:`No asset found for ${r}`};if(i.type!=="video")return{ok:!1,message:`Watermark applies to video assets; ${o.get(r)??r} is ${i.type}`};const s=o.get(r);return{ok:!0,artifactId:r,label:s?`@${s}`:r}}const Af=["top-left","top-center","top-right","middle-left","middle-center","middle-right","bottom-left","bottom-center","bottom-right"],Ef=33,Cf=10,Mf=90,Tf=.5,Rf=.05,$f=1,us=32,Nf=0,Pf=96,Of=88,Lf=26,Fw=480,Ff=100,Df=0,Vf=100,jf=["center","above-qr","on-qr","below-qr"];function Dw(e){return Number.isFinite(e)?Math.min(Mf,Math.max(Cf,e)):Ef}function Vw(e){return Number.isFinite(e)?Math.min($f,Math.max(Rf,e)):Tf}function Gf(e){return Number.isFinite(e)?Math.round(Math.min(Pf,Math.max(Nf,e))):us}function jw(e){const t=Gf(e);return Math.max(Lf+4,Of+2*(t-us))}function qf(e){return typeof e=="string"&&jf.includes(e)}function Gw(e){return Number.isFinite(e)?Math.round(Math.min(Vf,Math.max(Df,e))):Ff}function Uf(e){return e==="auto"||Af.includes(e)}const Bf=.5,Hf=0,Wf=2,Kf=.001;function qw(e){if(!Number.isFinite(e))return Bf;const t=Math.min(Wf,Math.max(Hf,e));return Math.round(t*10)/10}function zf(e,t,n,o){const r=Math.max(0,e),s=(t===null?n:Math.min(t,n))-r;if(!(o>0)||!(s>0))return{fadeIn:0,fadeOut:0};const a=Math.min(o,s/2),c=t!==null&&t<n-Kf;return{fadeIn:r>0?a:0,fadeOut:c?a:0}}function Uw(e,t,n,o,r,i){if(e<t||n!==null&&e>n)return 0;const s=zf(t,n,o,i);let a=1;return s.fadeIn>0&&(a=Math.min(a,(e-t)/s.fadeIn)),s.fadeOut>0&&n!==null&&(a=Math.min(a,(n-e)/s.fadeOut)),r*Math.min(1,Math.max(0,a))}const ds="videobook.watermark-review.v1:",ct=new Map;function gr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function ko(e){const t=gr(e);if(!t)return{};const n={};tc(t.platform)&&(n.platform=t.platform),Uf(t.position)&&(n.position=t.position),qf(t.handlePlacement)&&(n.handlePlacement=t.handlePlacement),typeof t.url=="string"&&(n.url=t.url);for(const r of["includeQr","includeHandle","includePlatformIcon","includeHandleBorder","saveDefault"])typeof t[r]=="boolean"&&(n[r]=t[r]);for(const r of["handleVerticalPercent","handlePadding","handlePaddingY","handleRounding","qrOpacity","handleOpacity","fadeSeconds","qrStartSeconds","handleStartSeconds"]){const i=t[r];typeof i=="number"&&Number.isFinite(i)&&(n[r]=i)}for(const r of["qrEndSeconds","handleEndSeconds"]){const i=t[r];(i===null||typeof i=="number"&&Number.isFinite(i))&&(n[r]=i)}const o=gr(t.handles);if(o){n.handles={};for(const r of ec)typeof o[r]=="string"&&(n.handles[r]=o[r])}return n}function Xf(e){if(!e)return{};const t=ct.get(e);if(t)return t;try{const n=window.localStorage.getItem(`${ds}${e}`);if(n!==null)return ko(JSON.parse(n))}catch{return ct.get(e)??{}}return ct.get(e)??{}}function Bw(e,t,{handle:n,...o}){if(!e)return;const r=Xf(e),i={...r,...ko(o),platform:o.platform??t,handles:n===void 0?r.handles:{...r.handles,[t]:n}};try{window.localStorage.setItem(`${ds}${e}`,JSON.stringify(i)),ct.delete(e)}catch{ct.set(e,i)}}function Yf(e,t){if(!t||!Number.isFinite(t)||t<=0)return e;const n={...e};for(const[o,r]of[["qrStartSeconds","qrEndSeconds"],["handleStartSeconds","handleEndSeconds"]]){const i=Math.max(0,e[o]??0),s=Math.min(t,e[r]??t);n[o]=i<s?i:0,n[r]=i<s&&e[r]!=null?s:null}return n}function Jf(e,t,n){const o=ha,r=n&&n>0?ba(o,n):null,i={...e},s=a=>e[a]===void 0&&t[a]===void 0;return s("position")&&(i.position="bottom-right"),s("handleVerticalPercent")&&(i.handleVerticalPercent=o.handleVerticalPercent),s("handlePadding")&&(i.handlePadding=o.handlePaddingX),s("handlePaddingY")&&(i.handlePaddingY=o.handlePaddingY),s("handleRounding")&&(i.handleRounding=o.handleRounding),s("qrOpacity")&&(i.qrOpacity=o.qrOpacity),s("handleOpacity")&&(i.handleOpacity=o.handleOpacity),s("fadeSeconds")&&(i.fadeSeconds=o.fadeSeconds),s("includePlatformIcon")&&(i.includePlatformIcon=o.includePlatformIcon),s("includeHandleBorder")&&(i.includeHandleBorder=o.includeHandleBorder),s("handlePlacement")&&(i.handlePlacement=o.handlePlacement),s("url")&&(i.url=o.profileUrl),r&&s("qrStartSeconds")&&s("qrEndSeconds")&&(i.qrStartSeconds=r.qrStartSeconds,i.qrEndSeconds=r.qrEndSeconds),r&&s("handleStartSeconds")&&s("handleEndSeconds")&&(i.handleStartSeconds=r.handleStartSeconds,i.handleEndSeconds=r.handleEndSeconds),i}function Hw(e,t,n){const o=t.platform??e.platform??"tiktok",r=o==="tiktok"?Jf(e,t,n):e;return{...Yf(r,n),...ko(t),platform:o,handles:t.handle===void 0?e.handles:{...e.handles,[o]:t.handle}}}const Zf=new Set(["queued","running","completing"]);function hr(e){return e.state==="failed"||e.state==="aborted"}function Ww(e,t,n,o){const r=o.find(a=>a.id===t);if(!r)return{kind:"missing"};if(hr(r))return{kind:"failed",message:r.error?.message??"Watermark burn failed"};if(r.state!=="done")return{kind:"continue"};const i=o.filter(a=>a.artifactId===e&&a.id>t),s=i.find(hr);return s||n?.status==="error"?{kind:"failed",message:s?.error?.message??"Post-watermark processing failed"}:i.some(a=>Zf.has(a.state))?{kind:"continue"}:n&&n.status!=="ready"?{kind:"continue"}:{kind:"completed",result:r.result}}function Kw(e){const t=e.placementSource==="vision"||e.placementSource==="cached"?" (frame-aware)":"",n=Math.round(e.handleOpacity*100),o=e.includeHandle?e.handlePlacement==="center"?` · handle ${e.handleVerticalPercent}% from top at ${n}%`:` · handle ${e.handlePlacement.replace("-"," ")} at ${n}%`:"",r=e.includeQr?` · QR ${Math.round(e.qrOpacity*100)}%`:"",i=e.corner??e.requestedPosition;return e.includeQr?e.includeHandle?`QR + @${e.handle} watermarks burned in — QR ${i}${t}${r}${o}.`:`QR watermark burned in — ${i}${t}${r}.`:`@${e.handle} watermark burned in${o}.`}function zw(e,t,n,o){return`Burning ${e?t?`QR + @${n} watermarks`:"QR watermark":`@${n} watermark`} into ${o}…`}function Xw(e){return e===1?"1 artifact":`${e} artifacts`}function Yw(e){return e===1?"1 notebook":`${e} notebooks`}function Jw(e,t,n){return n?{mode:e,closeMenu:!1}:t.kind==="close"?{mode:{kind:"idle"},closeMenu:!0}:t.kind==="escape"?e.kind==="idle"?{mode:e,closeMenu:!0}:{mode:{kind:"idle"},closeMenu:!1}:t.kind==="cancel"?e.kind==="idle"?{mode:e,closeMenu:!1}:{mode:{kind:"idle"},closeMenu:!1}:t.kind==="begin-create"?{mode:{kind:"create"},closeMenu:!1}:t.kind==="begin-rename"?{mode:{kind:"rename",bookId:t.bookId},closeMenu:!1}:{mode:{kind:"delete",bookId:t.bookId},closeMenu:!1}}function Xt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function fe(e,t){const n=Array.isArray(e)?e:Xt(e)?.[t];return Array.isArray(n)?n.flatMap(o=>{const r=Xt(o);return r?[r]:[]}):[]}function ie(e,t,n){return e.flatMap(o=>{const r=t.map(a=>o[a]).find(a=>typeof a=="string"&&!!a);if(!r)return[];const i=n.map(a=>o[a]).find(a=>typeof a=="string"&&!!a)??r,s=[o.type,o.status,o.createdAt??o.date].filter(a=>typeof a=="string").join(" · ");return[{value:r,label:i,...s?{detail:s}:{}}]})}async function Zw(e,t,n){const o=e.inputSchema.properties??{},r=e.handler.kind==="tool"?e.handler.tool:"",i={choices:{},entities:{},values:{}};let s=[];const a=[];o.notebook_id&&a.push((async()=>{i.choices.notebook_id=ie(fe(await n("list_notebooks",{}),"notebooks"),["id"],["name"])})()),/^(?:get|update|delete)_entity$/u.test(r)&&a.push((async()=>{const d=fe(await n("list_entities",{}),"entities");i.choices.entity_id=ie(d,["id"],["name"]),i.entities=Object.fromEntries(d.filter(f=>typeof f.id=="string").map(f=>[String(f.id),f])),r.startsWith("update_")&&typeof t.entity_id=="string"&&i.entities[t.entity_id]&&(i.values.entity=i.entities[t.entity_id])})()),o.job_id&&a.push((async()=>{i.choices.job_id=ie(fe(await n("list_jobs",{limit:200}),"jobs"),["id","jobId"],["name","type","tool"])})()),o.archive_ids&&a.push((async()=>{i.choices.archive_ids=ie(fe(await n("search_archive",{limit:100,presign_media:!1}),"results"),["archive_id"],["title","filename"])})());const c=t.asset_id??t.artifact_id,l=typeof c=="string"?c:void 0;(o.commit_hash||o.target_revision||o.action_id||o.target_action_id)&&a.push((async()=>{const d=l&&o.commit_hash?fe(await n("asset_history",{asset_id:l,limit:200}),"commits"):fe(await n("list_book_actions",{limit:200}),"actions"),f=ie(d,["hash","revision"],["message","operation"]);i.choices.commit_hash=f,i.choices.target_revision=f;const g=d.flatMap(y=>{const v=Xt(y.details)?.actionId;return typeof v=="string"?[{...y,actionId:v}]:[]}),p=ie(g,["actionId"],["operation","message"]);i.choices.action_id=r==="get_history_action"?ie(d,["hash","revision"],["operation","message"]):p,i.choices.target_action_id=p,r==="read_file_at_commit"&&(s=ie(d.flatMap(y=>{const v=Xt(y.details)?.path;return typeof v=="string"?[{name:v}]:[]}),["name"],["name"]))})()),o.filename&&l&&["read_file_at_commit","export_asset_file"].includes(r)&&a.push((async()=>{i.choices.filename=ie(fe(await n("asset_manifest",{asset_id:l}),"files"),["name"],["name"])})()),o.plan_id&&typeof t.notebook_id=="string"&&a.push((async()=>{const d=fe(await n(r.includes("generation")||r==="continue_notebook_generation"?"list_notebook_generation_plans":"list_notebook_run_plans",{notebook_id:t.notebook_id}),"plans");i.choices.plan_id=ie(d,["planId","plan_id"],["prompt","status"])})()),o.model&&e.generation&&a.push((async()=>{const d=fe(await n("list_generation_models",{media:e.generation?.mediaType}),"models");i.choices.model=ie(d,["id"],["title"])})()),o.voice_id&&a.push((async()=>{i.choices.voice_id=ie(fe(await n("list_elevenlabs_voices",{}),"voices"),["voice_id","id"],["name"])})()),(o.subject_ids||o.subject_id)&&l&&typeof t.object_hash=="string"&&a.push((async()=>{const d=fe(await n("get_image_subject_map",{artifact_id:l,object_hash:t.object_hash}),"subjects");i.choices.subject_id=ie(d,["id","subjectId"],["label","name"]),i.choices.subject_ids=i.choices.subject_id})());const m=(await Promise.allSettled(a)).flatMap(d=>d.status==="rejected"?[d.reason instanceof Error?d.reason.message:String(d.reason)]:[]);if(m.length)throw new Error(`Could not load action choices: ${m.join(" · ")}`);if(s.length){const d=new Map((i.choices.filename??[]).map(f=>[f.value,f]));for(const f of s)d.has(f.value)||d.set(f.value,{...f,detail:"Historical file"});i.choices.filename=[...d.values()]}return i}const Qw={open_actions:{kind:"existing"},switch_book:{kind:"existing"},open_projects:{kind:"existing"},open_music_video:{kind:"existing"},start_goal:{kind:"existing"},open_alive_captions:{kind:"existing"},open_cold_open:{kind:"existing"},open_post_dropbox:{kind:"existing"},open_post_icloud:{kind:"existing"},open_watermark:{kind:"existing"},speak_preview:{kind:"existing"},x_connect:{kind:"existing"},open_provider_keys:{kind:"screen",screen:"settings"},open_inbox:{kind:"library"},open_jobs:{kind:"screen",screen:"jobs"},open_status:{kind:"form",tool:"list_book_actions"},open_revisions:{kind:"form",tool:"list_book_actions"},open_diagnostics:{kind:"form",tool:"doctor"},open_entities:{kind:"search",query:"Entities"},open_archive:{kind:"form",tool:"search_archive"},open_rename_all:{kind:"form",tool:"rename_all"},open_crop:{kind:"form",tool:"crop_asset"},open_osg:{kind:"form",tool:"set_video_overlay"},settings_osg:{kind:"form",tool:"set_video_overlay"},settings_audio:{kind:"form",tool:"render_video"},settings_subs:{kind:"form",tool:"render_video"},settings_bg:{kind:"form",tool:"render_video"},viewer_show_settings:{kind:"form",tool:"render_video"},settings_landscape:{kind:"form",tool:"render_video"},settings_portrait:{kind:"form",tool:"render_video"},settings_square:{kind:"form",tool:"render_video"},viewer_focus_file:{kind:"form",tool:"asset_manifest"},open_post_composer:{kind:"form",tool:"post"},timeline_audio_add:{kind:"form",tool:"add_timeline_audio"},timeline_audio_move:{kind:"form",tool:"move_timeline_audio"},timeline_audio_remove:{kind:"form",tool:"remove_timeline_audio"},timeline_audio_update:{kind:"form",tool:"update_timeline_audio"},rewind_activity:{kind:"form",tool:"restore_edit_action"},sidebar_sort:{kind:"form",tool:"list_assets"},run_notebook:{kind:"form",tool:"plan_notebook_run"},open_upload:{kind:"special",action:"upload"},copy_clipboard:{kind:"special",action:"copy"},show_history:{kind:"special",action:"history"},open_asset:{kind:"special",action:"open"},viewer_set_original:{kind:"special",action:"original"},viewer_set_landscape:{kind:"special",action:"landscape"},viewer_set_portrait:{kind:"special",action:"portrait"},viewer_toggle_info:{kind:"form",tool:"read_asset_metadata"},close_viewer:{kind:"special",action:"close"},sidebar_collapse:{kind:"special",action:"collapse"},sidebar_expand:{kind:"special",action:"expand"},save_notebook:{kind:"special",action:"save"},open_notebook:{kind:"special",action:"notebook"},open_slot_player:{kind:"special",action:"play"},extract_skeleton:{kind:"special",action:"skeleton"}};function eS(e,t,n){const o={...t};if(e==="open_osg"&&t.image&&(o.osg_asset_id=t.image),e==="open_post_composer"&&t.asset_ref&&(o.asset_id=t.asset_ref),e==="open_crop"&&t.ratio!==void 0&&t.ratio!==null&&String(t.ratio).trim()!==""&&(o.ratio=im(t.ratio)),e==="sidebar_sort"&&(o.sort=om(t.order)),e==="viewer_toggle_info"&&(o.name="original"),e==="settings_bg"){const i=rm(t.mode);i&&(o.background_mode=i)}["settings_landscape","settings_portrait","settings_square"].includes(e)&&(o.orientation=e.slice(9)),e.startsWith("timeline_audio_")&&((e==="timeline_audio_add"||t.start!==void 0)&&(o.start_frame=Math.round(Number(t.start??0)*n)),t.duration!==void 0&&(o.duration_frames=Math.round(Number(t.duration)*n))),e==="rewind_activity"&&t.commit_hash&&(o.target_revision=t.commit_hash);const r=String(t.field??"").trim().toLowerCase();if(e==="settings_subs"&&["on","off"].includes(r)&&(o.subtitles_enabled=r==="on"),["settings_audio","settings_subs","timeline_audio_update"].includes(e)&&r&&t.value!==void 0){const i=e==="timeline_audio_update"?sm(r):e==="settings_audio"?am(r):fs[r]??r,s=String(t.value),a=Number(s);if(e==="timeline_audio_update"&&!Number.isFinite(a))throw new Error("Usage: /audio-set @clip volume|fade-in|fade-out <value>");o[i]=["on","off","true","false"].includes(s.toLowerCase())?["on","true"].includes(s.toLowerCase()):s.trim()&&Number.isFinite(a)?a:cm(r,i,s)}return o}const Qf=["newest","oldest"],em=["blur","black"],fs={"fade-in":"audio_fade_in","fade-out":"audio_fade_out",volume:"audio_volume",enabled:"subtitles_enabled",style:"highlight_style",size:"font_size",fontsize:"font_size",color:"text_color",textcolor:"text_color",highlight:"highlight_color",highlightcolor:"highlight_color",stroke:"stroke_width",strokewidth:"stroke_width",strokecolor:"stroke_color",shadow:"shadow_blur",shadowblur:"shadow_blur",shadowopacity:"shadow_opacity",language:"subtitle_language"},tm={position:["top","middle","bottom"],highlight_style:["impact","highlight","alive"],font_size:["small","medium","large"]},nm={position:{mid:"middle"},font_size:{s:"small",m:"medium",l:"large"}};function tS(e){if(e==null||e==="")return 1;const t=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(t)||t<1)throw new Error("Usage: /files <position>");return t}function nS(e){const t=(e??"both").trim().toLowerCase();if(t==="left"||t==="right"||t==="both")return t;throw new Error("Choose left, right or both.")}function om(e){const t=String(e??"newest").trim().toLowerCase();if(t==="newest"||t==="oldest")return t;throw new Error(`Usage: /sort ${Qf.join("|")}`)}function rm(e){if(e==null||String(e).trim()==="")return null;const t=String(e).trim().toLowerCase();if(t==="blur"||t==="black")return t;throw new Error(`Usage: /bg ${em.join("|")}`)}function im(e){const t=String(e).trim().toLowerCase();if(t==="16:9"||t==="landscape")return"16:9";if(t==="9:16"||t==="portrait")return"9:16";if(t==="1:1"||t==="square")return"1:1";throw new Error("Usage: /crop @asset [16:9|9:16|1:1]")}function sm(e){const t=e.replaceAll("-","_");if(t==="volume"||t==="fade_in"||t==="fade_out")return t;throw new Error("Usage: /audio-set @clip volume|fade-in|fade-out <value>")}function am(e){const t=fs[e];if(t==="audio_volume"||t==="audio_fade_in"||t==="audio_fade_out")return t;throw new Error("Usage: /audio volume|fade-in|fade-out <value>")}function cm(e,t,n){if(t==="subtitle_language"){const s=n.trim().toLowerCase();if(/^(original|[a-z]{2})$/u.test(s))return s;throw new Error("Usage: /subs language original|en")}const o=tm[t];if(!o)return n;const r=n.trim().toLowerCase(),i=nm[t]?.[r]??r;if(o.includes(i))return i;throw new Error(`Usage: /subs ${e} ${o.join("|")}`)}const lm={audio:new Set(["aac","flac","m4a","mp3","ogg","wav","weba"]),image:new Set(["gif","heic","heif","jpeg","jpg","png","svg","webp"]),video:new Set(["avi","mkv","mov","mp4","webm"])},oS={audio:"audio/*,.aac,.flac,.m4a,.mp3,.ogg,.wav,.weba",image:"image/*,.gif,.heic,.heif,.jpeg,.jpg,.png,.svg,.webp",video:"video/*,.avi,.mkv,.mov,.mp4,.webm"};function rS(e){const t=e.type.split("/",1)[0];if(t==="audio"||t==="image"||t==="video")return t;const n=e.name.toLowerCase().split(".").pop()??"";for(const o of["audio","image","video"])if(lm[o].has(n))return o;return null}function um(e){return e==="audio"||e==="image"||e==="video"?e:null}function iS(e,t,n){return um(e)!==null&&t===void 0&&n===0}function sS(e){return e.types.includes("Files")}const aS=["Media","Text & analysis","Generation","Edit"],Bn=[{type:"audio",label:"Audio",group:"Media"},{type:"image",label:"Image",group:"Media"},{type:"video",label:"Video",group:"Media"},{type:"post",label:"Post",group:"Media"},{type:"character",label:"Character",group:"Media"},{type:"prompt",label:"Prompt",group:"Text & analysis"},{type:"analyze",label:"Analyze",group:"Text & analysis"},{type:"generate_video",label:"Generate video",group:"Generation"},{type:"generate_image",label:"Generate image",group:"Generation"},{type:"generate_audio",label:"Generate audio",group:"Generation"},{type:"extract_audio",label:"Extract audio",group:"Edit"},{type:"split_video",label:"Split video",group:"Edit"},{type:"concat",label:"Concat",group:"Edit"},{type:"splice",label:"Splice",group:"Edit"},{type:"timeline",label:"Timeline",group:"Edit"}],dm=new Set(Bn.map(e=>e.type));function br(e){return e.trim().toLocaleLowerCase().replaceAll("_"," ")}function cS(e){const t=br(e);return t?Bn.filter(n=>br(`${n.label} ${n.type} ${n.group}`).includes(t)):Bn}function lS(e){return dm.has(e)}const fm=new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}),mm=new Intl.NumberFormat("en-US"),uS={images:"Images",video:"Video",audio:"Audio",chat:"Chat",voice:"Voice",analysis:"Analysis & transcription"};function dS(e,t=!1){return(t?mm:fm).format(e)}function pm(e){return e>0&&e<.01?"<$0.01":`$${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function fS(e){const t=e.reportedUsd+e.estimatedUsd;return t===0&&e.unpriced>0?"— cost":`${e.estimatedUsd>0?"~":""}${pm(t)}`}function gm(e){if(!e||typeof e!="object")throw new Error("Usage is unavailable");const t=e;if(typeof t.trackedSince!="number"||!t.totals||!Array.isArray(t.groups)||!Array.isArray(t.recent))throw new Error("Usage is unavailable");return t}function mS({bookId:e,ready:t,call:n}){const[o,r]=_.useState(null),[i,s]=_.useState(null),[a,c]=_.useState(0),l=_.useEffectEvent(async u=>{try{const m=gm(await n("get_book_usage",{book_id:e},{background:!0}));if(!u())return;r(d=>d?.bookId===e&&JSON.stringify(d.data)===JSON.stringify(m)?d:{bookId:e,data:m}),s(null)}catch{u()&&s(e)}});return _.useEffect(()=>{if(!t||!e)return;let u=!0,m=!1,d=0;const f=async()=>{if(window.clearTimeout(d),!(!u||m||document.visibilityState==="hidden")){m=!0;try{await l(()=>u)}finally{m=!1,u&&(d=window.setTimeout(f,2e3))}}},g=()=>{f()};return d=window.setTimeout(g,0),window.addEventListener("focus",g),document.addEventListener("visibilitychange",g),()=>{u=!1,window.clearTimeout(d),window.removeEventListener("focus",g),document.removeEventListener("visibilitychange",g)}},[e,t,a]),{snapshot:o?.bookId===e?o.data:null,stale:!t||i===e,retry:()=>c(u=>u+1)}}const ms=new Set(["video","generate_video","concat","splice"]);function hm(e,t){const n=ve(t),o=e.cells.find(r=>r.outputArtifactId?.toLowerCase()===n);return o||(e.cells.find(r=>ms.has(r.type)&&Yr(e,r)?.toLowerCase()===n)??null)}function wo(e,t){let n;try{n=yo(e,t)}catch(o){const r=hm(e,t);if(!r)throw o;n=r}if(!ms.has(n.type))throw new Error(`${Z(n)} is not a video-producing cell`);if(!Yr(e,n))throw new Error(`${Z(n)} does not have a video output yet`);return n}const bm="[a-z0-9][a-z0-9-]*",ym=new RegExp(`^(?:please\\s+)?(?:/split|split)\\s+@(${bm})(?:\\s+([\\s\\S]+?))?(?:\\s+please)?[.!]?$`,"iu"),oe=.02;function G(e){return Math.round(e*1e3)/1e3}function ye(e){const t=Math.max(0,Math.round(e*1e3)),n=Math.floor(t/6e4),o=(t-n*6e4)/1e3;return`${n}:${o.toFixed(3).padStart(6,"0")}`}function pS(e){const t=e.pieces[e.selectedIndex]??e.pieces[0];return t?`Cutting ${ye(t.startSeconds)}–${ye(t.endSeconds)} (${t.durationSeconds.toFixed(3)}s)`:"Split video"}function gS(e){return typeof e!="number"||!Number.isFinite(e)||!(e>0)?null:1/e}function _m(e,t){return(e==="all"?Math.max(1,t):1)+1}function Hn(e){const t=e.trim().toLowerCase(),n=t.match(/^(\d+(?:\.\d+)?)\s*(?:s|secs?|seconds?)?$/u);if(n)return Number(n[1]);const o=t.match(/^(\d+)\s*(?:m|mins?|minutes?)\s*(?:(\d+(?:\.\d+)?)\s*(?:s|secs?|seconds?)?)?$/u);if(o)return Number(o[1])*60+Number(o[2]??0);const r=t.match(/^(?:(\d+):)?(\d+):([0-5]?\d(?:\.\d+)?)$/u);return r?Number(r[1]??0)*3600+Number(r[2])*60+Number(r[3]):null}function vm(e){return e.trim().replace(/^(?:into|at)\s+/iu,"").replace(/\s+(?:and|plus)\s+(?:(?:keep|use)\s+)?(?:the\s+)?(?:remaining|remainder|rest)(?:\s+(?:clip|part|video))?$/iu,"").trim()}function km(e){const t=vm(e);return t?t.split(/\s*(?:,|;|\band\b|\bthen\b)\s*/iu).map(n=>n.trim()).filter(Boolean):[]}function wm(e,t,n){const o=We(e),r=Nn(n,o),i=[];let s=r;for(let a=0;a<t;a+=1){const c=Nn(s,[...o,r,...i]);i.push(c),s=c}return{action:r,outputs:i}}function Sm(e){const t={id:Dt(),type:"video",label:`Chunk ${String(e.chunkIndex+1).padStart(2,"0")}`,slot:e.slot,inputs:{chunkCount:e.chunkCount,chunkIndex:e.chunkIndex,endSeconds:e.endSeconds,mediaRole:"split-video-output",producerCellId:e.actionCell.id,sourceCellId:e.source.id,startSeconds:e.startSeconds,state:"pending"}};return{chunkIndex:e.chunkIndex,endSeconds:e.endSeconds,outputCell:t,startSeconds:e.startSeconds}}function Im(e){return{id:e.id,type:e.type,...e.label===void 0?{}:{label:e.label},slot:e.slot,...e.provider===void 0?{}:{provider:e.provider},...e.operation===void 0?{}:{operation:e.operation},...e.tool===void 0?{}:{tool:e.tool},...e.inputs===void 0?{}:{inputs:e.inputs}}}function xm(e){const t=e.trim().match(/^(keep|remove)\s+([\s\S]+)$/iu);if(!t)return null;const n=t[2].trim().match(/^(.+?)\s*[-–]\s*(.+)$/u);if(!n)throw new Error("Use a keep/remove range, for example: /split @a1 keep 0.03-0.11");const o=Hn(n[1]),r=Hn(n[2]);if(o===null||r===null||!Number.isFinite(o)||!Number.isFinite(r)||!(r>o)||o<0)throw new Error("Use positive split times, for example: /split @a1 keep 0.03-0.11");return{endSeconds:G(r),mode:t[1].toLowerCase()==="remove"?"remove":"keep",startSeconds:G(o)}}function hS(e){const t=e.trim().match(ym);if(!t)return null;const n=t[2]?.trim()??"";if(n&&/^(keep|remove)\b/iu.test(n)){const i=xm(n);if(!i)return null;const s=[i.startSeconds,i.endSeconds].filter(a=>a>0).sort((a,c)=>a-c);return{sourceReference:t[1].toLowerCase(),cutPointsSeconds:s,outputMode:i.mode,selectedChunkIndexes:[i.startSeconds>0?1:0]}}const r=(n?km(n):[]).map(Hn);if(r.some(i=>!Number.isFinite(i)||!(i>0)))throw new Error("Use positive split times, for example: /split @a3 at 15s, 28.5s");return{sourceReference:t[1].toLowerCase(),cutPointsSeconds:r.map(i=>G(i)).sort((i,s)=>i-s)}}function Gt(e){for(const t of e)if(!(G(t.endSeconds-t.startSeconds)>=oe))throw new Error(`Keep at least ${oe}s in every output range`)}function un(e){const t=G(e.sourceDurationSeconds);if(!Number.isFinite(t)||t<oe)throw new Error(`Video must be at least ${oe}s long to split`);const o=(e.cutPointsSeconds.length>0?e.cutPointsSeconds:[t/2]).map(s=>G(s)).sort((s,a)=>s-a);if(o.some(s=>!Number.isFinite(s)))throw new Error("Split times must be finite numbers");const r=[0,...o,t],i=r.slice(0,-1).map((s,a)=>({endSeconds:r[a+1],startSeconds:s}));for(const s of i)if(!(s.endSeconds>s.startSeconds))throw new Error(`Keep at least ${oe}s in every output range`);return i}function bS(e){const t=un(e);return Gt(t),t.slice(0,-1).map(n=>n.endSeconds)}function Am(e){const t=un({cutPointsSeconds:e.cutPointsSeconds,sourceDurationSeconds:e.sourceDurationSeconds}),n=e.outputMode??"all";if(n==="all")return Gt(t),t.map(s=>[s]);const o=new Set((e.selectedChunkIndexes??[0]).filter(s=>Number.isSafeInteger(s)&&s>=0&&s<t.length));if(o.size===0&&o.add(0),n==="keep"){const s=t.filter((a,c)=>o.has(c));if(s.length===0)throw new Error("Keep at least one split piece");return Gt(s),s.map(a=>[a])}const r=t.filter((s,a)=>!o.has(a));if(r.length===0)throw new Error("Remove leaves nothing to keep");const i=r.reduce((s,a)=>s+(a.endSeconds-a.startSeconds),0);return Gt([{startSeconds:r[0].startSeconds,endSeconds:r[0].startSeconds+i}]),[r]}function Em(e){const t=e.outputMode??"all",n=un({cutPointsSeconds:e.cutPointsSeconds,sourceDurationSeconds:e.sourceDurationSeconds});if(t==="all")return`Split ${e.sourceAddress} into ${n.length} chunks`;const o=e.selectedChunkIndexes?.[0]??0,r=n[o]??n[0],i=`${ye(r.startSeconds)}-${ye(r.endSeconds)}`;return t==="keep"?`Cut ${i} out of ${e.sourceAddress}`:`Remove ${i} from ${e.sourceAddress}`}function Cm(e,t,n){if(e==="all")return`Chunk ${String(n+1).padStart(2,"0")}`;if(e==="keep"){const a=t[0];return`Cut ${ye(a.startSeconds)}-${ye(a.endSeconds)}`}const o=t[0],r=t[t.length-1],i=o.endSeconds,s=r.startSeconds;return t.length>=2&&s>i?`Without ${ye(i)}-${ye(s)}`:`Without ${ye(o.startSeconds)}-${ye(r.endSeconds)}`}function yS(e){const t=wo(e.document,e.command.sourceReference);if(!Number.isFinite(e.sourceDurationSeconds)||e.sourceDurationSeconds<=0)throw new Error(`${Z(t)} does not have a usable duration yet; wait for video processing to finish`);const n=e.command.outputMode??"all",o=e.command.selectedChunkIndexes??[],r=Am({cutPointsSeconds:e.command.cutPointsSeconds,outputMode:n,selectedChunkIndexes:o,sourceDurationSeconds:e.sourceDurationSeconds}),i=un({cutPointsSeconds:e.command.cutPointsSeconds,sourceDurationSeconds:e.sourceDurationSeconds}).slice(0,-1).map(d=>d.endSeconds),s=wm(e.document.cells,r.length,t.slot),a=r.map(d=>d.map(f=>({endSeconds:f.endSeconds,startSeconds:f.startSeconds}))),c={id:Dt(),type:"split_video",label:n==="all"?`Split into ${r.length} chunks`:Em({cutPointsSeconds:i,outputMode:n,selectedChunkIndexes:o.length>0?o:[0],sourceAddress:Z(t),sourceDurationSeconds:e.sourceDurationSeconds}),slot:s.action,provider:"local",operation:n==="all"?"split_at_points":"split_ranges",tool:"ffmpeg",inputs:{cutPointsSeconds:i,endSeconds:e.sourceDurationSeconds,sourceCellId:t.id,sourceDurationSeconds:e.sourceDurationSeconds,startSeconds:0,state:"ready",...n==="all"?{}:{outputsSeconds:a,selectedChunkIndexes:o}}},l=r.map((d,f)=>{const g=d[0].startSeconds,p=d.reduce((v,S)=>v+(S.endSeconds-S.startSeconds),g),y=Sm({actionCell:c,chunkCount:r.length,chunkIndex:f,endSeconds:d.length===1?d[0].endSeconds:p,slot:s.outputs[f],source:t,startSeconds:g});return y.outputCell={...y.outputCell,label:Cm(n,d,f)},y}),u=[c,...l.map(d=>d.outputCell)],m=[{id:Dt(),source:t.id,target:c.id,targetInput:"video"},...l.map(d=>({id:Dt(),source:c.id,target:d.outputCell.id,targetInput:"media"}))];return{actionCell:c,createdCellIds:u.map(d=>d.id),cutPointsSeconds:i,document:{...e.document,cells:[...e.document.cells,...u],edges:[...e.document.edges,...m]},outputs:l,sourceCellId:t.id,sourceAddress:Z(t)}}async function _S(e){const t=[];let n=!1;try{const o=[e.draft.actionCell,...e.draft.outputs.map(c=>c.outputCell)];for(const[c,l]of o.entries()){t.push(l.id);const u=await e.callTool("create_notebook_cell",{book_id:e.bookId,notebook_id:e.draft.document.id,...c===0&&e.expectedRevision?{expected_revision:e.expectedRevision}:{},cell:Im(l)}),m=h(u);if(x(m?.id)!==l.id)throw new Error("The server did not preserve the planned split cell")}await e.callTool("connect_notebook_cells",{book_id:e.bookId,notebook_id:e.draft.document.id,source_cell_id:e.draft.sourceCellId,target_cell_id:e.draft.actionCell.id,target_input:"video"});for(const c of e.draft.outputs)await e.callTool("connect_notebook_cells",{book_id:e.bookId,notebook_id:e.draft.document.id,source_cell_id:e.draft.actionCell.id,target_cell_id:c.outputCell.id,target_input:"media"});n=!0;const r=await e.callTool("run_notebook",{actor:e.actor,book_id:e.bookId,notebook_id:e.draft.document.id,cell_ids:[e.draft.actionCell.id]}),i=h(r),s=x(i?.job_id),a=x(i?.run_id);if(!s||!a)throw new Error("The server did not return a notebook split run");return{actionCellId:e.draft.actionCell.id,actionAddress:Z(e.draft.actionCell),outputs:e.draft.outputs.map(c=>({chunkIndex:c.chunkIndex,outputCellId:c.outputCell.id,outputAddress:Z(c.outputCell)})),cutPointsSeconds:e.draft.cutPointsSeconds,jobId:s,runId:a,sourceCellId:e.draft.sourceCellId,sourceAddress:e.draft.sourceAddress}}catch(o){if(!n)for(const r of t.reverse())await e.callTool("delete_notebook_cell",{book_id:e.bookId,notebook_id:e.draft.document.id,cell_id:r}).catch(()=>{});throw o}}const Mm=1/60;function Tm(e,t){return e[t]}function vS(e){const t=e.windows.filter(a=>Number.isFinite(a.startSeconds)&&Number.isFinite(a.endSeconds)&&a.endSeconds>a.startSeconds);if(t.length===0)return{type:"continue"};const n=e.frameDurationSeconds??Mm,o=e.pendingSeekSeconds;if(typeof o=="number"&&Number.isFinite(o)&&Math.abs(e.currentTimeSeconds-o)>n)return{type:"continue"};const r=Math.min(t.length-1,Math.max(0,e.activeWindowIndex)),i=Tm(t,r),s=e.currentTimeSeconds;if(s>=i.startSeconds&&s<i.endSeconds)return{type:"continue"};if(s>=i.endSeconds){const a=(r+1)%t.length;return{type:"seek",timeSeconds:t[a].startSeconds,windowIndex:a}}return{type:"seek",timeSeconds:i.startSeconds,windowIndex:r}}function kS(e){return e>0&&e<.25}function ze(e){return[...new Set(e.map(G))].filter(t=>Number.isFinite(t)).sort((t,n)=>t-n)}function Rm(e){return ze(e.slice(1,-1))}function $m(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function Ce(e){const t=G(e.sourceDurationSeconds),o=[0,...ze(e.cutPointsSeconds).filter(r=>r>0&&r<t),t];return o.slice(0,-1).map((r,i)=>{const s=o[i+1];return{durationSeconds:G(s-r),endSeconds:s,index:i,startSeconds:r}})}function wS(e){let t=0;return e.map(n=>(t=G(t+n),t))}function SS(e){const t=e.leadSeconds??1.5,n=G(e.sourceDurationSeconds),o=G(e.segment.startSeconds),r=G(e.segment.endSeconds),i=[],s=Math.max(0,G(o-t));o>s&&i.push({startSeconds:s,endSeconds:o});const a=Math.min(n,G(r+t));return a>r&&i.push({startSeconds:r,endSeconds:a}),{segment:{startSeconds:o,endSeconds:r},surroundings:i}}function ps(e){const t=G(e.sourceDurationSeconds),n=Ce(e),o=n[e.index];if(!o)return{maxEnd:t,maxStart:0,minEnd:oe,minStart:0};const r=n[e.index-1]?.startSeconds??0,i=n[e.index+1]?.endSeconds??t,s=e.index===0?0:G(r+oe);return{maxEnd:e.index===n.length-1?t:G(i-oe),maxStart:G(o.endSeconds-oe),minEnd:G(o.startSeconds+oe),minStart:s}}function So(e){const t=G(e.sourceDurationSeconds),n=Ce(e),o=n[e.index];if(!o)return{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index};const r=ps(e);let i=G(Math.min(r.maxStart,Math.max(r.minStart,e.startSeconds)));i>0&&i<oe&&(i=oe);let s=G(Math.min(r.maxEnd,Math.max(Math.max(r.minEnd,i+oe),e.endSeconds)));if(s<t&&t-s<oe&&(s=G(t-oe)),i===o.startSeconds&&s===o.endSeconds)return{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index};const a=n[e.index-1],c=n[e.index+1],l=a?ze(e.cutPointsSeconds.filter(p=>p<=a.startSeconds)):[],u=c?ze(e.cutPointsSeconds.filter(p=>p>=c.endSeconds)):[],m=[];i>0&&m.push(i),s<t&&m.push(s);const d=ze([...l,...m,...u]).filter(p=>p>0&&p<t),g=Ce({cutPointsSeconds:d,sourceDurationSeconds:t}).findIndex(p=>p.startSeconds===i&&p.endSeconds===s);return{cutPointsSeconds:d,selectedIndex:g>=0?g:e.index}}function IS(e){const n=Ce(e)[e.index];return n?So({...e,endSeconds:n.endSeconds,startSeconds:G(n.startSeconds+e.deltaSeconds)}):{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index}}function xS(e){const n=Ce(e)[e.index];return n?So({...e,endSeconds:G(n.endSeconds+e.deltaSeconds),startSeconds:n.startSeconds}):{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index}}function AS(e){const n=Ce(e)[e.index];if(!n)return{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index};const o=n.durationSeconds,r=ps(e),i=G(Math.min(r.maxEnd-o,Math.max(r.minStart,n.startSeconds+e.deltaSeconds))),s=G(i+o);return i===n.startSeconds&&s===n.endSeconds?{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index}:So({...e,endSeconds:s,startSeconds:i})}function ES(e){const n=Ce(e)[e.index];if(!n||n.durationSeconds<oe*2)return{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index};const o=G(n.startSeconds+n.durationSeconds/2),r=ze([...e.cutPointsSeconds,o]).filter(i=>i>0&&i<G(e.sourceDurationSeconds));return $m(r,e.cutPointsSeconds)?{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index}:{cutPointsSeconds:r,selectedIndex:e.index}}function CS(e){const t=Ce(e),n=t[e.index],o=t[e.index+1];return!n||!o?{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index}:{cutPointsSeconds:Rm([0,...e.cutPointsSeconds.filter(i=>i!==n.endSeconds),G(e.sourceDurationSeconds)]),selectedIndex:e.index}}const Nm={steps:[],credits:[]};function MS(e=Nm,t=_t){return{loading:!1,error:null,context:e,options:{enabled:Zm(e)},promptOverrides:{},creditsOverride:null,maxCharacters:t}}function TS(e,t){return e.maxCharacters===t?e:{...e,maxCharacters:t}}function ft(e,t){return e.slot.row-t.slot.row||e.slot.column-t.slot.column||e.id.localeCompare(t.id)}function Pm(e,t){const n=e.cells.filter(o=>!Ve(o)&&(o.outputArtifactId===t||o.outputEntityId===t));if(n.length>0){const o=n.filter(r=>r.type!=="generate_video");return(o.length>0?o:n).sort(ft)}return e.cells.filter(o=>Le(e,o)===t).sort(ft)}const yr=new Set(["generate_audio","generate_image","generate_video"]),Om=["sourceArtifactId","source_asset_id","first_asset_id","second_asset_id","additional_asset_ids"];function In(e,t){const n=e.inputs?.[t];return typeof n=="string"&&n.trim()?n:null}function Nt(e){return e?.trim()?e:null}function gs(e,t){const n=e.inputs?.[t];return(Array.isArray(n)?n:[n]).filter(r=>typeof r=="string"&&r.trim()!=="")}function Lm(e){return Om.flatMap(t=>gs(e,t))}function Fm(e){const t=new Map(e.cells.map(o=>[o.id,o])),n=new Map;for(const o of[...e.cells].sort(ft)){if(Ve(o))continue;const r=Le(e,o);if(!r)continue;const i=n.get(r);(!i||yr.has(i.type)&&!yr.has(o.type))&&n.set(r,o)}return{cellsById:t,cellsByArtifactId:n}}function hs(e,t,n){const o=e.edges.filter(s=>s.target===n.id).map(s=>s.source),r=gs(n,"sourceCellId"),i=Lm(n).flatMap(s=>{const a=t.cellsByArtifactId.get(s);return a?[a.id]:[]});return[...new Set([...o,...r,...i])].filter(s=>s!==n.id)}function _r(e,t,n,o){const r=new Set,i=[],s=[],a=n.map(c=>c.id);for(let c=0;c<a.length;c+=1){const l=a[c];if(!l||r.has(l))continue;r.add(l);const u=t.cellsById.get(l);if(u){if(i.push(u),o(u)){s.push(u);continue}for(const m of hs(e,t,u))r.has(m)||a.push(m)}}return{visited:i,stopped:s}}function Dm(e){return e.type==="generate_video"}function bs(e,t){const n=t.flatMap(o=>{const r=Le(e,o);return r?[r]:[]});return[...new Set(n)]}function Vm(e,t,n){const o=Hs(e,n.id)?.outputCell??null,r=hs(e,t,n).map(i=>t.cellsById.get(i)).filter(i=>i!==void 0).sort(ft);return{id:n.id,producerCellId:n.id,outputCellId:o?.id??null,outputArtifactId:o?Le(e,o)??null:Le(e,n)??null,producerPrompt:Nt(n.prompt)??In(n,"prompt"),producerResolvedPrompt:In(n,"resolvedPrompt")??In(n,"resolved_prompt"),producerTool:Nt(n.tool),producerModel:Nt(n.model),producerProvider:Nt(n.provider),sourceArtifactIds:bs(e,r)}}function RS(e,t){const n=Fm(e),o=Pm(e,t),r=_r(e,n,o,Dm).stopped.sort(ft),i=_r(e,n,o,()=>!1).visited;return{steps:r.map(s=>Vm(e,n,s)),upstreamArtifactIds:bs(e,i)}}function $S(e){const t=e.attempts.find(n=>n.status==="completed"&&n.artifactId===e.outputArtifactId&&n.resolvedPrompt?.trim());return t?.resolvedPrompt?.trim()?t.resolvedPrompt:e.outputAssetPrompt?.trim()?e.outputAssetPrompt:e.producerResolvedPrompt?.trim()?e.producerResolvedPrompt:e.producerPrompt?.trim()?e.producerPrompt:""}function NS(e){const t=e.outputArtifactId?e.attempts.find(s=>s.status==="completed"&&s.artifactId===e.outputArtifactId)??null:null,n=t?.tool?.trim()||e.producerTool,o=n?e.actions.find(s=>s.tool===n):void 0,r=o?.title.trim()||t?.model?.trim()||e.producerModel?.trim()||n?.trim()||"";if(!r)return null;const i=o?.providerLabel.trim()||t?.provider?.trim()||e.producerProvider?.trim()||null;return{label:r,provider:i}}const ys="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",jm=new RegExp(`^${ys}$`,"iu"),Gm=new RegExp(`@(${ys}|${Ws})(?![\\w-])`,"giu");function qm(e){return e==="video"||e==="final"?"video":e==="image"||e==="audio"?e:"source"}function PS(e,t){const n=new Map(t.map(i=>[ve(i.reference),i.type])),o=new Map,r=new Map;return e.replace(Gm,(i,s)=>{const a=ve(s),c=o.get(a);if(c)return c;const l=n.get(a);if(!l&&!jm.test(a))return i;const u=qm(l),m=(r.get(u)??0)+1;r.set(u,m);const d=`[${u} ${m}]`;return o.set(a,d),d})}const Um=new Set(["youtube.com","m.youtube.com","music.youtube.com","youtu.be"]),Bm=new Set(["x.com","mobile.x.com","twitter.com","mobile.twitter.com"]),Hm=new Set(["explore","home","i","intent","messages","notifications","search","settings","share"]);function Wm(e,t){if(t==="youtu.be")return e.pathname.split("/")[1]||null;const n=e.searchParams.get("v");return n||(e.pathname.match(/^\/(?:shorts|embed|live|v)\/([A-Za-z0-9_-]+)/)?.[1]??null)}function Km(e,t){const n=Wm(e,t);return n&&e.pathname.startsWith("/shorts/")?{kind:"youtube",url:`https://www.youtube.com/shorts/${n}`,videoId:n}:n?{kind:"youtube",url:`https://youtu.be/${n}`,videoId:n}:(e.hash="",{kind:"youtube",url:e.toString(),videoId:null})}function zm(e){const t=e.pathname.match(/^\/([A-Za-z0-9_]{1,15})\/status\/(\d+)/);if(!t)return e.hash="",{kind:"x",url:e.toString(),handle:null,status:!1};const n=t[1],o=Hm.has(n.toLowerCase())?null:n;return{kind:"x",url:`https://x.com/${n}/status/${t[2]}`,handle:o,status:!0}}function Xm(e){if(typeof e!="string")return null;try{const t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return null;const n=t.hostname.toLowerCase().replace(/^www\./,"");return Um.has(n)?Km(t,n):Bm.has(n)?zm(t):null}catch{return null}}function Ym(e){return e.kind==="youtube"?e.videoId!==null:e.status}function Jm(e,t){return typeof e.uploader!="string"?t:e.uploader.replaceAll("@","").replace(/\s+/g," ").trim()||t}function OS(e,t){const n=[t.webpage_url,t.webpageUrl,t.source_url,t.sourceUrl].map(Xm).filter(r=>r!==null),o=n.find(Ym)??n[0];return o?{id:`${e}:${o.url}`,label:Jm(t,o.kind==="x"?"X":"YouTube"),url:o.url,xHandle:o.kind==="x"?o.handle:null}:null}function LS(e){const t=new Set;return e.filter(n=>t.has(n.url)?!1:(t.add(n.url),!0))}const FS="The thread has nothing to post. Add a prompt, or turn the thread off.";function Zm(e){return e.credits.length>0||e.steps.some(t=>t.prompt.trim()!==""||t.images.length>0)}function Qm(e){return e.slice(0,Pn)}function _s(e,t){return t>1?` (${e+1}/${t})`:""}function vs(e,t,n){const o=_s(t,n);if(!e.model)return`Prompt${o}:
15
+ `;const r=e.model.provider?` via ${e.model.provider}`:"";return`Made with ${e.model.label}${r}${o}. Prompt:
16
+ `}const ep="…",tp=2;function np(e,t){for(let n=Math.min(t,e.length-1);n>=0;n-=1)if(/\s/u.test(e.charAt(n)))return n;return-1}function op(e,t){if(e.length<=t)return e;const n=Math.max(0,t-tp),o=np(e,n),r=o>Math.floor(n/2)?o:n;return`${e.slice(0,r).trimEnd()}${ep}`}function rp(e,t,n,o){const r=vs(e,t,n);return op(e.prompt.trim(),o-r.length)}function ip(e,t){const n=e.context.steps.findIndex(o=>o.id===t.id);return n===-1?0:n}function sp(e,t){return e.promptOverrides[t.id]??rp(t,ip(e,t),e.context.steps.length,e.maxCharacters)}function ap(e){return e.xHandle?`@${e.xHandle}`:e.label}function vr(e){return`${ap(e)}: ${e.url}`}function cp(e,t=_t){const n=[...e].sort((i,s)=>+(i.xHandle===null)-+(s.xHandle===null)),o=n[0];if(!o)return"";if(n.length===1)return`Special thanks to ${vr(o)}`;const r=`Special thanks to:
17
+ ${n.map(vr).join(`
18
+ `)}`;return r.length<=t?r:`Special thanks to:
19
+ ${n.map(i=>i.url).join(`
20
+ `)}`}function lp(e){return e.creditsOverride??cp(e.context.credits,e.maxCharacters)}function ks(e,t,n,o){return{id:e,stepId:t,text:n,imageAssetIds:o.map(r=>r.assetId),images:[...o]}}function up(e,t,n,o){const r=sp(e,t).trim(),i=Qm(t.images);if(!r&&i.length===0)return null;const s=r?`${vs(t,n,o)}${r}`:`Input images for this video${_s(n,o)}:`;return ks(`step:${t.id}`,t.id,s,i)}function dp(e){if(!e.options.enabled)return[];const t=e.context.steps.length,n=e.context.steps.flatMap((r,i)=>{const s=up(e,r,i,t);return s?[s]:[]}),o=e.context.credits.length>0?lp(e).trim():"";return o&&n.push(ks("credits",null,o,[])),n}function DS(e){return dp(e).map(t=>({text:t.text,imageAssetIds:t.imageAssetIds}))}const fp=2e3,mp=6*6e4,VS={status:null,connecting:!1,authorizeUrl:null,error:null};function pp(e){const t=h(e),n=W(t?.username),o=W(t?.subscription_type);return n&&o?{username:n,subscriptionType:o}:null}function gp(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:_t}function hp(e){const t=h(e);return{connected:t?.connected===!0,pending:t?.pending===!0,hasCredentials:t?.has_credentials===!0,error:W(t?.error),expiresAt:W(t?.expires_at),account:pp(t?.account),postMaxCharacters:gp(t?.post_max_characters)}}function bp(e){return e?.postMaxCharacters??_t}function yp(e){switch(e){case"Basic":return"X Premium Basic";case"Premium":return"X Premium";case"PremiumPlus":return"X Premium+";case"None":return"No X Premium";default:return e}}function _p(e){if(!e.account)return null;const t=bp(e).toLocaleString("en-US");return`${yp(e.account.subscriptionType)}: posts up to ${t} characters.`}async function kr(e,t={}){return hp(await e("service_status",{service:"x",...t.refreshAccount?{refresh_account:!0}:{}},{background:!0}))}async function jS(e){const t=h(await e("connect_service",{service:"x"})),n=W(t?.authorize_url);if(!n)throw new Error("X did not return an authorization URL.");return n}async function GS(e,t){const n=t.now??Date.now,o=t.pollMs??fp,r=t.timeoutMs??mp,i=n();let s=await kr(e);for(;s.pending;){if(n()-i>=r)return{...s,pending:!1,error:"Timed out waiting for X authorization."};await t.sleep(o),s=await kr(e)}return s}function qS(e){return e.error?{ok:!1,message:e.error}:e.connected?{ok:!0,message:"X account connected"}:{ok:!1,message:"X authorization did not complete."}}function vp(e){return new Date(e).toLocaleString([],{hour:"2-digit",minute:"2-digit",month:"short",day:"numeric"})}function kp(e,t){const n=e?Date.parse(e):Number.NaN;return Number.isFinite(n)?n<=t?"Access token expired; it renews automatically on next use.":`Access token renews automatically; the current one expires ${vp(n)}.`:"Tokens renew automatically."}function US(e,t={}){if(t.connecting)return{tone:"pending",label:"Waiting for X authorization",detail:"Approve the request in the browser tab that opened.",actionLabel:null};if(!e)return{tone:"unknown",label:"Not checked",detail:"Refresh to check the X connection.",actionLabel:"Connect X"};if(!e.hasCredentials)return{tone:"missing-credentials",label:"App credentials missing",detail:"Save X_CLIENT_ID and X_CLIENT_SECRET as provider keys first. They come from console.x.com → your app → OAuth 2.0.",actionLabel:null};if(e.pending)return{tone:"pending",label:"Waiting for X authorization",detail:"An authorization started elsewhere is still open in a browser tab.",actionLabel:null};if(e.error)return{tone:"error",label:"Connection failed",detail:e.error,actionLabel:e.connected?"Reconnect X":"Connect X"};if(e.connected){const n=_p(e);return{tone:"connected",label:e.account?`Connected as @${e.account.username}`:"Connected",detail:[n,kp(e.expiresAt,t.now??Date.now())].filter(o=>o!==null).join(" "),actionLabel:"Reconnect X"}}return{tone:"disconnected",label:"Not connected",detail:"Posting needs a one-time browser authorization; tokens renew on their own afterwards.",actionLabel:"Connect X"}}const wp={DROPBOX_CLIENT_ID:"Dropbox app key",DROPBOX_CLIENT_SECRET:"Dropbox app secret (optional)",X_CLIENT_ID:"X client ID",X_CLIENT_SECRET:"X client secret",B2_ACCESS_KEY_ID:"Access key ID",B2_SECRET_ACCESS_KEY:"Secret access key",B2_REGION:"Region",B2_BUCKET:"Bucket",B2_ENDPOINT:"Endpoint",B2_ARCHIVE_PREFIX:"Archive prefix"};function Sp(e){return wp[e.envKey]??e.label}function Wn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function BS(e){const t=Wn(e);if(!Array.isArray(t?.providers))throw new Error("Could not read provider settings");return t.providers.flatMap(n=>{const o=Wn(n);return!o||typeof o.envKey!="string"||typeof o.label!="string"||typeof o.provider!="string"?[]:[{envKey:o.envKey,provider:o.provider,label:o.label,keyStatus:typeof o.keyStatus=="string"?o.keyStatus:"missing",maskedKey:typeof o.maskedKey=="string"?o.maskedKey:null,editable:o.editable===!0&&o.source!=="1password",secret:o.secret!==!1,source:typeof o.source=="string"?o.source:"missing"}]})}function HS(e){const t=Wn(e);if(!t||typeof t.state!="string"||typeof t.head!="string"||typeof t.pendingObjects!="number"||!Number.isSafeInteger(t.pendingObjects)||t.pendingObjects<0)throw new Error("Could not read project storage status");return{...t,state:t.state,head:t.head,pendingObjects:t.pendingObjects,...typeof t.lastError=="string"?{lastError:t.lastError}:{}}}function WS(e){const[t,n]=_.useState(null),[o,r]=_.useState(!1),[i,s]=_.useState(null),a=_.useRef(null),c=_.useRef(0),l=()=>{c.current+=1,n(null);const d=a.current;sn(()=>d)()};return{draft:t,saving:o,message:i,edit:(d,f)=>{!d.editable||o||(c.current+=1,a.current=f,s(null),n({key:d.envKey,value:d.secret?"":d.maskedKey??""}))},close:l,save:async d=>{if(!t||t.key!==d.envKey||!t.value.trim()||o||!d.editable)return;const f=c.current;r(!0),s(null);try{if(await e(t.key,t.value),f!==c.current)return;s({key:t.key,text:`${Sp(d)} saved`,error:!1}),l()}catch(g){f===c.current&&s({key:t.key,text:g instanceof Error?g.message:String(g),error:!0})}finally{r(!1)}},change:d=>n(f=>f?{...f,value:d}:null)}}const Io={label:"In place · previous version kept",tone:"warning"};function He(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0&&e[t]!==null}function $e(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function xe(e){return typeof e=="string"&&e.trim()?e.trim():null}function De(e){const t=$e(e);return t!==null?me(t):xe(e)}function je(e,t){const n=to(e).map(r=>r.raw),o=xe(t.asset_id);return o?.startsWith("@")?o:n.length===1?n[0]:o?`@${o}`:"Not provided"}function L(e,t,n="default",o=!1){return{label:e,value:t,tone:n,wide:o}}function Ip(e,t){const n=$e(e),o=$e(t);return n===null||o===null||o<n?null:me(o-n)}function xp(e){const t=He(e.params,"start_time")?De(e.params.start_time)??"Not provided":"0:00 (default)",n=De(e.params.end_time)??"Not provided",o=Ip(e.params.start_time??0,e.params.end_time)??"Calculated on apply";return{title:"Extract new video clip",settings:[L("Source",je(e.input,e.params)),L("Start",t),L("End",n),L("Duration",o),L("Output","New clip · source preserved"),L("Name",xe(e.params.name)??"Automatic")],effect:{label:"New clip · source preserved",tone:"default"}}}function Ap(e){const t=De(e.params.chunk_a_end)??"Not provided",n=He(e.params,"chunk_b_start")?e.params.chunk_b_start:e.params.chunk_a_end,o=De(n)??"Not provided",r=$e(e.params.chunk_a_end),i=$e(n),s=r!==null&&i!==null&&i<r?me(r-i):"None";return{title:"Split video into two clips",settings:[L("Source",je(e.input,e.params)),L("First clip",`0:00 → ${t}`),L("Remaining clip",`${o} → end`),L("Overlap",s),L("Output","Two new clips · source preserved")],effect:{label:"Two new clips · source preserved",tone:"default"}}}function Ep(e){const t=He(e.params,"cut_start")||He(e.params,"cut_end"),n=t?"cut_start":"trim_start",o=t?"cut_end":"trim_end",r=He(e.params,n)?De(e.params[n])??"Not provided":t?"Not provided":"0:00 (default)",i=He(e.params,o)?De(e.params[o])??"Not provided":t?"Not provided":"End of video";return{title:t?"Remove section from video":"Trim video in place",settings:[L("Source",je(e.input,e.params)),L("Operation",t?"Remove range":"Keep range"),L("Start",r),L("End",i),L("Output","Existing source updated in place","warning"),L("Recovery","Previous version retained")],effect:Io}}function mt(e){const t=e.replaceAll("_"," ").replaceAll("-"," ");return t.charAt(0).toUpperCase()+t.slice(1)}function Cp(e){return String(Number(e.toFixed(2)))}function Mp(e){const t=$e(e.sourceDurationSeconds),n=$e(e.params.speed),o=$e(e.params.target_duration_seconds),r=n??(t!==null&&o!==null&&o>0?t/o:null),i=o??(t!==null&&r!==null&&r>0?t/r:null),s=[L("Source",je(e.input,e.params))];return t!==null&&t>0&&s.push(L("Source duration",me(t))),s.push(L("Speed",r!==null?`${Cp(r)}×${n===null?" (from target duration)":""}`:"Calculated on apply")),o!==null&&s.push(L("Target duration",me(o))),i!==null&&i>0&&o===null&&s.push(L("Expected duration",me(i))),s.push(L("Output","Existing source updated in place","warning"),L("Recovery","Previous version retained")),{title:"Change video speed",settings:s,effect:Io}}function Tp(e){const t=xe(e.params.scheduled_for),n=xe(e.params.orientation);return{title:"Post to X",settings:[L("Destination","X"),L("Source",je(e.input,e.params)),L("Publish",t?`Scheduled · ${t}`:"Now","default",t!==null),L("Orientation",n?mt(n):"Keep source")],effect:{label:t?"Publishes to X · scheduled":"Publishes to X · now",tone:"default"},postText:typeof e.params.text=="string"?e.params.text:""}}const xo=/api.?key|secret|(?:^|[_-])token(?:$|[_-])|password|credential|authorization/iu;function Rp(e,t){return e!=="value"?!1:Object.entries(t).some(([n,o])=>/^(?:env_?)?key$|^(?:variable_?)?name$/iu.test(n)&&typeof o=="string"&&xo.test(o))}function Kn(e){return Array.isArray(e)?e.map(Kn):typeof e!="object"||e===null?e:Object.fromEntries(Object.entries(e).map(([t,n])=>[t,xo.test(t)?"Hidden":Kn(n)]))}function ws(e,t,n){if(xo.test(e)||Rp(e,n))return"Hidden";if(/time|seconds|duration/iu.test(e)){const r=De(t);if(r)return r}if(typeof t=="boolean")return t?"Yes":"No";if(typeof t=="number")return String(t);if(typeof t=="string"&&(/url/iu.test(e)||/^https?:\/\//iu.test(t)))return t;if(typeof t=="string")return t.length>96?`${t.slice(0,93)}…`:t;const o=JSON.stringify(Kn(t));return o?o.length>96?`${o.slice(0,93)}…`:o:"None"}function $p(e){const t=Array.isArray(e.params.steps)?e.params.steps:[],n=t.flatMap((r,i)=>{const s=xn(r),a=xe(s?.tool)??`step ${i+1}`,c=xn(s?.params)??{},l=xe(c.asset_id)??xe(c.audio_asset_id)??je(e.input,c);return[L(`Step ${i+1}`,`${mt(a)} · ${l}`)]}),o=t.some(r=>{const i=xe(xn(r)?.tool);return i==="replace_video_audio"||i==="trim_video"});return{title:"Chained actions",settings:n.length>0?n:[L("Tool","chain")],effect:o?Io:null}}function wr(e){return e===null?"Unknown":e<.01?`${Math.round(e*100)}¢`:`$${e.toFixed(2)}`}function KS(e,t){const n=[L("Step",`${e.index+1} of ${e.total}`),...e.address?[L("Source",e.address)]:[],...Object.entries(e.params).filter(([o])=>o!=="prompt"&&o!=="_provider").slice(0,5).map(([o,r])=>L(mt(o),ws(o,r,e.params))),L("Estimated cost",wr(e.estimateUsd),e.estimateUnavailable?"warning":"default"),L("Remaining steps",t>0?String(t):"None")];return{title:`Step ${e.index+1} of ${e.total} · ${e.title}`,settings:n,effect:{label:e.estimateUnavailable?"Cost unknown for this model":`Spends about ${wr(e.estimateUsd)}`,tone:"warning"},postText:typeof e.params.prompt=="string"?e.params.prompt:void 0}}function xn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Np(e){const t=Object.entries(e.params).filter(([n])=>n!=="book_id").slice(0,8).map(([n,o])=>L(mt(n),n==="asset_id"?je(e.input,e.params):ws(n,o,e.params),"default",/url/iu.test(n)&&typeof o=="string"));return{title:mt(e.tool),settings:t.length>0?t:[L("Tool",e.tool)],effect:null}}function zS(e){return e.tool==="extract_video_clip"?xp(e):e.tool==="split_video"?Ap(e):e.tool==="trim_video"?Ep(e):e.tool==="change_video_speed"?Mp(e):e.tool==="post"?Tp(e):e.tool==="chain"?$p(e):Np(e)}const It={blocking:null,notice:null};function ee(e){return{blocking:e,notice:null}}function Ss(e){return{blocking:null,notice:e}}function Sr(e,t,n){return t!==null?t>e:n<=0||e<n}function Pp(e){return e.trim().replace(/^@/,"").trim()}function XS(e){const t=Pp(e.handle),n=e.url.trim(),o=e.durationSeconds??0;return!e.includeHandle&&!e.includeQr?ee("Include a handle, a QR code, or both."):e.includeHandle&&!t?ee("Include handle is on but no handle is set. Type a handle, or turn Include handle off."):e.includeQr&&!n&&!t?ee("Include QR code is on but there is nothing to link. Enter a QR link, or a handle it can point to."):e.includeQr&&!Sr(e.qrStartSeconds,e.qrEndSeconds,o)?ee("QR end time must be after its start time."):e.includeHandle&&!Sr(e.handleStartSeconds,e.handleEndSeconds,o)?ee("Handle end time must be after its start time."):It}function YS(e){if(!e.prompt?.trim())return ee("Write a prompt before applying.");if(e.settingsError)return ee(e.settingsError);if(e.previewStale)return It;if(e.previewLoading)return ee("Waiting for the server preview.");if(e.previewError!==null)return ee(`Preview failed — ${e.previewError}`);const[t,...n]=e.promptLeaks;if(t){const o=n.length>0?` (+${n.length} more)`:"";return ee(`${t.message}${o}. Add it with Add input, or remove the mention.`)}return Ss(e.estimateUnknown?"No cost estimate is available for this model.":null)}function JS(e){const t=Ce({cutPointsSeconds:e.cutPointsSeconds,sourceDurationSeconds:e.sourceDurationSeconds});if(t.length===0)return ee("Nothing to split yet — add a cut point.");if(e.outputMode==="remove"&&t.length<2)return ee("Removing a piece needs at least two pieces. Add a cut first.");const n=_m(e.outputMode,t.length);return e.availableEmptyCells<n?ee(`This split needs ${n} empty notebook cells; ${e.availableEmptyCells} available.`):It}function ZS(e){if(e.suggestions&&e.suggestions.every(s=>!s.included))return ee("Include at least one suggestion, or cancel.");const t=e.previews.flatMap(s=>s.conflicts)[0];if(t)return ee(t.message);if(e.previews.some(s=>!s.valid))return ee("A planned edit no longer fits the current sequence. Prepare it again.");const n=e.previews.flatMap(s=>s.warnings),[o,...r]=n;if(!o)return It;const i=r.length>0?` (+${r.length} more)`:"";return Ss(`${o.message}${i}`)}function QS(e,t,n){const o=Ya(e,t,n);return o?ee(o):It}function e0(e){return e.busy?{state:"busy",message:e.busyLabel,dismissible:!1}:e.validation.blocking!==null?{state:"blocking",message:e.validation.blocking,dismissible:!1}:e.outcome&&!e.outcome.ok?{state:"failed",message:e.outcome.message,dismissible:!0}:e.notice?.tone==="error"?{state:"failed",message:e.notice.message,dismissible:!0}:e.validation.notice!==null?{state:"notice",message:e.validation.notice,dismissible:!1}:e.outcome?.ok?{state:"info",message:e.outcome.message,dismissible:!0}:e.notice?{state:"info",message:e.notice.message,dismissible:!0}:{state:"ready",message:null,dismissible:!1}}const Op=1024,t0=`(min-width: ${Op}px)`;function n0(e){return e.state==="ready"&&!e.hasSecondaryActions&&e.wideEnough}function Lp(e){return e==="image"||e==="generate_image"?"image":e==="video"||e==="split_video"||e==="generate_video"||e==="concat"||e==="splice"?"video":e==="audio"||e==="extract_audio"||e==="generate_audio"?"audio":null}function Fp(e,t,n){const o=new Set(e.edges.filter(r=>r.target===t).map(r=>r.targetInput));if(!o.has(n))return n;for(let r=2;;r+=1){const i=`${n}_${r}`;if(!o.has(i))return i}}function Dp(e){return e==="generate_image"||e==="generate_video"||e==="generate_audio"}function o0(e,t){const n=t.targetHandle??"input",o=e.cells.find(s=>s.id===t.source),r=e.cells.find(s=>s.id===t.target);if(!o||!r||!Dp(r.type))return n;const i=Lp(o.type);return!i||i==="image"&&(n==="first_frame"||n==="last_frame")||i==="audio"&&(n==="replace_audio"||n==="scene_audio")?n:Fp(e,r.id,i)}function Vp(e){return e==="extract_audio"?["video"]:e==="split_video"?["video","analysis"]:e==="analysis"?["result"]:e==="image"?["media","segment"]:e==="audio"||e==="video"?["media"]:["input"]}function jp(e,t){if(t.inputs?.mediaRole!=="extract-frame-output")return null;const n=typeof t.inputs.sourceCellId=="string"?t.inputs.sourceCellId:null,o=n?e.get(n):void 0,r=Number(t.inputs.atSeconds??t.inputs.timestampSeconds);return{sourceAddress:o?ue(o.slot):null,atSeconds:Number.isFinite(r)?r:null}}function Gp(e){const t=new Map(e.cells.map(a=>[a.id,a])),n=Di(e),o=new Map,r=new Map,i=new Map,s=new Map;for(const a of e.edges){const c=o.get(a.target)??[];c.includes(a.targetInput)||c.push(a.targetInput),o.set(a.target,c),r.set(a.target,(r.get(a.target)??0)+1);const l=i.get(a.target)??{};l[a.targetInput]=(l[a.targetInput]??0)+1,i.set(a.target,l);const u=n.get(a.id)??Oi,m=Vi(u.sourceSide,u.sourcePortIndex),d=s.get(a.source)??[];d.includes(m)||d.push(m),s.set(a.source,d)}return e.cells.map(a=>{const c=jp(t,a),l=Ic(a,e.cells,e.edges);return{id:a.id,type:a.type==="timeline"||a.type==="goal"?a.type:"cell",...a.type==="timeline"?{dragHandle:".notebook-timeline-header",connectable:!1}:{},...["goal","post"].includes(a.type)?{connectable:!1}:{},position:Ze(a.slot),data:{kind:a.type,...a.label===void 0?{}:{label:a.label},subtitle:Ve(a)?nu():`${a.type.toUpperCase()} · CELL`,slot:a.slot,status:"ready",targetInputs:o.get(a.id)??Vp(a.type),targetConnectionCount:r.get(a.id)??0,targetInputConnectionCounts:i.get(a.id)??{},sourcePorts:s.get(a.id)??[],...a.prompt===void 0?{}:{prompt:a.prompt},...a.provider===void 0?{}:{provider:a.provider},...a.model===void 0?{}:{model:a.model},...a.operation===void 0?{}:{operation:a.operation},...a.tool===void 0?{}:{tool:a.tool},...a.outputEntityId===void 0?{}:{outputEntityId:a.outputEntityId},...a.outputArtifactId===void 0?{}:{outputArtifactId:a.outputArtifactId},...a.inputs===void 0?{}:{inputs:a.inputs},...c===null?{}:{frameProvenance:c},...l?.provider===void 0?{}:{producerProvider:l.provider},...l?.model===void 0?{}:{producerModel:l.model}}}})}function r0(e,t,n){let o=!1;const r=e.map(i=>i.id!==t||i.data.status===n?i:(o=!0,{...i,data:{...i.data,status:n}}));return o?r:e}function i0(e){const t=Di(e),n=new Map(e.cells.map(o=>[o.id,ii(o.type)]));return e.edges.map(o=>{const r=t.get(o.id)??Oi,i=n.get(o.source)??"data";return{id:o.id,source:o.source,sourceHandle:Vi(r.sourceSide,r.sourcePortIndex),target:o.target,targetHandle:o.targetInput,type:"busRiver",className:`workflow-edge edge-family-${i}`,data:r}})}function s0(e,t){return t?e.map(n=>{const o=new Set((n.className??"").split(/\s+/).filter(Boolean));return o.add(n.source===t||n.target===t?"workflow-edge-cell-focus":"workflow-edge-cell-dim"),{...n,className:[...o].join(" ")}}):e}function qp(e){return e.operation!=="rewrite_prompt"&&vt(e.type)}function a0(e){return e.tool==="edit_image_subjects"&&e.provider==="local"?!1:e.operation==="rewrite_prompt"||qp(e)}function it(e="text"){return{mode:e,reference:null,startSeconds:"0",durationSeconds:"",preparing:!1,error:null}}function Ir(e){return e instanceof Error?e.message:String(e)}function Up({initialMode:e="text",onStateChange:t,release:n}){let o=!0,r=0,i=it(e);const s=p=>{i=p,o&&t(p)},a=p=>{p&&Promise.resolve(n(p)).catch(()=>{})},c=p=>{r+=1;const y=i.reference;s(it(p)),a(y)};return{changeMode:p=>{o&&c(p)},clearError:()=>{o&&i.error&&s({...i,error:null})},clearReference:()=>{if(!o)return;r+=1;const p=i.reference;s({...i,reference:null,startSeconds:"0",durationSeconds:"",preparing:!1,error:null}),a(p)},close:()=>{o&&c("text")},getState:()=>i,prepare:async(p,y)=>{if(!o)return{status:"stale"};const v=r+1;if(r=v,i.mode===p)s({...i,preparing:!0,error:null});else{const S=i.reference;s({...it(p),preparing:!0}),a(S)}try{const S=await y();if(!o||v!==r)return a(S),{status:"stale"};const w=i.reference;return s({mode:p,reference:S,startSeconds:"0",durationSeconds:"",preparing:!1,error:null}),w!==S&&a(w),{status:"ready",mode:p,reference:S}}catch(S){if(!o||v!==r)return{status:"stale"};const w=Ir(S);return s({...i,preparing:!1,error:w}),{status:"error",error:w}}},resetInvalidRange:p=>{const y=Ir(p);return o&&s({...i,startSeconds:"0",durationSeconds:"",error:y}),y},setDurationSeconds:p=>{o&&s({...i,durationSeconds:p,error:null})},setStartSeconds:p=>{o&&s({...i,startSeconds:p,error:null})},stop:()=>{if(!o)return;o=!1,r+=1;const p=i.reference;i=it(),a(p)}}}function Bp(e){if(typeof e!="object"||e===null)return[];const t=e.preparationJobs;return Array.isArray(t)?t.flatMap(n=>{if(typeof n!="object"||n===null)return[];const o=n;return typeof o.bookId=="string"&&typeof o.jobId=="number"&&Number.isSafeInteger(o.jobId)&&o.jobId>0?[{bookId:o.bookId,jobId:o.jobId}]:[]}):[]}async function c0(e){const t=Date.now()+(e.timeoutMs??6e5);try{for(;!e.isCancelled();){const n=await e.search();let o=Bp(n);if(e.isCancelled())return;if(o.length===0)return n;for(e.onPreparing(!0);o.length>0;){if(Date.now()>=t)throw new Error("Search preparation is still running. Try searching again shortly.");if(e.isCancelled())return;const r=[];for(const i of new Set(o.map(s=>s.bookId))){const s=o.filter(c=>c.bookId===i),a=await e.listJobs(i,s.map(c=>c.jobId));if(!Array.isArray(a))throw new Error("The server returned an invalid search preparation status");for(const c of s){const l=a.find(u=>typeof u=="object"&&u!==null&&u.id===c.jobId);if(!l)throw new Error("Search preparation could not be found. Try searching again.");if(l.state==="failed"||l.state==="aborted"){const u=l.error;throw new Error(u?.message??"Search preparation failed. Try searching again.")}l.state!=="done"&&r.push(c)}}o=r,o.length>0&&await new Promise(i=>setTimeout(i,e.intervalMs??1e3))}}return}finally{e.onPreparing(!1)}}function Ue(e){if(typeof e!="object"||e===null)throw new Error("Invalid search indexing response");return e}async function l0(e){const t=Ue(await e.start());if(!Array.isArray(t.jobs))throw new Error("Invalid search indexing jobs");let n=t.jobs.map(i=>{const s=Ue(i);if(typeof s.bookId!="string"||typeof s.jobId!="number"||!Number.isSafeInteger(s.jobId)||s.jobId<=0)throw new Error("Invalid search indexing job");return{bookId:s.bookId,jobId:s.jobId}});const o={indexed:0,failed:0,failures:[]},r=Date.now()+(e.timeoutMs??20*6e4);for(;n.length>0;){if(e.isCancelled())return;if(Date.now()>=r)throw new Error("Indexing is still running. Reopen the Library to check coverage.");const i=[];for(const s of new Set(n.map(a=>a.bookId))){if(e.isCancelled())return;const a=n.filter(l=>l.bookId===s),c=await e.listJobs(s,a.map(l=>l.jobId));if(!Array.isArray(c))throw new Error("Invalid search indexing status");for(const l of a){const u=c.map(Ue).find(m=>m.id===l.jobId);if(!u)throw new Error("Indexing job could not be found. Reopen the Library to retry.");if(u.state==="done"){const m=Ue(u.result);if(typeof m.indexed!="number"||typeof m.failed!="number"||!Array.isArray(m.failures))throw new Error("Invalid search indexing result");o.indexed+=m.indexed,o.failed+=m.failed;for(const d of m.failures){const f=Ue(d).message;typeof f=="string"&&o.failures.length<20&&o.failures.push({message:f})}}else if(u.state==="failed"||u.state==="aborted"){o.failed+=1;const m=u.error?Ue(u.error).message:void 0;o.failures.length<20&&o.failures.push({message:typeof m=="string"?m:"Search indexing failed"})}else i.push(l)}}n=i,n.length>0&&await new Promise(s=>setTimeout(s,e.intervalMs??1e3))}return e.isCancelled()?void 0:o}function u0(e){const t=ne.c(10),n="text";let o;t[0]!==n?(o=()=>it(n),t[0]=n,t[1]=o):o=t[1];const[r,i]=_.useState(o);let s;t[2]!==n?(s=()=>Up({initialMode:n,onStateChange:i,release:cf}),t[2]=n,t[3]=s):s=t[3];const[a]=_.useState(s);let c,l;t[4]!==a?(c=()=>()=>{a.stop()},l=[a],t[4]=a,t[5]=c,t[6]=l):(c=t[5],l=t[6]),_.useEffect(c,l);let u;return t[7]!==a||t[8]!==r?(u={state:r,lifecycle:a},t[7]=a,t[8]=r,t[9]=u):u=t[9],u}const Ao={jobs:{path:"/jobs",name:"Jobs"},settings:{path:"/settings",name:"Settings"}},Hp=Object.entries(Ao);function d0(e){const t=e.replace(/\/+$/,"")||"/";return Hp.find(([,o])=>o.path===t)?.[0]??"notebook"}function f0(e){return e==="notebook"?"/":Ao[e].path}function m0(e){return e==="notebook"?"VIDEOBOOK":`${Ao[e].name} · VIDEOBOOK`}function Wp(e,t){return!e||!t?null:`${e}:${t}`}function Kp(e,t){return t?e[t]??null:null}function zp(e,t,n){if(!t)return{...e};const o=e[t];return o&&o.row===n.row&&o.column===n.column?e:{...e,[t]:n}}function p0(e,t){const n=ne.c(11);let o;n[0]===Symbol.for("react.memo_cache_sentinel")?(o={},n[0]=o):o=n[0];const[r,i]=_.useState(o);let s,a;n[1]!==e||n[2]!==t||n[3]!==r?(s=Wp(e,t),a=Kp(r,s),n[1]=e,n[2]=t,n[3]=r,n[4]=s,n[5]=a):(s=n[4],a=n[5]);const c=a;let l;n[6]!==s?(l=d=>{i(f=>zp(f,s,d))},n[6]=s,n[7]=l):l=n[7];const u=l;let m;return n[8]!==c||n[9]!==u?(m={lastWorkSlot:c,rememberLastWorkSlot:u},n[8]=c,n[9]=u,n[10]=m):m=n[10],m}function g0(e,t=n=>window.requestAnimationFrame(n)){t(()=>{t(()=>{const n=e();n&&n.scrollTo({top:n.scrollHeight,behavior:"smooth"})})})}function Xp(e,t){const n=e();if(!n)return()=>{};const o=n.closest(".app-shell")?.querySelector(".command-composer:not([hidden])");let r=0,i=!1;const s=()=>{i=!0,window.cancelAnimationFrame(r),l.disconnect(),n.scrollTo({top:n.scrollTop,behavior:"instant"}),window.removeEventListener("pointerdown",s,!0),window.removeEventListener("wheel",s,!0),window.removeEventListener("keydown",s,!0),window.removeEventListener("resize",s)},a=()=>{if(i)return;const u=e();if(!u)return s();const m=u.querySelectorAll(".react-flow__node.selected"),d=m.length===1?m[0]:null;if(!d||d.getAttribute("data-id")!==t)return s();const f=u.getBoundingClientRect(),p=Math.min(f.top+u.clientHeight,o?.getBoundingClientRect().top??f.bottom)-f.top;if(p<=0)return;const y=d.getBoundingClientRect(),v=Math.max(16,(p-y.height)/2),S=Math.max(0,Math.min(u.scrollHeight-u.clientHeight,u.scrollTop+y.top-f.top-v));Math.abs(S-u.scrollTop)<=2||u.scrollTo({top:S,behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"})},c=()=>{i||(window.cancelAnimationFrame(r),r=window.requestAnimationFrame(()=>{r=window.requestAnimationFrame(a)}))},l=new ResizeObserver(c);return l.observe(n),o&&l.observe(o),window.addEventListener("pointerdown",s,!0),window.addEventListener("wheel",s,{capture:!0,passive:!0}),window.addEventListener("keydown",s,!0),window.addEventListener("resize",s),c(),s}function h0(e,t,n){const o=ne.c(16),r=_.useRef(null);let i;o[0]===Symbol.for("react.memo_cache_sentinel")?(i={width:0,height:0,minimumZoom:0},o[0]=i):i=o[0];const[s,a]=_.useState(i),c=_.useRef(1),l=_.useRef(0),u=_.useRef(null),m=eu(s.width,s.minimumZoom);let d;o[1]===Symbol.for("react.memo_cache_sentinel")?(d=()=>{const I=r.current;I&&(l.current=I.scrollTop/c.current)},o[1]=d):d=o[1];const f=d;let g;o[2]!==n?(g=()=>{const I=r.current;if(!n||!I)return;I.scrollLeft=0,I.scrollTop=0,l.current=0;const E=()=>{f();const A=getComputedStyle(I),$=Math.max(0,I.clientWidth-parseFloat(A.paddingLeft)-parseFloat(A.paddingRight)),T=I.clientHeight,N=parseFloat(A.getPropertyValue("--notebook-minimum-zoom"))||0;a(M=>M.width===$&&M.height===T&&M.minimumZoom===N?M:{width:$,height:T,minimumZoom:N})};E(),I.addEventListener("scroll",f,{passive:!0});const C=new ResizeObserver(E);return C.observe(I),()=>{u.current?.(),I.removeEventListener("scroll",f),C.disconnect()}},o[2]=n,o[3]=g):g=o[3];let p;o[4]!==n||o[5]!==e||o[6]!==t?(p=[n,e,t,f],o[4]=n,o[5]=e,o[6]=t,o[7]=p):p=o[7],_.useLayoutEffect(g,p);let y,v;o[8]!==n||o[9]!==m?(y=()=>{const I=r.current;!n||!I||(I.scrollTop=l.current*m,c.current=m,f())},v=[n,f,m],o[8]=n,o[9]=m,o[10]=y,o[11]=v):(y=o[10],v=o[11]),_.useLayoutEffect(y,v);let S;o[12]===Symbol.for("react.memo_cache_sentinel")?(S=I=>{u.current?.(),u.current=Xp(()=>r.current,I)},o[12]=S):S=o[12];const w=S;let k;return o[13]!==s||o[14]!==m?(k={scrollRef:r,surface:s,zoom:m,revealCell:w},o[13]=s,o[14]=m,o[15]=k):k=o[15],k}function b0(e,t){const n=e?t.find(o=>o.artifactId===e||o.id===e):void 0;return!e||!n?{ok:!1,message:"Usage: /music-video @audio"}:n.type!=="audio"?{ok:!1,message:"/music-video requires an audio asset"}:n.status!=="ready"||!n.mediaUrl||!n.audioInfo?{ok:!1,message:"Process the audio asset before opening the music-video editor"}:{ok:!0,asset:n}}const y0=["source","cinematic","ig-influencer"],Yp={source:{id:"source",label:"Match source",summary:"Keep the look, camera and lighting of the source screenshot.",briefKeywords:[],defaults:{imageModel:"nano-banana-2-1",imageResolution:"2K",videoResolution:"720p"},planner:"Infer the visual style, framing, lighting and camera from the scene reference. Preserve that look. Identify the scene screenshot, character references and prop references from the actual images and brief. Reference images are not necessarily people. Remove social-media interface overlays from generated pictures.",fragments:{frame:"Match the source scene's framing, lighting and visual style; remove interface overlays",storyboard:"Keep the approved scene's visual style, people and props",ending:"Keep the approved scene's visual style",video:"Match the approved scene's camera and lighting; natural ambient sound",revise:"Preserve the selected image's visual style"},banned:[],options:[]},cinematic:{id:"cinematic",label:"Cinematic",summary:"Photographic live-action with natural proportions, textures and motion.",briefKeywords:["cinematic"],defaults:{},planner:"Photographic live-action. Natural proportions, real skin and material textures, practical light. Restrained expressions and plausible motion. Comedy comes from situations and timing; avoid cartoon rendering, caricature, rubbery movement and exaggerated features.",fragments:{frame:"Photographic live-action, natural proportions, real textures",storyboard:"Photographic live-action, natural proportions, real textures",ending:"Photographic live-action, natural proportions, real textures",video:"Live-action, natural motion, restrained expressions",revise:"Photographic live-action, natural proportions, real textures"},banned:[],options:[]},"ig-influencer":{id:"ig-influencer",label:"IG Influencer",summary:"Hyper-realistic, candid iPhone footage with natural skin and light.",briefKeywords:["ig influencer","instagram influencer","influencer","insta reel","instagram reel"],defaults:{aspectRatio:"9:16",imageModel:"sunburst",imageResolution:"2K",videoResolution:"720p"},planner:"Use a hyper-realistic Instagram phone-camera register: real-world activity in present tense, one location per shot, candid framing with slight imperfection, light grain, unretouched skin with visible pores and texture. Use the selected iPhone camera and lighting; natural daylight or soft indoor light by default. No HDR crunch or beautify. No captions or on-screen text inside pictures or video; storyboard notes go below pictures. Avoid cinematic, masterpiece, editorial, Portra, Cinestill and all film-stock vocabulary. Match the delivery: address the camera for selfies, be caught mid-action when filmed by a friend, hold framing steady on a tripod, or show the reflection for a mirror shot. Make the selected content format explicit in the four beats. Sound is ambient room or street sound with an optional short spoken line.",fragments:{frame:"hyper-realistic, skin pores, light grain",storyboard:"hyper-realistic, skin pores, light grain",ending:"hyper-realistic, skin pores",video:"hyper-realistic skin pores, natural motion, handheld micro-shake, ambient sound",revise:"hyper-realistic, skin pores"},banned:["cinematic","masterpiece","editorial","Portra","Cinestill"],options:[{key:"format",label:"Content format",default:"day-in-the-life",choices:[{value:"grwm",label:"GRWM",prompt:"GRWM",briefKeywords:["grwm","get ready with me"],beats:"skincare, outfit, final look, mirror check"},{value:"ootd",label:"OOTD",prompt:"OOTD",briefKeywords:["ootd","outfit of the day"],beats:"reveal, details, walk, turn"},{value:"day-in-the-life",label:"Day in the life",prompt:"day-in-the-life",briefKeywords:["day in the life","vlog"],beats:"arrive, begin activity, react, finish"},{value:"travel-reel",label:"Travel reel",prompt:"travel",briefKeywords:["travel reel"],beats:"arrive, explore, discover, farewell"},{value:"cafe",label:"Café",prompt:"café",briefKeywords:["brunch","cafe","café"],beats:"order, receive drink, taste, smile"},{value:"gym",label:"Gym",prompt:"gym",briefKeywords:["gym"],beats:"warm up, exercise, effort, recover"},{value:"skincare",label:"Skincare",prompt:"skincare",briefKeywords:["skincare"],beats:"cleanse, apply, massage, reveal"},{value:"haul",label:"Haul",prompt:"haul",briefKeywords:["haul"],beats:"unpack, show item, try on, react"},{value:"storytime",label:"Storytime",prompt:"storytime",briefKeywords:["storytime"],beats:"hook, explain, react, conclude"}]},{key:"delivery",label:"Delivery",default:"selfie-to-camera",choices:[{value:"selfie-to-camera",label:"Selfie to camera",prompt:"selfie",briefKeywords:["selfie","front camera"]},{value:"filmed-by-friend",label:"Filmed by a friend",prompt:"friend-filmed",briefKeywords:["filmed by"]},{value:"tripod",label:"Tripod",prompt:"tripod",briefKeywords:["tripod"]},{value:"mirror",label:"Mirror",prompt:"mirror",briefKeywords:["mirror"]}]},{key:"camera",label:"Camera",default:"iphone-front",choices:[{value:"iphone-front",label:"iPhone front camera",prompt:"iPhone front",briefKeywords:["front camera","iphone front"]},{value:"iphone-main",label:"iPhone main camera",prompt:"iPhone main",briefKeywords:["main camera","iphone main"]}]},{key:"light",label:"Light",default:"soft-daylight",choices:[{value:"soft-daylight",label:"Soft daylight",prompt:"soft daylight",briefKeywords:["soft daylight","natural daylight"]},{value:"golden-hour",label:"Golden hour",prompt:"golden hour",briefKeywords:["golden hour"]},{value:"indoor-warm",label:"Warm indoor light",prompt:"warm indoor",briefKeywords:["warm indoor","indoor warm"]},{value:"night-flash",label:"Night flash",prompt:"night flash",briefKeywords:["night out","flash"]}]}]}};function Yt(e){return Yp[e]}function zn(e,t={}){const n=Yt(e);for(const r of Object.keys(t))if(!n.options.some(i=>i.key===r))throw new Error(`Unknown ${n.label} option: ${r}`);const o={};for(const r of n.options){const i=r.key==="camera"&&o.delivery!=="selfie-to-camera"?"iphone-main":r.default,s=t[r.key]??i;if(!r.choices.some(a=>a.value===s))throw new Error(`Invalid ${n.label} ${r.label}: ${s}. Choose ${r.choices.map(a=>a.value).join(", ")}.`);o[r.key]=s}return o}function _0(e,t){const n=Yt(e.id),o=zn(e.id,e.options);let r=n.fragments[t];if(!r)return"";const i=n.options.map(s=>s.choices.find(a=>a.value===o[s.key]).prompt);return`${i.length?`${i.join(", ")}: `:""}${r}.`}function Jp(e,t){if(e.id!==t.id)return!1;const n=zn(e.id,e.options),o=zn(t.id,t.options);return Object.keys(n).every(r=>n[r]===o[r])}function pt(e){return!!(e&&"version"in e&&e.version===2)}function Ne(e){return!e||!("shots"in e)?[]:e.shots}function v0(e,t){return e.title===t.title&&e.continuity===t.continuity&&e.aspectRatio===t.aspectRatio&&e.imageModel===t.imageModel&&e.imageResolution===t.imageResolution&&e.videoResolution===t.videoResolution&&e.storyboardLayout===t.storyboardLayout&&JSON.stringify(e.referenceRoles??[])===JSON.stringify(t.referenceRoles??[])&&!!e.frameContinuity==!!t.frameContinuity&&Jp(e.style??{id:"cinematic",options:{}},t.style??{id:"cinematic",options:{}})&&e.frame.prompt===t.frame.prompt&&e.shots.length===t.shots.length&&e.shots.every((n,o)=>n.title===t.shots[o]?.title&&n.storyboardPrompt===t.shots[o]?.storyboardPrompt&&(n.endingPrompt??null)===(t.shots[o]?.endingPrompt??null)&&n.videoPrompt===t.shots[o]?.videoPrompt&&n.durationSeconds===t.shots[o]?.durationSeconds)}function k0(e,t,n){return e.stages[t]?.outputs.find(o=>o.index===n)?.versions??[]}function w0(e,t,n){return e.stages[t]?.outputs.find(o=>o.index===n)?.stale??null}function S0(e,t,n){const o=e.estimate[t].usd;if(o===null||t==="frame")return o;const r=Ne(e.plan),i=Math.max(1,r.length);if(t==="videos"&&r.length>0){const s=r.reduce((a,c)=>a+c.durationSeconds,0);return o*(r[n]?.durationSeconds??0)/s}return o/(i*(e.plan&&"frameContinuity"in e.plan&&e.plan.frameContinuity?2:1))}function Is(e){return Object.values(e.stages).flatMap(t=>t.attempts??[]).find(t=>t.chainId===e.chainId&&t.feedback)}function dn(e){const t=Is(e);if(!t)return null;if(e.planVersion===3){if(t.stage==="frame")return"scene";if(t.stage==="videos")return"video"}if(t.stage==="frame")return"frame";if(t.stage==="videos")return`video ${t.index+1}`;const n=Math.max(1,Ne(e.plan).length);return`${t.index>=n?"ending frame":"storyboard"} ${t.index%n+1}`}function I0(e){return(e.planVersion===2||e.planVersion===3)&&(e.status==="failed"||e.status==="interrupted")}function x0(e){return e.status!=="running"||!e.resumeStage?"Stop goal":Is(e)?"Stop revision":"Stop regeneration"}function Zp(e,t,n,o){if(n.phase!=="review"||!["frame","storyboards"].includes(t.phase)||!e.chainId||!o.stages[t.stage]?.previousChainIds.includes(e.chainId))return null;const r=dn(e);return`${r?`${r[0].toUpperCase()}${r.slice(1)} revision`:t.stage==="frame"?"Frame generation":"Storyboard generation"} stopped`}function xs(e){if(!e||typeof e!="object"||!("kind"in e)||e.kind!=="video-goal")throw new Error("The server returned an invalid video goal");return e}function Qp(e){if(!e||typeof e!="object"||!("goals"in e)||!Array.isArray(e.goals))throw new Error("The server returned an invalid goal list");return e.goals.map(xs)}function eg(e){return{planned:"Planned",waiting:"Waiting",submitting:"Submitting",generating:"Generating",done:"Ready",failed:"Failed",skipped:"Not started",stopped:"Stopped"}[e]}function gt(e){const t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function As(e){return e&&"version"in e&&e.version===3?e.video.durationSeconds:Ne(e).reduce((t,n)=>t+n.durationSeconds,0)}function tg(e,t,n){return t?t.status==="completed"?"done":t.status==="running"?t.address?"generating":"submitting":t.status==="failed"||t.status==="interrupted"?"failed":t.status==="cancelled"||t.status==="rejected"?"stopped":t.status==="skipped"?e.status==="cancelled"?"stopped":"skipped":"waiting":n?"done":e.status==="planning"||e.status==="review"?"planned":"waiting"}function ng(e){return Ne(e).map((t,n)=>({index:n,number:String(n+1).padStart(2,"0"),title:t.title,prompt:"videoPrompt"in t?t.videoPrompt:t.prompt,seconds:t.durationSeconds,state:"planned",startedAt:null,cellId:null,address:null,artifactId:null,error:null}))}function og(e,t){const n=e.plan,o=n&&"version"in n&&n.version===3?n:null,r=o?[{index:0,number:"01",title:t==="videos"?"Video":"Scene",prompt:t==="videos"?o.video.prompt:o.scene.prompt,seconds:t==="videos"?o.video.durationSeconds:0}]:t==="frame"&&pt(n)?[{index:0,number:"01",title:"Full frame",prompt:n.frame.prompt,seconds:0}]:Ne(n).map((c,l)=>({index:l,number:String(l+1).padStart(2,"0"),title:c.title,prompt:"videoPrompt"in c?t==="storyboards"?c.storyboardPrompt:c.videoPrompt:c.prompt,seconds:t==="videos"?c.durationSeconds:0})),i=!o&&t==="storyboards"&&pt(n)&&n.frameContinuity?[...r,...n.shots.map((c,l)=>({index:l+n.shots.length,number:`${String(l+1).padStart(2,"0")} end`,title:`${c.title} · Ending`,prompt:c.endingPrompt??c.videoPrompt,seconds:0}))]:r,s=e.stages[t],a=new Map((s?.steps??(e.planVersion===1?e.steps:[])).map(c=>[c.id,c]));return i.map(c=>{const l=o?t==="videos"?"video":"scene":t==="frame"?"frame":`${t==="storyboards"?"storyboard":"shot"}${c.index+1}`,u=a.get(l),m=s?.outputs.find(d=>d.index===c.index);return{...c,state:tg(e,u,!!m),startedAt:u?.startedAt??null,cellId:u?.cellId??m?.cellId??null,address:u?.address??m?.address??null,artifactId:u?.status==="completed"?u.artifactId:m?.artifactId??null,error:u?.error??null}})}function rg(e,t){return e.status==="cancelled"?"stopped":e.status==="completed"?"complete":e.status!=="running"?e.status:e.stage==="assembly"||e.steps.some(n=>n.id==="assemble"&&n.status==="running")?"assembling":t}function Qe(e){const t=e.stage==="assembly"?"videos":e.stage,n=og(e,t),o=rg(e,t),r=n.find(i=>i.state==="failed")??n.find(i=>i.state==="submitting"||i.state==="generating")??(["frame","storyboards","videos"].includes(o)?n.find(i=>i.state!=="done")??null:null);return{phase:o,stage:t,reviewStage:o==="review"?t:null,shots:n,done:n.filter(i=>i.state==="done").length,total:n.length,active:r,failedStep:e.steps.find(i=>i.status==="failed"||i.status==="interrupted")?.id??null}}function ig(e){return{frame:"Full frame",storyboards:"Storyboards",videos:"Videos"}[e]}function Jt(e,t){const n=e.estimate[t];return n.usd===null?"":` · est. $${n.usd.toFixed(2)}`}function sg(e,t){return e.failedStep===null?`Planning ${t}`:e.failedStep==="assemble"?`Assembly ${t}`:e.stage==="frame"?`Full frame ${t}`:`${e.stage==="storyboards"?"Storyboard":"Shot"} ${(e.active?.index??0)+1} ${t}`}function Oe(e,t,n,o,r){return{text:e,short:t,announce:`Goal: ${e}`,action:n,tone:o,busy:r}}function ag(e,t){if(e.planVersion!==3)return null;const n=Qe(e),o=e.finish;if(o?.status==="running")return Oe("Finishing the cold open and watermark","Finishing",null,"live",!0);if(o?.status==="failed")return Oe("Finishing failed","Finishing failed","Finish","attention",!1);if(n.phase==="review"){if(o){const r=e.coldOpen?` · analysis $${e.coldOpen.analysisUsd.toFixed(2)}`:"";return Oe(`Review finish${r}`,"Review","Review","review",!1)}return e.stage==="videos"?Oe(`Review video${Jt(e,"videos")}`,"Review","Review","review",!1):Oe(`Review scene${Jt(e,"frame")}`,"Review","Review","review",!1)}if(n.phase==="frame"||n.phase==="videos"){const r=n.active?.state==="generating"?`Generating${t===null?"":` ${gt(t)}`}`:"Submitting",i=dn(e),s=n.phase==="frame"?"Scene":"Video";return Oe(`${i?`Revising ${i}`:s} · ${r}`,s,null,"live",!0)}if(n.phase==="failed"||n.phase==="interrupted"){const r=n.phase==="failed"?"failed":"interrupted",i=e.chainId?`${n.stage==="videos"?"Video":"Scene"} ${r}`:`Planning ${r}`;return Oe(i,n.phase==="failed"?"Failed":"Interrupted","Retry","attention",!1)}return null}function ht(e,t=null){const n=ag(e,t);if(n)return n;const o=Qe(e),r=pt(e.plan)&&e.plan.storyboardLayout==="six-panel";let i="Stopped",s="Stopped",a=null,c="quiet",l=!1;if(o.phase==="planning")i=s="Planning",c="live",l=!0;else if(o.phase==="review")i=o.stage==="frame"?`Review ${r?"scene":"plan"}${Jt(e,"frame")}`:o.stage==="storyboards"?r?"Review scene":"Review full frame":r?"Review storyboard":"Review storyboards",s=a="Review",c="review";else if(["frame","storyboards","videos"].includes(o.phase)){const u=o.active?o.active.index+1:o.done+1,m=o.active?.state==="generating"?`Generating${t===null?"":` ${gt(t)}`}`:"Submitting",d=dn(e);i=`${d?`Revising ${d}`:o.stage==="frame"?r?"Scene":"Full frame":`${o.stage==="storyboards"?"Storyboard":"Shot"} ${u} of ${o.total}`} · ${m}`,s=o.stage==="frame"?"Frame":`${o.stage==="storyboards"?"SB ":""}${u}/${o.total}`,c="live"}else o.phase==="assembling"?(i=`Assembling ${o.total} clips`,s="Combining",c="live",l=!0):o.phase==="complete"?(i=`Complete · ${gt(As(e.plan))}`,s="Done",a="Preview",c="done"):(o.phase==="failed"||o.phase==="interrupted")&&(i=sg(o,o.phase==="failed"?"failed":"interrupted"),s=o.phase==="failed"?"Failed":"Interrupted",a=e.planVersion===1?null:"Retry",c="attention");return{text:i,short:s,announce:`Goal: ${i}`,action:a,tone:c,busy:l}}function xr(e){const t=Qe(e);return`${e.goalId}:${e.chainId??""}:${t.phase}:${t.stage}:${t.done}:${t.active?.index??-1}`}function cg(e,t){const n=xr(t);if(e.goalId!==t.goalId||xr(e)===n||t.status==="cancelled")return null;const o=Qe(e),r=Qe(t);let i=ht(e).text;const s=dn(t),a=Zp(e,o,r,t);return r.phase==="failed"||r.phase==="interrupted"?i=ht(t).text:r.phase==="complete"?i=t.assembly?"Sequence assembled":"Clip ready":o.phase==="planning"&&r.phase==="review"?i="Plan ready":a?i=a:r.phase==="review"&&s?i=`${s[0].toUpperCase()}${s.slice(1)} revised`:r.phase==="review"&&t.planVersion===3&&t.finish?i="Video ready":r.phase==="review"&&t.planVersion===3&&r.stage==="videos"?i="Scene ready":r.phase==="review"&&r.stage==="storyboards"?i="Full frame ready":r.phase==="review"&&r.stage==="videos"?i="Storyboards ready":o.phase==="review"?i=s?`Revising ${s}`:o.stage!=="frame"&&r.stage==="frame"?"Frame regeneration started":o.stage==="videos"&&r.stage==="storyboards"?"Storyboard regeneration started":r.stage==="frame"?"Plan approved":r.stage==="storyboards"?"Frame approved":"Storyboards approved":o.phase==="failed"||o.phase==="interrupted"?i=`Retrying ${ig(r.stage).toLowerCase()}`:r.done>o.done&&(i=`${r.stage==="storyboards"?"Storyboard":"Shot"} ${r.done} ready`),{id:n,from:i,tone:r.phase==="failed"||r.phase==="interrupted"?"attention":"live"}}function A0(e){return e.find(t=>t.status!=="cancelled"&&!t.dismissedAt&&t.cellId)??null}function E0(e){const t=new Map;for(const n of e){n.combined&&t.set(n.combined.cellId,`Combined${n.address?` · ${n.address}`:""}`);const o=Ne(n.plan).length,r=n.planVersion===1?n.steps:Object.values(n.stages).flatMap(i=>i.allSteps);for(const i of r){const s=/^(frame|storyboard|shot)(\d+)?$/.exec(i.id);if(!s)continue;const a=Number(s[2]);let c=s[1]==="frame"?"Frame":s[1]==="storyboard"&&a>o?`End ${a-o}/${o}`:`${s[1]==="storyboard"?"SB ":""}${s[2]}/${o}`;const l=s[1]==="frame"?"frame":s[1]==="storyboard"?"storyboards":"videos",u=n.stages[l]?.attempts?.filter(d=>d.index===(l==="frame"?0:a-1))??[],m=u.findIndex(d=>d.chainId===i.chainId&&d.stepId===i.id);u.length>1&&m>=0&&(c=`${l==="frame"?"Frame":l==="videos"?`Video ${a}`:a>o?`End ${a-o}`:`SB ${a}`} v${m+1}`);for(const d of[i.cellId,i.outputCellId])d&&t.set(d,`${c}${n.address?` · ${n.address}`:""}`)}}return t}const Ar=5,Er={planning:{label:"Planning",tone:"live"},review:{label:"Review",tone:"review"},frame:{label:"Frame",tone:"live"},storyboards:{label:"Storyboards",tone:"live"},videos:{label:"Videos",tone:"live"},assembling:{label:"Combining",tone:"live"},complete:{label:"Complete",tone:"done"},failed:{label:"Failed",tone:"attention"},interrupted:{label:"Interrupted",tone:"attention"},stopped:{label:"Stopped",tone:"quiet"}};function C0(e){const t=e?.plan;if(!t||typeof t!="object")return null;const n=t;return typeof n.title=="string"&&Array.isArray(n.shots)&&n.shots.every(o=>o&&typeof o=="object"&&typeof o.title=="string"&&typeof o.durationSeconds=="number")?t:null}function lg(e,t){return!e||!t?null:t.phase==="failed"||t.phase==="interrupted"?`${ht(e).text}${e.planVersion===1?" · start a new goal":" · open to retry"}`:t.phase==="planning"?e.brief||null:t.phase==="review"?`${ht(e).text}${t.stage==="frame"?"":Jt(e,t.stage)}`:t.phase==="complete"?`${e.assembly?"Added to the timeline":"Clip ready"} · ${gt(As(e.plan))}`:null}function ug(e,t){if(e.status==="completed")return 100;if(e.planVersion===3){const r=(e.stages.frame?.outputs.length?1:0)+(e.stages.videos?.outputs.length?1:0);return Math.round(r/2*100)}if(e.planVersion===1)return t.total>0?Math.round(t.done/t.total*100):0;const n=1+(pt(e.plan)&&e.plan.frameContinuity?3:2)*Ne(e.plan).length,o=Object.values(e.stages).reduce((r,i)=>r+i.outputs.length,0);return Math.round(o/n*100)}function M0(e,t,n){const o=e?.plan??t,r=e?Qe(e):null,i=r?.phase??null,s=r&&r.shots.length>0?r.shots:ng(o),a=s.length>Ar?s.slice(0,Ar-1):s,c=Ne(o),l=o&&"version"in o&&o.version===3?o:null,u=l?l.video.durationSeconds:c[0]?.durationSeconds??null,m=l||c.length>0&&c.every(f=>f.durationSeconds===u)?u:null,d=e?[...(e.stages.frame?.outputs??[]).map(f=>({...f,label:l?"Scene":"Full frame"})),...(e.stages.storyboards?.outputs??[]).map(f=>({...f,label:f.index>=c.length?`Ending ${f.index+1-c.length}`:`Storyboard ${f.index+1}`}))]:[];return{title:o?.title??(i==="planning"?"Building your shot plan":n??"Video goal"),planning:i==="planning",rows:a.map(f=>({key:`${f.index}`,number:f.number,title:f.title,state:f.state,detail:f.state==="generating"?"":f.state==="submitting"?"Queued":f.seconds>0&&(f.state==="done"||f.state==="planned")?f.state==="done"?gt(f.seconds):`${f.seconds}s`:eg(f.state),startedAt:f.state==="generating"?f.startedAt:null})),hiddenRows:s.length-a.length,note:lg(e,r),noteTone:i?Er[i].tone:"quiet",chip:e?.finish?.status==="running"?{label:"Finishing",tone:"live"}:i?Er[i]:{label:"Goal",tone:"quiet"},progressPercent:e&&r?ug(e,r):0,shotsLabel:o?m===null?`${c.length} clips`:l?`1 × ${m}s`:`${c.length} × ${m}s`:null,aspectRatio:o?.aspectRatio??null,thumbnails:d,styleLabel:pt(o)?Yt(o.style?.id??"cinematic").label:e?.requestedStyle?Yt(e.requestedStyle.id).label:null}}function Cr(e){const t=e?.startedAt??e?.enqueuedAt;return typeof t=="number"&&Number.isFinite(t)&&t>0?new Date(t).toISOString():void 0}function dg(e,t,n,o){if(!sc(e)||!t)return o;if(t.status==="ready")return{status:"completed"};const r=n.filter(a=>a.artifactId===t.artifactId),i=r.find(a=>a.state==="queued"||a.state==="running"||a.state==="completing"),s=r.find(a=>a.state==="failed"||a.state==="aborted");return t.status==="error"||!i&&s?{status:"error",error:s?.error?.message??o.error??"Media processing failed"}:{status:t.status,startedAt:Cr(i)??Cr(r[0])??t.createdAt}}function fg(e,t,n){const o=e.definition.source;if(!o)return null;const r=t.find(s=>s.id===o.cellId),i=n.get(o.snapshotArtifactId??"")??n.get(o.artifactId);return{address:r?ue(r.slot):null,...i?{asset:i}:{}}}function mg(e,t){return t?e.get(t):void 0}function pg(e,t){const n=h(e.execution),o=n&&h(n[t]),r=e.cells.find(i=>i.id===t);return o?b(o.error)?"error":b(o.status)??b(r?.inputs?.state)??"ready":b(r?.inputs?.state)??(r?.outputArtifactId?"completed":"ready")}function gg(e,t){const n=h(e.execution),o=n&&h(n[t]);return b(o?.startedAt)??b(o?.updatedAt)??void 0}function hg(e,t){const n=h(e.execution),o=n&&h(n[t]);return b(o?.error)??void 0}function Mr(e){const t=typeof e=="number"?e:typeof e=="string"&&e.trim()?Number(e):Number.NaN;return Number.isFinite(t)&&t>0?t:null}function bg(e,t,n){const o=e.cells.find(d=>d.id===t),r=b(o?.inputs?.producerCellId)??e.edges.find(d=>d.target===t&&d.targetInput==="media")?.source??null,i=r?e.cells.find(d=>d.id===r):void 0,s=i?.type==="generate_video"?h(i.inputs?.generationSettings):null,a=Yi(i?.model??"",i?.inputs?.generationMode),c=a?"adaptive":Ji(i?.model??"",i?.inputs??{})??b(o?.inputs?.aspectRatio??o?.inputs?.aspect_ratio)??b(s?.aspect_ratio),l=c&&c!=="adaptive"&&c!=="auto"?c:on(n?.width??null,n?.height??null),u=Mr(n?.duration),m=Mr(o?.inputs?.durationSeconds??o?.inputs?.duration_seconds??s?.duration??s?.duration_seconds);return{aspectRatio:l,durationSeconds:u??(a?null:m)}}function T0(e,t,n){const o=new Map(t.map(r=>[r.artifactId,r]));return Gp(e).map(r=>{const i=e.posts?.find(f=>f.id===r.id),s=i?fg(i,e.cells,o):null,a=yc(r.data.inputs),c=mg(o,r.data.outputArtifactId),l=r.data.kind==="video"?bg(e,r.id,c):null,u=gg(e,r.id),m=hg(e,r.id),d=dg(r.data.kind,c,n,{status:pg(e,r.id),...u?{startedAt:u}:{},...m?{error:m}:{}});return{...r,data:{...r.data,status:i?.runtime.status??d.status,...i?{post:i}:{},...s?{postSource:s}:{},...d.startedAt?{statusStartedAt:d.startedAt}:{},...d.error?{statusError:d.error}:{},asset:c,...l?.aspectRatio?{videoAspectRatio:l.aspectRatio}:{},...l?.durationSeconds?{videoDurationSeconds:l.durationSeconds}:{},...r.data.kind==="split_video"?{splitFrames:{first:{artifactId:a.first,...a.first&&o.has(a.first)?{asset:o.get(a.first)}:{}},last:{artifactId:a.last,...a.last&&o.has(a.last)?{asset:o.get(a.last)}:{}}}}:{}}}})}function Eo(e,t){return Object.is(e,t)?!0:JSON.stringify(e)===JSON.stringify(t)}function R0(e,t){const n=new Map(e.map(i=>[i.id,i])),o=t.map(i=>{const s=n.get(i.id);if(!s)return i;const a={...i,...s.selected!==void 0?{selected:s.selected}:{},...s.measured!==void 0?{measured:s.measured}:{},...s.dragging!==void 0?{dragging:s.dragging}:{},...s.dragging?{position:s.position}:{}};return Eo(a,s)?s:a});return o.length===e.length&&o.every((i,s)=>i===e[s])?e:o}function $0(e,t){const n=new Map(e.map(i=>[i.id,i])),o=t.map(i=>{const s=n.get(i.id);if(!s)return i;const a={...i,...s.selected!==void 0?{selected:s.selected}:{}};return Eo(a,s)?s:a});return o.length===e.length&&o.every((i,s)=>i===e[s])?e:o}const Pt=[],An=[];function En(e){return e?`${e.bookId}:${e.notebookId}`:""}function yg(e,t){return e.some(n=>n.goalId===t.goalId)?e.map(n=>n.goalId===t.goalId?t:n):[t,...e]}function N0(e,t){const n=ne.c(12);let o;n[0]===Symbol.for("react.memo_cache_sentinel")?(o={key:"",goals:Pt,events:An},n[0]=o):o=n[0];const[r,i]=_.useState(o),s=_.useRef(r),a=En(t),c=r.key===a?r.goals:Pt,l=r.key===a?r.events:An;let u;n[1]===Symbol.for("react.memo_cache_sentinel")?(u=(w,k,I)=>{const E=I===void 0?!1:I,C=s.current,A=C.key===w?C.goals:Pt,$=k.map(R=>{const D=A.find(z=>z.goalId===R.goalId);return D&&D.updatedAt>R.updatedAt?D:R});if(C.key===w&&Eo(C.goals,$))return;const T=$.flatMap(R=>{const D=A.find(q=>q.goalId===R.goalId),z=D?cg(D,R):E&&R.status==="review"?{from:"Plan ready"}:null;return z?[{kind:"status",sequence:Bt(),goalId:R.goalId,text:`Goal woke up · ${z.from} · ${ht(R).text}${R.address?` · ${R.address}`:""}`}]:[]}),N=[...C.key===w?C.events:An,...T].slice(-256),M={key:w,goals:$,events:N};s.current=M,i(M)},n[1]=u):u=n[1];const m=u;let d;n[2]===Symbol.for("react.memo_cache_sentinel")?(d=(w,k)=>{const I=Qp(k),E=En(w);m(E,I)},n[2]=d):d=n[2];const f=d;let g;n[3]!==e?(g=async w=>{f(w,await e("video_goal",{book_id:w.bookId,notebook_id:w.notebookId,action:"list"},{background:!0}))},n[3]=e,n[4]=g):g=n[4];const p=g;let y;n[5]!==e?(y=async(w,k,I)=>{const E=xs(await e("video_goal",{...k,book_id:w.bookId,notebook_id:w.notebookId},I?{chat:I}:{background:!0})),C=En(w),A=s.current;return(A.key===C||A.key==="")&&m(C,yg(A.key===C?A.goals:Pt,E),k.action==="create"),E},n[5]=e,n[6]=y):y=n[6];const v=y;let S;return n[7]!==v||n[8]!==l||n[9]!==c||n[10]!==p?(S={goals:c,events:l,accept:f,refresh:p,act:v},n[7]=v,n[8]=l,n[9]=c,n[10]=p,n[11]=S):S=n[11],S}const _g="Usage: /clip-audio @clip-id gain|mute|fade-in|fade-out <value>",vg=["gain","mute","fade-in","fade-out"];function kg(e){const[t,n,o,r]=e,i=n?.toLowerCase();if(!t||!i||o===void 0||r!==void 0||!Ig(i))return{ok:!1,message:_g};const s=o.trim();if(i==="gain"){const c=Number(s);return!Number.isFinite(c)||c<-96||c>24?{ok:!1,message:"Gain must be from -96 to 24 dB"}:{ok:!0,clipRef:t,edit:{field:i,gainDb:c}}}if(i==="mute"){const c=xg(s);return c===null?{ok:!1,message:"Mute must be on or off"}:{ok:!0,clipRef:t,edit:{field:i,muted:c}}}const a=Number(s);return!Number.isSafeInteger(a)||a<0?{ok:!1,message:"Fade length must be a whole number of frames"}:{ok:!0,clipRef:t,edit:{field:i,frames:a}}}function wg(e,t){if(!e)return{ok:!1,message:"Load the primary sequence first."};const n=ve(t),o=e.clips.filter(s=>s.clipId.toLowerCase().startsWith(n)),r=o.length===1?o[0]:void 0;return r?e.tracks.find(s=>s.trackId===r.trackId)?.kind!=="audio"?{ok:!1,message:"/clip-audio requires a clip on an audio track"}:{ok:!0,clipId:r.clipId,audio:{gainDb:r.audio?.gainDb??0,muted:r.audio?.muted??!1,fadeInFrames:r.audio?.fadeInFrames??0,fadeOutFrames:r.audio?.fadeOutFrames??0}}:{ok:!1,message:"Choose one audio clip from the current sequence"}}function Sg(e,t,n){return{kind:"volume",clip_id:e,gain_db:n.field==="gain"?n.gainDb:t.gainDb,...n.field==="mute"?{muted:n.muted}:{},...n.field==="fade-in"?{fade_in_frames:n.frames}:{},...n.field==="fade-out"?{fade_out_frames:n.frames}:{}}}function Ig(e){return vg.includes(e)}function xg(e){const t=e.toLowerCase();return t==="on"||t==="true"||t==="yes"?!0:t==="off"||t==="false"||t==="no"?!1:null}const Ag=new Set(["/caption","/move","/split-clip","/clip-delete","/gap","/fit","/reframe","/clip-reverse","/clip-audio","/duck","/insert","/overwrite","/clip-trim","/volume"]);function P0(e,t,n){if(e==="/delete"||e==="/trim"||e==="/reverse"){if(!he(n.sequence,t[0]))return{handled:!1}}else if(!Ag.has(e))return{handled:!1};const o=s=>({handled:!0,ok:!1,message:s}),r=s=>({handled:!0,ok:!0,request:s}),i=n.sequence;if(e==="/caption"){const[s,a,c,...l]=t,u=Number(s),m=Number(a),d=c?.toLowerCase(),f=d==="clean"||d==="bold"||d==="high-contrast"?d:null,g=l.join(" ").trim();return!Number.isSafeInteger(u)||u<0||!Number.isSafeInteger(m)||m<1||!f||!g?o("Usage: /caption <start-frame> <duration-frames> clean|bold|high-contrast <text>"):r({kind:"caption",timeline_start_frame:u,duration_frames:m,text:g,style_id:f})}if(e==="/move"){const[s,a,c]=t,l=he(i,s),u=Tr(i,a),m=Number(c);return!l||!u||!Number.isSafeInteger(m)||m<0?o("Usage: /move @clip-id @track-id <start-frame>"):r({kind:"move",clip_id:l.clipId,track_id:u.trackId,timeline_start_frame:m})}if(e==="/split-clip"){const[s,a]=t,c=he(i,s),l=Number(a);return!c||!Number.isSafeInteger(l)||l<0?o("Usage: /split-clip @clip-id <sequence-frame>"):r({kind:"split",clip_id:c.clipId,split_frame:l})}if(e==="/clip-delete"||e==="/delete"){const s=he(i,t[0]),a=t.slice(1).filter(c=>c!=="--ripple");return!s||a.length>0?o("Usage: /clip-delete @clip-id [--ripple]"):r({kind:"delete",clip_id:s.clipId,ripple:t.includes("--ripple")})}if(e==="/gap"){const s=Number(t[0]),a=Number(t[1]),c=Tr(i,t[2]);return!Number.isSafeInteger(s)||s<0||!Number.isSafeInteger(a)||a<1||t[2]!==void 0&&!c?o("Usage: /gap <start-frame> <duration-frames> [@track-id]"):r({kind:"gap",timeline_start_frame:s,duration_frames:a,...c?{track_ids:[c.trackId]}:{}})}if(e==="/fit"){const s=he(i,t[0]),a=t[1]?.toLowerCase();return!s||a!=="fit"&&a!=="fill"&&a!=="crop"?o("Usage: /fit @clip-id fit|fill|crop"):Ot(i,s)?.kind!=="video"?o("/fit requires a visual clip"):r({kind:"transform",clip_id:s.clipId,fit:a})}if(e==="/reframe"){const s=he(i,t[0]);return s?Ot(i,s)?.kind!=="video"?o("Automatic reframe requires a visual clip"):r({kind:"reframe",clip_id:s.clipId}):o("Usage: /reframe @visual-clip-id")}if(e==="/clip-reverse"||e==="/reverse"){const s=he(i,t[0]);return s?s.source.kind!=="timed"||!s.speed||s.reverse===void 0||!s.audioPolicy?o("/clip-reverse requires a timed clip"):r({kind:"speed",clip_id:s.clipId,numerator:s.speed.numerator,denominator:s.speed.denominator,reverse:!s.reverse,audio_policy:s.audioPolicy}):o("Usage: /clip-reverse @timed-clip-id")}if(e==="/clip-audio"){const s=kg(t);if(!s.ok)return o(s.message);const a=wg(i,s.clipRef);return a.ok?r(Sg(a.clipId,a.audio,s.edit)):o(a.message)}if(e==="/duck"){const s=he(i,t[0]),a=t[1]===void 0?-12:Number(t[1]);return!s||!Number.isFinite(a)||a<-36||a>-1?o("Usage: /duck @narration-clip-id [reduction-db from -36 to -1]"):Ot(i,s)?.kind!=="audio"?o("Ducking requires a narration clip on an audio track"):r({kind:"duck",narration_clip_id:s.clipId,reduction_db:a})}if(e==="/insert"||e==="/overwrite"||e==="/clip-trim"||e==="/trim"||e==="/volume"){const s=t.map(m=>m.startsWith("@")?m.slice(1):m);if(e==="/insert"||e==="/overwrite"){const[m,d,f]=s,p=n.mentionAssets.find(S=>S.cellAddress.toLowerCase()===m?.toLowerCase())??n.assets.find(S=>S.id===m||S.artifactId===m),y=Number(d),v=f===void 0?void 0:Number(f);return!p||!Number.isSafeInteger(y)||y<0||v!==void 0&&(!Number.isSafeInteger(v)||v<1)?o(`Usage: ${e} @asset <start-frame> [duration-frames]`):r({kind:"insert",mode:e==="/overwrite"?"overwrite":"insert",artifact_id:p.artifactId,timeline_start_frame:y,...v===void 0?{}:{duration_frames:v}})}if(e==="/clip-trim"||e==="/trim"){const[m,d,f]=s,g=he(i,m),p=Number(d),y=Number(f);return!g||!Number.isSafeInteger(p)||p<0||!Number.isSafeInteger(y)||y<1?o("Usage: /clip-trim @clip-id <start-frame> <duration-frames>"):r({kind:"trim",clip_id:g.clipId,timeline_start_frame:p,duration_frames:y})}const[a,c]=s,l=he(i,a),u=Number(c);return!l||!Number.isFinite(u)||u<-96||u>24?o("Usage: /volume @clip-id <gain-db from -96 to 24>"):Ot(i,l)?.kind!=="audio"?o("Volume changes require a clip on an audio track"):r({kind:"volume",clip_id:l.clipId,gain_db:u})}return{handled:!1}}function he(e,t){if(!e||!t)return;const n=ve(t),o=e.clips.filter(r=>r.clipId.toLowerCase().startsWith(n));return o.length===1?o[0]:void 0}function Tr(e,t){if(!e||!t)return;const n=ve(t),o=e.tracks.filter(r=>r.trackId.toLowerCase().startsWith(n)||r.name.toLowerCase()===n);return o.length===1?o[0]:void 0}function Ot(e,t){return e?.tracks.find(n=>n.trackId===t.trackId)}const Eg="Usage: /export-sequence --aspect 16:9|9:16|1:1 --captions burned|sidecar|omit";function O0(e,t){const n=e.findIndex(u=>u.toLowerCase()==="--aspect"),o=e.findIndex(u=>u.toLowerCase()==="--captions"),r=(n>=0?e[n+1]:"16:9")?.trim().toLowerCase(),i=(o>=0?e[o+1]:"burned")?.trim().toLowerCase(),s=r==="9:16"?"portrait":r==="1:1"?"square":r==="16:9"?"landscape":null,a=i==="burned"||i==="burn-in"?"burn-in":i==="sidecar"||i==="omit"?i:null,c=new Set;n>=0&&(c.add(n),c.add(n+1)),o>=0&&(c.add(o),c.add(o+1));const l=e.filter((u,m)=>!c.has(m));return!s||!a||l.some(u=>u!=="@sequence-main"&&u!==`@${t}`)?{ok:!1,message:Eg}:{ok:!0,orientation:s,captions:a}}const Cg="Usage: /track-add video|audio|caption [name]";function L0(e){const[t,...n]=e,o=t?.toLowerCase();return o!=="video"&&o!=="audio"&&o!=="caption"?{ok:!1,message:Cg}:{ok:!0,kind:o,name:n.join(" ")}}function F0(e,t){if(!t)return{ok:!1,message:"Open a project with a sequence first."};const n=Mg(t),o=e?.trim()??"";if(!o)return{ok:!0,initialFrame:n[0]?.timelineStartFrame??0};const r=Tg(o);if(r===null)return{ok:!1,message:"Usage: /play [@s01]"};const i=n[r];return i?{ok:!0,initialFrame:i.timelineStartFrame}:{ok:!1,message:"Choose an existing sequence slot."}}function Mg(e){const t=e.tracks.filter(n=>n.kind==="video").sort((n,o)=>n.ordinal-o.ordinal)[0];return t?e.clips.filter(n=>n.trackId===t.trackId).sort((n,o)=>n.timelineStartFrame-o.timelineStartFrame||n.clipId.localeCompare(o.clipId)):[]}function Tg(e){const t=/^@?(?:s)?(\d+)$/iu.exec(e.trim());if(!t)return null;const n=Number.parseInt(t[1]??"",10)-1;return n>=0?n:null}const Rr="Choose a timeline audio clip or the audio asset on the timeline";function D0(e,t,n,o){if(!t)return{ok:!1,message:"Load the primary sequence first."};const r=ve(e);if(!r)return{ok:!1,message:Rr};const i=new Set(t.tracks.filter(m=>m.kind==="audio").map(m=>m.trackId)),s=t.clips.filter(m=>i.has(m.trackId));if(!Kr(r)){const m=s.filter(d=>d.clipId.toLowerCase().startsWith(r));if(m.length===1)return{ok:!0,clipId:m[0].clipId};if(m.length>1)return{ok:!1,message:"Choose one timeline audio clip"}}const a=o.find(m=>m.cellAddress.toLowerCase()===r),c=n.find(m=>m.id.toLowerCase()===r||m.artifactId.toLowerCase()===r),l=a?.artifactId??c?.artifactId;if(!l)return{ok:!1,message:Rr};const u=s.filter(m=>m.source.artifactId===l);return u.length===1?{ok:!0,clipId:u[0].clipId}:u.length===0?{ok:!1,message:"That audio asset is not on the timeline"}:{ok:!1,message:"Choose one timeline audio clip"}}const Rg=["stack","punch","karaoke"],$g=["pop","slam","rise"],Ng=1,$r=j().regex(/^#[0-9a-fA-F]{6}$/),Pg=te({style:Xe(Rg),motion:Xe($g),energySizing:Te(),snapToOnsets:Te(),avoidFaces:Te(),avoidText:Te(),textColor:$r,hitColor:$r}).strict(),Og=te({kind:Xe(["face","text","graphic"]),confidence:V().min(0).max(1),x:V().min(0).max(1),y:V().min(0).max(1),width:V().positive().max(1),height:V().positive().max(1)}).strict(),Lg=te({text:j().min(1),transcriptStart:V().nonnegative(),transcriptEnd:V().nonnegative(),onsetStart:V().nonnegative(),energy:V().min(0).max(1)}).strict(),Fg=te({id:j().min(1),frameTime:V().nonnegative(),regions:ae(Og),lines:ae(ae(Lg).min(1)).min(1)}).strict(),Dg=te({version:Zr(Ng),fingerprint:j().min(1),analyzedAt:j().min(1),durationSeconds:V().nonnegative(),sourceWidth:V().positive(),sourceHeight:V().positive(),envelopeHz:V().positive(),envelope:ae(V().min(0).max(1)),onsets:ae(V().nonnegative()),regionsAnalyzed:Te(),phrases:ae(Fg)}).strict(),Vg=.8,jg=.5,Zt=.92,Xn=.06,Nr=.06,Gg=.5,qg=.18,Ug=.05,Lt=.02,Bg=.3;function Co(e,t){const n=t?e.onsetStart-e.transcriptStart:0,o=e.transcriptStart+n,r=Math.max(o+Ug,e.transcriptEnd+n);return{text:e.text,start:o,end:r,energy:e.energy}}function Hg(e){const{sourceWidth:t,sourceHeight:n,targetWidth:o,targetHeight:r}=e,i=Math.min(o/t,r/n),s=t*i,a=n*i;return{x:(o-s)/2,y:(r-a)/2,width:s,height:a}}function Wg(e,t){const n=Hg(t);return{x:(n.x+e.x*n.width)/t.targetWidth,y:(n.y+e.y*n.height)/t.targetHeight,width:e.width*n.width/t.targetWidth,height:e.height*n.height/t.targetHeight}}function Kg(e){return e.targetHeight>e.targetWidth?[{side:"center",x0:.07,x1:.93}]:[{side:"left",x0:.06,x1:.47},{side:"right",x0:.53,x1:.94}]}function zg(e){return{y0:.08,y1:e.targetHeight>e.targetWidth?.86:.92}}function Xg(e,t){return t.filter(n=>n.x-Lt<e.x1&&n.x+n.width+Lt>e.x0).map(n=>({y0:n.y-Lt,y1:n.y+n.height+Lt})).sort((n,o)=>n.y0-o.y0)}function Yg(e,t){const n=[];let o=e.y0;for(const r of t)if(r.y0>o&&n.push({y0:o,y1:Math.min(r.y0,e.y1)}),o=Math.max(o,r.y1),o>=e.y1)break;return o<e.y1&&n.push({y0:o,y1:e.y1}),n.filter(r=>r.y1-r.y0>0)}function Jg(e){return e.reduce((t,n)=>t===null||n.y1-n.y0>t.y1-t.y0?n:t,null)}function Zg(e){return e.reduce((t,n)=>t+(n.y1-n.y0),0)}function Qg(e,t,n){const o=Xg(e,n);return{candidate:e,span:Jg(Yg(t,o)),blocked:Zg(o)}}function Cn(e){return e.span?e.span.y1-e.span.y0:0}function Pr(e,t,n){return{side:e.side,x:e.x0*n.targetWidth,y:t.y0*n.targetHeight,width:(e.x1-e.x0)*n.targetWidth,height:(t.y1-t.y0)*n.targetHeight}}function eh(e,t){const n=zg(t),o=Kg(t).map(s=>Qg(s,n,e)),r=o.reduce((s,a)=>Cn(a)>Cn(s)+.02?a:s);if(r.span&&Cn(r)>=Bg)return Pr(r.candidate,r.span,t);const i=o.reduce((s,a)=>a.blocked<s.blocked?a:s);return Pr(i.candidate,n,t)}function th(e,t){return e.filter(n=>n.kind==="face"?t.avoidFaces:t.avoidText)}function nh(e){return e.map(t=>t.text).join(" ")}function oh(e){return Math.max(...e.map(t=>t.energy))}function Es(e,t,n){return Math.min(n,t/(Math.max(e.length,2)*jg))}function Cs(e){return e.reduce((n,o)=>n+o*(Zt+Xn),0)-(e.length>0?e[e.length-1]*Xn:0)}function rh(e){return e*Xn}function ih(e,t,n){const o=t.height*.36,r=e.map(a=>Es(nh(a),t.width,o)),i=n?r.map((a,c)=>a*(.7+.3*oh(e[c]))):r.map(()=>Math.min(...r)),s=Math.min(1,t.height/Cs(i));return e.map((a,c)=>({words:a,fontSize:Math.round(i[c]*s*10)/10}))}function sh(e,t,n){const o=n?.7+.3*e.energy:.85;return Math.min(Es(e.text,t.width,t.height*.6),t.height*.6)*o}function ah(e,t){const n=e.flat(),o=n[0].start-Nr,r=n[n.length-1].end+Gg,i=t===null?r:Math.min(r,t-Nr);return{start:o,end:Math.max(i,o+.1)}}function ch(e,t){return Co(e.lines[0][0],t).start}function V0(e,t,n){return e.map((o,r)=>{const i=o.lines.map(d=>d.map(f=>Co(f,t.snapToOnsets))),s=e[r+1],a=ah(i,s?ch(s,t.snapToOnsets):null),c=th(o.regions,t).map(d=>Wg(d,n)),l=eh(c,n),u=ih(i,l,t.energySizing),m=Cs(u.map(d=>d.fontSize));return{id:o.id,start:a.start,end:a.end,column:l,lines:u,blockTop:l.y+(l.height-m)/2}})}function lh(e,t){return e.find(n=>t>=n.start&&t<n.end)??null}function uh(e,t){return Mo((e.end-t)/qg)}function dh(e,t){return e.lines.flatMap(n=>n.words).filter(n=>n.start<=t).pop()??null}const fh={pop:{seconds:.14,apply:(e,t,n,o)=>({opacity:e,scale:1+(1-e)*.3*(.6+n),translateY:(1-e)*o*.12})},slam:{seconds:.09,apply:(e,t)=>({opacity:Mo(t*3),scale:1+(1-e)*.9,translateY:0})},rise:{seconds:.22,apply:(e,t,n,o)=>({opacity:e,scale:1,translateY:(1-e)*o*.35})}};function Mo(e){return e<0?0:e>1?1:e}function mh(e,t,n){const o=t>=e.start;return o&&t<e.end||o&&e.energy>=Vg?n.hitColor:n.textColor}function ph(e,t,n,o,r){const i=t-e.start,s=mh(e,t,n);if(n.style==="karaoke")return{opacity:(i<0?.3:1)*r,scale:1,translateY:0,color:s};if(i<0)return{opacity:0,scale:1,translateY:0,color:s};const a=fh[n.motion],c=Mo(i/a.seconds),l=1-Math.pow(1-c,3),u=n.energySizing?e.energy:.5,m=a.apply(l,c,u,o);return{...m,opacity:m.opacity*r,color:s}}const Or=[{id:"landscape",label:"16:9",width:1920,height:1080},{id:"portrait",label:"9:16",width:1080,height:1920},{id:"square",label:"1:1",width:1080,height:1080}],gh=.03;function j0(e){const t=e&&typeof e=="object"?e:{};return{analysis:Dg.parse(t.analysis),settings:Pg.parse(t.settings),cached:t.cached===!0}}function G0(e,t){return!e||!t?"landscape":t>e?"portrait":e===t?"square":"landscape"}function q0(e,t){const n=Or.find(o=>o.id===t)??Or[0];return{sourceWidth:e.sourceWidth,sourceHeight:e.sourceHeight,targetWidth:n.width,targetHeight:n.height}}function U0(e,t){return e.phrases.flatMap((n,o)=>n.lines.flat().map((r,i)=>{const s=Co(r,t.snapToOnsets),a=r.transcriptStart-r.onsetStart;return{key:`${n.id}-${i}`,phraseIndex:o,text:r.text,start:s.start,end:s.end,onset:r.onsetStart,driftMs:Math.round(a*1e3),drifted:Math.abs(a)>=gh}}))}function B0(e){const t=e.filter(n=>n.drifted).map(n=>Math.abs(n.driftMs));return{count:t.length,minMs:t.length>0?Math.min(...t):0,maxMs:t.length>0?Math.max(...t):0}}function H0(e,t){return e.findIndex(n=>t>=n.start&&t<n.end)}function W0(e){return e.column.side==="center"?"stack centered":`stack ${e.column.side}`}function K0(e){const t=Math.max(0,e),n=Math.floor(t/60),o=t-n*60,r=Math.floor(o),i=Math.floor((o-r)*100);return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}.${String(i).padStart(2,"0")}`}function z0(e){if(e.length===0)return"";const t=1e3/e.length;return`M0,100 L${e.map((o,r)=>`${(r*t).toFixed(1)},${(100-o*100).toFixed(1)}`).join(" L")} L1000,100 Z`}function X0(e){const t=e instanceof Error?e.message:String(e);try{const n=JSON.parse(t);return typeof n.message=="string"?n.message:t}catch{return t}}function Y0(e){return{style:e.style,motion:e.motion,energy_sizing:e.energySizing,snap_to_onsets:e.snapToOnsets,avoid_faces:e.avoidFaces,avoid_text:e.avoidText,text_color:e.textColor,hit_color:e.hitColor}}function J0(e,t){const n=e?t.find(o=>o.artifactId===e||o.id===e):void 0;return!e||!n?{ok:!1,message:"Usage: /alive @video"}:n.type!=="video"?{ok:!1,message:"/alive requires a video asset"}:n.status!=="ready"||!n.mediaUrl?{ok:!1,message:"Process the video before opening alive captions"}:{ok:!0,asset:n}}const Yn=["image","gen","video","audio","work"],hh={audio:"Audio",gen:"Gen",image:"Images",video:"Videos",work:"Work"},bh=["image","gen","video"];function Ms(e){const t=ii(e);return t==="data"||t==="goal"?"work":t}function Jn(e){return hh[e]}function yh(e){return e.map(Jn).join(" · ")}function _h(e,t){const n=new Set;for(const o of e)o.slot.row===t&&n.add(Ms(o.type));return Yn.filter(o=>n.has(o))}function vh(e,t,n,o){if(t.length===0){const r=o?bh[e]:void 0;return r?{caption:Jn(r),continuation:!1,families:[r],family:r,kind:"starter",row:e}:{caption:"",continuation:!1,families:[],family:null,kind:"empty",row:e}}if(t.length===1){const r=t[0],i=n.length===1&&n[0]===r;return{caption:Jn(r),continuation:i,families:t,family:r,kind:"homogeneous",row:e}}return{caption:yh(t),continuation:!1,families:t,family:null,kind:"mixed",row:e}}function Z0(e,t){const n=e.length===0,o=[];let r=[];for(let i=0;i<t;i+=1){const s=_h(e,i),a=vh(i,s,r,n);o.push(a),r=s}return o}function Q0(e){const t=[];for(const n of e){if(n.kind==="empty")continue;const o=t.at(-1);if(o&&n.kind==="homogeneous"&&o.kind==="homogeneous"&&o.family===n.family&&o.startRow+o.rowCount===n.row){t[t.length-1]={...o,rowCount:o.rowCount+1};continue}t.push({caption:n.caption,families:n.families,family:n.family,kind:n.kind,rowCount:1,startRow:n.row})}return t}function Mn(e,t){return e.slot.row-t.slot.row||e.slot.column-t.slot.column||e.id.localeCompare(t.id)}function kh(e,t={}){const n=e.cells.filter(p=>p.type==="goal").sort(Mn);if(n.length===0)return e;const o=new Set(n.flatMap(p=>Array.isArray(p.inputs?.characters)?p.inputs.characters.flatMap(y=>y&&typeof y=="object"&&"cellId"in y&&typeof y.cellId=="string"?[y.cellId]:[]):[])),r=new Set(e.edges.filter(p=>e.cells.some(y=>y.id===p.source&&y.type==="generate_image")).map(p=>p.target)),i=[...e.cells].sort((p,y)=>p.id.localeCompare(y.id)),s=e.cells.filter(p=>p.type==="image"&&(o.has(p.id)||!r.has(p.id)&&!p.inputs?.producerCellId&&!p.inputs?.mediaRole)).sort(Mn),a=new Set(s.map(p=>p.id)),c=i.filter(p=>p.type.startsWith("generate_")||p.type==="prompt"),l=i.filter(p=>p.type==="image"&&!a.has(p.id)),u=i.filter(p=>p.type==="video"),m=e.cells.filter(p=>p.type==="timeline").sort(Mn),d=new Map;let f=0;const g=(p,y=0,v=1)=>{p.forEach((S,w)=>d.set(S.id,{row:f+Math.floor(w/X),column:w%X})),f+=Math.max(v,Math.ceil((p.length+y)/X))};g(s,0,0),g([...n,...c],t.generators),g(l,t.images),g(u,t.videos);for(const p of m)d.set(p.id,{row:f,column:0}),f+=1;if(f+=t.timelines??0,g(i.filter(p=>!d.has(p.id)),0,0),f>de)throw new Error(`The goal layout needs ${f} rows, but the grid supports ${de}. Remove unused cells before continuing.`);return{...e,cells:e.cells.map(p=>({...p,slot:d.get(p.id)}))}}function Tn(e,t){return{ok:!1,code:e,message:t}}function wh(e){return[...e].sort((t,n)=>t.slot.row-n.slot.row||t.slot.column-n.slot.column||t.id.localeCompare(n.id))}function Sh(e){return e<=0?0:Math.ceil(e/X)}function eI(e){if(new Map(e.cells.map(c=>[c.id,c])).size!==e.cells.length)return Tn("invalid-edge","Cannot auto-arrange a notebook with duplicate cell IDs.");if(e.cells.some(c=>c.type==="goal"))try{const c=kh(e);return{ok:!0,rowCount:Math.max(...c.cells.map(l=>l.slot.row+1)),slots:c.cells.map(l=>({id:l.id,...l.slot}))}}catch(c){return Tn("capacity",c instanceof Error?c.message:String(c))}const n={audio:[],gen:[],image:[],video:[],work:[]},o=e.cells.filter(c=>c.type==="timeline"),r=new Set(o.map(c=>c.slot.row));for(const c of wh(e.cells))c.type!=="timeline"&&n[Ms(c.type)].push(c.id);const i=Yn.reduce((c,l)=>c+Sh(n[l].length),0);if(i+r.size>de)return Tn("capacity",`Cannot auto-arrange because the layout needs ${i} rows, but the grid supports ${de}.`);const s=o.map(c=>({id:c.id,...c.slot}));let a=0;for(const c of Yn){const l=n[c];if(l.length!==0)for(let u=0;u<l.length;u+=X){for(;r.has(a);)a+=1;for(const[m,d]of l.slice(u,u+X).entries())s.push({id:d,row:a,column:m});a+=1}}return{ok:!0,rowCount:Math.max(a,...o.map(c=>c.slot.row+1)),slots:s}}function tI(e,t=n=>window.requestAnimationFrame(n)){t(()=>{t(()=>{e()?.scrollTo({left:0,top:0,behavior:"smooth"})})})}function Rn(e){return`${e.row}:${e.column}`}function Lr(e){return[...e].sort((t,n)=>t.slot.row-n.slot.row||t.slot.column-n.slot.column)}function Ih(e,t,n){return t==="column"?{row:(e.row+n)%de,column:e.column}:{row:e.row,column:(e.column+n)%X}}function nI(e,t,n,o){const r=Lr(e.cells.filter(p=>t.has(p.id)));if(r.length===0)return{ok:!1,code:"no-videos",message:"No video cells in this notebook to arrange."};const i=o==="column"?de:X;if(r.length>i)return{ok:!1,code:"capacity",message:`Cannot arrange ${r.length} videos in one ${o}: the grid fits ${i}.`};const s=r.map((p,y)=>Ih(n,o,y)),a=new Set(s.map(Rn));if(e.cells.some(p=>p.type==="timeline"&&Ee(p).some(y=>a.has(Rn(y)))))return{ok:!1,code:"capacity",message:"Choose an arrangement that leaves the timeline row free."};const c=Lr(e.cells.filter(p=>!t.has(p.id)&&a.has(Rn(p.slot)))),l=new Set([...r.map(p=>p.id),...c.map(p=>p.id)]),u=[...e.cells.filter(p=>!l.has(p.id)).flatMap(Ee),...s],m=Jr(u,c.length),d=[...r.map((p,y)=>({id:p.id,...s[y]})),...c.map((p,y)=>({id:p.id,...m[y]}))],f=new Map(e.cells.map(p=>[p.id,p.slot])),g=d.filter(p=>{const y=f.get(p.id);return y?.row!==p.row||y?.column!==p.column}).length;return{ok:!0,slots:d,movedCount:g,displacedCount:c.length}}function Fr(e){return[...e].sort((t,n)=>t.slot.row-n.slot.row||t.slot.column-n.slot.column)}function xh(e,t){const n=(e.row*X+e.column+t)%qt;return{row:Math.floor(n/X),column:n%X}}function Ah(e){return qt-new Set(e.map(_e)).size}function oI(e,t,n){const o=Fr(e.cells.filter(f=>t.has(f.id)));if(o.length===0)return{ok:!1,code:"no-images",message:"No image cells in this notebook to group."};if(o.length>qt)return{ok:!1,code:"capacity",message:`Cannot group ${o.length} images: the grid fits ${qt}.`};const r=o.map((f,g)=>xh(n,g)),i=new Set(r.map(_e));if(e.cells.some(f=>f.type==="timeline"&&Ee(f).some(g=>i.has(_e(g)))))return{ok:!1,code:"capacity",message:"Choose an arrangement that leaves the timeline row free."};const s=Fr(e.cells.filter(f=>!t.has(f.id)&&i.has(_e(f.slot)))),a=new Set([...o.map(f=>f.id),...s.map(f=>f.id)]),c=[...e.cells.filter(f=>!a.has(f.id)).flatMap(Ee),...r];if(s.length>Ah(c))return{ok:!1,code:"grid-full",message:Ks};const l=Jr(c,s.length),u=[...o.map((f,g)=>({id:f.id,...r[g]})),...s.map((f,g)=>({id:f.id,...l[g]}))],m=new Map(e.cells.map(f=>[f.id,f.slot])),d=u.filter(f=>{const g=m.get(f.id);return g?.row!==f.row||g?.column!==f.column}).length;return{ok:!0,slots:u,movedCount:d,displacedCount:s.length}}function Eh(e,t){return`Generation was interrupted (${e?.trim()||`Notebook run ${t}`}). Clear the slot to reset the cell, then generate again.`}function rI(e){const t=e.jobs.filter(n=>{if(n.type!=="await_notebook_output")return!1;const o=n.payload;return o?o.cellId===e.cellId&&o.runId===e.runId:!1});return t.length>0?t.reduce((o,r)=>{const i=o.operationId??"";return(r.operationId??"")>i?r:o}):e.jobs.find(n=>n.operationId===e.jobOperationId)??null}function iI(e){return e.observation.state==="error"?{kind:"failed",message:e.observation.error??`@${e.address} failed`}:e.observation.state==="completed"?{kind:"completed"}:e.observation.state==="pending"&&e.sawRun?{kind:"superseded"}:e.job?.state==="failed"||e.job?.state==="aborted"?{kind:"failed",message:Eh(e.job.errorMessage,e.job.state)}:{kind:"continue",sawRun:e.sawRun||e.observation.state==="active"}}function sI(e){return{state:e.state,errorMessage:e.error?.message??null,operationId:e.operationId,type:e.type,startedAt:e.startedAt??null,payload:e.payload??null,...typeof e.id=="number"?{id:e.id}:{}}}function aI(e,t,n){const o=h(e),r=x(o?.artifact_id);if(!r)throw new Error("The download did not return an artifact for the board");const i=x(o?.job_id);return{type:"video",slot:n,inputs:{sourceOperation:"download_video",sourceUrl:t,...i?{jobId:i}:{}},output_artifact_id:r}}const Ch=new Set(["download_video","process_image","process_video","process_audio","process_upload","complete_kie_task","generate_media"]);function cI(e,t,n,o){const r=n.find(c=>c.artifactId===e&&c.type==="download_video"&&c.state==="done"),i=h(r?.result),s=i?.retyped===!0?x(i.assetId??i.artifact_id):null;if(s&&s!==e)return{kind:"redirected",artifactId:s};if(t?.status==="ready")return{kind:"completed"};const a=n.find(c=>c.artifactId===e&&(c.state==="failed"||c.state==="aborted")&&Ch.has(c.type));return t?.status==="error"||a?{kind:"failed",message:a?.error?.message??x(o)??"Media processing failed"}:{kind:"continue"}}function fn(e,t){return Object.fromEntries(t.flatMap(n=>e[n]===void 0?[]:[[n,e[n]]]))}function bt(e,t,n){const o=x(e[t]);if(!o)throw new Error(n);return o}function Mh(e){return{type:"video",artifactId:bt(e,"output_artifact_id","The extracted clip did not return an artifact for the notebook"),inputs:{sourceOperation:"extract_video_clip",...fn(e,["source_asset_id","start_time","end_time","duration","job_id"])}}}function Th(e){const t=fn(e,["source_asset_id","chunk_a_end","chunk_b_start","overlap_sec","job_id"]);return[{type:"video",artifactId:bt(e,"chunk_a_artifact_id","The first split clip did not return an artifact for the notebook"),inputs:{sourceOperation:"split_video",splitOutput:"first",...t}},{type:"video",artifactId:bt(e,"chunk_b_artifact_id","The remaining split clip did not return an artifact for the notebook"),inputs:{sourceOperation:"split_video",splitOutput:"remaining",...t}}]}function Rh(e){return{type:"audio",artifactId:bt(e,"audio_asset_id","The cover song did not return an audio artifact for the notebook"),inputs:{sourceOperation:"make_cover_song",...fn(e,["source_asset_id","source_kind","duration_seconds","job_id"])}}}function Ts(e){const t=e.additional_asset_ids??e.additional;return Array.isArray(t)?t.flatMap(n=>{const o=x(n);return o?[o]:[]}):[]}function $h(e,t){const n=x(t.first_asset_id)??x(t.first),o=x(t.second_asset_id)??x(t.second);if(!n||!o)throw new Error(`${e} did not return both source artifacts for the notebook`);const r=Ts(t);return{type:"video",artifactId:bt(t,"asset_id",`${e} did not return an artifact for the notebook`),inputs:{sourceOperation:e,first_asset_id:n,second_asset_id:o,...r.length>0?{additional_asset_ids:r}:{},...fn(t,["overlap","transition_seconds","alignment_mode","job_id"])}}}function Nh(e,t,n){const o=x(e.source_asset_id),r=o?t.find(i=>!Ve(i)&&i.outputArtifactId===o):void 0;return an(t,r?[r.slot]:[],n)}function Ph(e,t,n,o){const r=new Set([x(e.source_asset_id),x(e.first_asset_id)??x(e.first),x(e.second_asset_id)??x(e.second),...Ts(e)].filter(c=>c!==null)),i=t.filter(c=>c.outputArtifactId&&r.has(c.outputArtifactId)&&!Ve(c)).map(c=>c.slot),s=[...t],a=[];for(let c=0;c<n;c+=1){const l=uo(s,i,o);a.push(l),s.push({type:"video",slot:l})}return a}function lI(e,t,n,o=null){if(e!=="extract_video_clip"&&e!=="split_video"&&e!=="make_cover_song"&&e!=="splice_video"&&e!=="smooth_scene_concat")return[];const r=h(t);if(!r)throw new Error(`${e} returned an invalid result`);const s=(e==="extract_video_clip"?[Mh(r)]:e==="split_video"?Th(r):e==="make_cover_song"?[Rh(r)]:[$h(e,r)]).filter(c=>!n.some(l=>!Ve(l)&&l.outputArtifactId===c.artifactId));if(s.length===0)return[];const a=e==="make_cover_song"?[Nh(r,n,o)]:Ph(r,n,s.length,o);return s.map((c,l)=>({type:c.type,slot:a[l],inputs:c.inputs,output_artifact_id:c.artifactId}))}function Oh(e,t){const n=new Set(e.edges.filter(o=>o.source===t&&(o.targetInput==="video"||o.targetInput==="segment")).map(o=>o.target));return e.cells.find(o=>n.has(o.id)&&(o.type==="extract_audio"||o.inputs?.mediaRole==="extract-audio-output"))??null}function Lh(e,t){const n=h(e.execution),o=n?h(n[t]):null,r=x(o?.status),i=x(o?.runId);return r&&i&&nn(r)?i:null}function Dr(e){const t=h(e),n=x(t?.job_id),o=x(t?.run_id);if(!n||!o)throw new Error("The server did not return an Extract Audio run");return{jobId:n,runId:o}}async function uI(e){const t=wo(e.document,e.command.sourceReference),n=t.id,o=Z(t),r=e.expectedRevision?{expected_revision:e.expectedRevision}:{},i=Oh(e.document,t.id);if(i){const l={actionCellId:i.id,actionAddress:Z(i),outputCellId:i.id,reusedAction:!0,sourceCellId:n,sourceAddress:o},u=Lh(e.document,i.id);if(u)return{...l,jobId:"",runId:u};const m=Dr(await e.callTool("run_notebook_cell",{book_id:e.bookId,notebook_id:e.document.id,cell_id:i.id,actor:e.actor,...r}));return{...l,...m}}const s=h(await e.callTool("extract_notebook_audio",{book_id:e.bookId,notebook_id:e.document.id,source_cell_id:t.id,label:"Extract audio",...r})),a=x(s?.cell_id),c=x(s?.address);if(!a||!c)throw new Error("The server did not return an Extract Audio run");return{actionCellId:a,actionAddress:c,outputCellId:a,...Dr(s),reusedAction:!1,sourceCellId:n,sourceAddress:o}}function Fh(e){const t=Number(e);return Number.isFinite(t)&&t>=0?Math.round(t*1e3)/1e3:null}async function dI(e){const t=e.command.frameMode==="time"?Fh(e.command.timestampSeconds):null;if(e.command.frameMode==="time"&&t===null)throw new Error("A valid timestamp is required for time-mode frame extraction");const n=wo(e.document,e.command.sourceReference),o=h(await e.callTool("extract_notebook_frame",{book_id:e.bookId,notebook_id:e.document.id,source_cell_id:n.id,frame_mode:e.command.frameMode,...t===null?{}:{timestamp_seconds:t},...e.expectedRevision?{expected_revision:e.expectedRevision}:{}})),r=x(o?.cell_id),i=x(o?.address),s=x(o?.job_id),a=x(o?.run_id);if(!r||!i||!s||!a)throw new Error("The server did not return the frame extraction cell");return{actionCellId:r,actionAddress:i,outputCellId:r,jobId:s,runId:a,reusedAction:!1,sourceCellId:n.id,sourceAddress:Z(n)}}const Vr="2026-07-28",Dh=21*6e4;function Vh(e){return e==="apply_watermark"?Dh:void 0}async function Rs(e,t){const n=new zs({name:t,version:"0.1.0"},{capabilities:{},supportedProtocolVersions:[Vr],versionNegotiation:{mode:{pin:Vr}}});try{return await n.connect(new Xs(new URL(e))),n}catch(o){throw await n.close(),o}}function jh(e,t,n){const o=Vh(t);return e.callTool({name:t,arguments:n},o===void 0?void 0:{timeout:o})}function Gh(e,t){if(t){const n=e.find(o=>o.bookId===t);if(n)return n}return e.find(n=>typeof n.bookId=="string"&&n.bookId.length>0)??null}function qh(e){const t=h(e);if(!t||t.isError)throw new Error("Bootstrap tool failed");const n=t.content?.find(o=>o.type==="text")?.text;if(!n)return null;try{return JSON.parse(n)}catch{return n}}async function Se(e,t,n){return qh(await e.callTool({name:t,arguments:n}))}function jr(e){try{return window.localStorage.getItem(e)??""}catch{return""}}async function Uh(e){const[t,n,o]=await Promise.all([Se(e,"list_books",{sort:"newest"}),Se(e,"slash_commands",{detail:"full"}),Se(e,"list_chat_models",{})]),r=Array.isArray(t)?t:[],i=Gh(r.map(h).filter(v=>v!==null),jr("videobook.active-book")),s=typeof i?.bookId=="string"?i.bookId:"";if(!s)return{bookValue:t,commandValue:n,chatModelValue:o,bookId:"",notebookId:"",notebookValue:[],assetValue:[],sequenceValue:null,jobValue:[],ingestStatusValue:[],actionValue:[]};const[a,c,l,u,m,d]=await Promise.all([Se(e,"list_notebooks",{book_id:s}),Se(e,"list_assets",{book_id:s,sort:"newest",limit:200,include_referenced:!0}),Se(e,"get_primary_sequence",{book_id:s}),Se(e,"list_jobs",{book_id:s,limit:200}),Se(e,"list_ingest_status",{book_id:s,limit:200}),Se(e,"list_notebook_actions",{book_id:s})]),f=Array.isArray(a)?a.map(h).filter(v=>v!==null):[],g=jr(`videobook.active-notebook:${s}`),p=f.find(v=>v.id===g)??f[0],y=typeof p?.id=="string"?p.id:"";return{bookValue:t,commandValue:n,chatModelValue:o,bookId:s,notebookValue:a,notebookId:y,assetValue:c,sequenceValue:l,jobValue:u,ingestStatusValue:m,actionValue:d}}async function fI(){const e=new URL("/mcp",window.location.origin).toString(),t=await Rs(e,"videobook-bootstrap");try{return await Uh(t)}finally{await t.close()}}const Zn="gpt-6-astra",Bh={defaultModel:"gpt-6-astra",models:[{id:Zn,label:"Astra",description:"Routes every composer request and configures its tools"}]};function Hh(e){const t=h(e),n=Array.isArray(t?.models)?t.models.flatMap(i=>{const s=h(i);return typeof s?.id=="string"&&typeof s.label=="string"&&typeof s.description=="string"&&s.id===Zn?[{id:s.id,label:s.label,description:s.description}]:[]}):[],o=Zn,r=n.some(i=>i.id===o)?o:n[0]?.id;return r?{defaultModel:r,models:n}:Bh}function mI(e,t){return e.models.some(n=>n.id===t)?t:e.defaultModel}function Gr(e){return e instanceof Error?e:new Error(String(e))}function Wh({callTool:e,cancelTimer:t,connect:n,onStateChange:o,reconnectDelayMs:r,scheduleTimer:i}){let s=!1,a=null,c=0,l=null;const u=v=>{v.onclose=void 0,v.close().catch(()=>{})},m=()=>{l!==null&&(t(l),l=null)},d=async()=>{if(!s)return;const v=++c;o({state:"connecting",error:null});try{const S=await n();if(!s||v!==c){S!==a&&u(S);return}a=S,S.onclose=()=>{!s||a!==S||(S.onclose=void 0,a=null,o({state:"failed",error:new Error("MCP connection closed")}),f())},o({state:"ready",error:null})}catch(S){if(!s||v!==c)return;o({state:"failed",error:Gr(S)}),f()}},f=()=>{!s||l!==null||(l=i(()=>{l=null,d()},r))};return{callTool:async(v,S)=>{const w=a;if(!s||!w)throw new Error("MCP server is not ready");try{return await e(w,v,S)}catch(k){const I=Gr(k);throw s&&a===w&&(a=null,u(w),o({state:"failed",error:I}),f()),I}},start:()=>{s||(s=!0,d())},stop:()=>{if(!s)return;s=!1,c+=1,m();const v=a;a=null,v&&u(v)}}}function pI(e){const t=ne.c(9),{url:n,clientName:o,reconnectDelayMs:r}=e,i=_.useRef(null),[s,a]=_.useState("connecting"),[c,l]=_.useState(null);let u,m;t[0]!==o||t[1]!==r||t[2]!==n?(u=()=>{const p=Wh({connect:()=>Rs(n,o),callTool:jh,reconnectDelayMs:r,scheduleTimer:zh,cancelTimer:Kh,onStateChange:y=>{a(y.state),l(y.error)}});return i.current=p,p.start(),()=>{i.current===p&&(i.current=null),p.stop()}},m=[o,r,n],t[0]=o,t[1]=r,t[2]=n,t[3]=u,t[4]=m):(u=t[3],m=t[4]),_.useEffect(u,m);let d;t[5]===Symbol.for("react.memo_cache_sentinel")?(d=async(p,y)=>{const v=i.current;if(!v)throw new Error("MCP server is not ready");return v.callTool(p,y)},t[5]=d):d=t[5];const f=d;let g;return t[6]!==c||t[7]!==s?(g={state:s,error:c,callTool:f},t[6]=c,t[7]=s,t[8]=g):g=t[8],g}function Kh(e){return window.clearTimeout(e)}function zh(e,t){return window.setTimeout(e,t)}function gI({bookId:e,notebookId:t,enabled:n,refresh:o}){const r=_.useEffectEvent(o);_.useEffect(()=>{if(!n||!e||!t)return;let i=!0,s=!1,a=!1,c=0;const l=async()=>{if(window.clearTimeout(c),!(!i||document.visibilityState==="hidden")){if(s){a=!0;return}s=!0;try{await r(()=>i)}catch{a=!1}finally{s=!1,i&&(c=window.setTimeout(l,a?0:2e3)),a=!1}}},u=()=>{l()};return c=window.setTimeout(l,0),window.addEventListener("focus",u),document.addEventListener("visibilitychange",u),()=>{i=!1,window.clearTimeout(c),window.removeEventListener("focus",u),document.removeEventListener("visibilitychange",u)}},[e,n,t])}function Ie(e,t){return{kind:"refused",outcome:{status:e,message:t}}}function se(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu," ").trim()}function Xh(e){return e.map(t=>t.title).join(", ")}function $s(e){return e.length>0?e.map(t=>t.label).join(", "):"no settings"}function Qn(e){return e.options.map(String).join(", ")}function Yh(e,t){const n=se(e);if(!n)return null;const o=t.find(i=>se(i.name)===n||se(i.label)===n);if(o)return o;const r=t.filter(i=>se(i.label).includes(n)||se(i.name).includes(n));return r.length===1?r[0]:null}function Jh(e){if(typeof e=="boolean")return e;const t=se(String(e));return["true","on","yes","enable","enabled"].includes(t)?!0:["false","off","no","disable","disabled"].includes(t)?!1:null}function Zh(e){return typeof e=="string"&&["default","auto","automatic"].includes(se(e))}function Qh(e,t){const n=typeof t=="number"?t:Number(String(t).trim());return typeof t=="boolean"||!Number.isFinite(n)?{error:`${e.label} takes a number, not "${String(t)}".`}:e.minimum!==void 0&&(e.exclusiveMinimum?n<=e.minimum:n<e.minimum)?{error:e.exclusiveMinimum?`${e.label} must be greater than ${e.minimum}.`:`${e.label} does not go below ${e.minimum}.`}:e.maximum!==void 0&&(e.exclusiveMaximum?n>=e.maximum:n>e.maximum)?{error:e.exclusiveMaximum?`${e.label} must be less than ${e.maximum}.`:`${e.label} does not go above ${e.maximum}.`}:e.options.length>0&&!e.options.includes(n)?{error:`${e.label} does not take ${n}. It takes ${Qn(e)}.`}:{kind:"setting",name:e.name,value:n}}function eb(e,t,n){const o=Yh(e,n);if(!o)return{error:`This review has no "${e}" setting. It has ${$s(n)}.`};if(Zh(t))return o.required?{error:`${o.label} has no default. It takes ${Qn(o)}.`}:{kind:"setting",name:o.name,value:void 0};if(o.valueType==="boolean"){const s=Jh(t);return s===null?{error:`${o.label} is on or off, not "${String(t)}".`}:{kind:"setting",name:o.name,value:s}}if(o.valueType==="number")return Qh(o,t);const r=String(t).trim(),i=o.options.find(s=>se(String(s))===se(r));return o.options.length>0&&i===void 0?{error:`${o.label} does not take "${r}". It takes ${Qn(o)}.`}:{kind:"setting",name:o.name,value:i??r}}function tb(e,t){const n=se(e),o=t.find(r=>se(r.id)===n)??t.find(r=>se(r.title)===n)??t.find(r=>se(r.title).includes(n));return o?{kind:"model",actionId:o.id}:{error:`This review has no "${e}" model. It offers ${Xh(t)}.`}}function hI(e,t){if(t.kind==="none")return Ie("failed","There is no review on screen to act on.");if(e.decision==="cancel")return{kind:"command",input:"/cancel"};const n=e.prompt?.trim(),o=Object.entries(e.settings??{}),r=e.model?.trim();if(e.decision==="apply")return r||o.length>0?Ie("review","Revise the model and settings first, then apply. Apply only takes a new prompt."):n&&t.kind==="chain-step"?Ie("review","A chain step can't be rewritten. Apply it as it stands, or cancel the chain."):n&&t.kind!=="generation"?Ie("review","Only a generation review takes a new prompt. Apply this one as it stands, or cancel it."):{kind:"command",input:n?`/apply ${n}`:"/apply"};if(t.kind==="chain-step")return Ie("review","A chain step can't be revised. Apply it, or cancel to stop the whole chain.");if(t.kind!=="generation")return Ie("review","Only a generation review has a prompt, a model and settings to revise.");if(!n&&!r&&o.length===0)return Ie("review",`Say what to change: the prompt, the model, or one of ${$s(t.action.controls)}.`);const i=[];if(r){const c=tb(r,t.models);if("error"in c)return Ie("review",c.error);i.push(c)}n&&i.push({kind:"prompt",prompt:n});const s=i.find(c=>c.kind==="model"),a=s?t.models.find(c=>c.id===s.actionId)?.controls??[]:t.action.controls;for(const[c,l]of o){const u=eb(c,l,a);if("error"in u)return Ie("review",u.error);i.push(u)}return{kind:"revise",edits:i}}const bI={target:null,sources:[]};function yI(e){const t=new Map;for(const n of e.sources)n&&t.set(n,"source");return e.target&&t.set(e.target,"target"),t}function nb(e){if(!Number.isFinite(e.row)||e.row<0)return 0;const t=Number.isFinite(e.zoom)&&e.zoom>0?e.zoom:1,n=O.originY+e.row*O.rowPitch+O.squareSize/2,o=Math.max(0,e.scrollHeight-e.clientHeight),r=n*t-e.clientHeight/2;return Math.min(o,Math.max(0,Math.round(r)))}const ob=2;function _I(e,t,n={}){(n.scheduleFrame??(r=>window.requestAnimationFrame(r)))(()=>{const r=e();if(!r)return;const i=nb({...t,clientHeight:r.clientHeight,scrollHeight:r.scrollHeight});Math.abs(i-r.scrollTop)<=ob||r.scrollTo({top:i,behavior:n.reducedMotion?"auto":"smooth"})})}function vI(e,t){return t.some(n=>{const o=Xr(n.address);return o?(Zi(e,o)?.id??null)!==n.cellId:!0})}const qr=["#65e6a5","#ffbd5c","#69b7ff","#ff7f9c","#c58cff","#50d7dc","#f38d58","#d2e466"];function ce(e){return typeof e=="string"&&e.length>0?e:null}function re(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Ur(e,t){return typeof e=="boolean"?e:t}function be(e){const t=e>1?e/1e3:e;return Math.min(1,Math.max(0,t))}function rb(e){if(Array.isArray(e)&&e.length>=4){const d=re(e[0]),f=re(e[1]),g=re(e[2]),p=re(e[3]);if(d===null||f===null||g===null||p===null)return null;const y=be(d),v=be(f);return{x:y,y:v,width:Math.max(0,be(g)-y),height:Math.max(0,be(p)-v)}}const t=h(e);if(!t)return null;const n=re(t.x??t.left??t.x1),o=re(t.y??t.top??t.y1),r=re(t.width),i=re(t.height),s=re(t.right??t.x2),a=re(t.bottom??t.y2);if(n===null||o===null)return null;const c=be(n),l=be(o),u=r===null?s===null?null:be(s)-c:be(r),m=i===null?a===null?null:be(a)-l:be(i);return u===null||m===null?null:{x:c,y:l,width:Math.max(0,Math.min(1-c,u)),height:Math.max(0,Math.min(1-l,m))}}function ib(e,t){let n=t;for(const o of e)n=(n<<5)-n+o.charCodeAt(0)|0;return qr[Math.abs(n)%qr.length]}function sb(e,t){const n=h(e);if(!n)return null;const o=ce(n.id??n.subject_id??n.region_id)??(re(n.index)===null?null:`subject-${re(n.index)}`);if(!o)return null;const r=h(n.capabilities),i=h(n.bounding_box??n.boundingBox);return{id:o,label:ce(n.label??n.name)??`Subject ${t+1}`,description:ce(n.description),color:ce(n.color)??ib(o,t),box:rb(n.normalized_box??n.normalizedBox??i?.normalized??n.box),layerUrl:ce(n.layer_url??n.layerUrl??n.mask_url??n.maskUrl??n.url),thumbnailUrl:ce(n.thumbnail_url??n.thumbnailUrl),zIndex:re(n.z_index??n.zIndex)??t+1,removable:Ur(r?.remove??n.removable,!0),exactEdit:Ur(r?.exact_edit??r?.exactEdit??n.exact_edit,!1)}}function ab(e,t){return e==="idle"||e==="analyzing"||e==="ready"||e==="failed"?e:t}function kI(e){const t=h(e),o=h(t?.subject_map??t?.subjectMap??t?.map)??t,i=(Array.isArray(o?.subjects)?o.subjects:Array.isArray(o?.regions)?o.regions:Array.isArray(o?.layers)?o.layers:[]).flatMap((c,l)=>{const u=sb(c,l);return u?[u]:[]}).sort((c,l)=>c.zIndex-l.zIndex),s=ce(o?.error??t?.error),a=s?"failed":i.length>0?"ready":"idle";return{status:ab(o?.status??t?.status,a),artifactId:ce(o?.artifact_id??o?.artifactId??t?.artifact_id??t?.artifactId),objectHash:ce(o?.object_hash??o?.objectHash??t?.object_hash??t?.objectHash),width:re(o?.width??t?.width),height:re(o?.height??t?.height),baseUrl:ce(o?.base_url??o?.baseUrl??t?.base_url??t?.baseUrl),jobId:ce(o?.job_id??o?.jobId??t?.job_id??t?.jobId),startedAt:ce(o?.started_at??o?.startedAt??t?.started_at??t?.startedAt),error:s,subjects:i}}async function cb(e,t){if(!t())return{kind:"stale"};try{const n=await e();return t()?{kind:"current",value:n}:{kind:"stale"}}catch(n){return t()?{kind:"error",error:n}:{kind:"stale"}}}const lb=3e3,ub=27*6e4;function db(e){return new Promise(t=>window.setTimeout(t,e))}function fb(e,t){if(!e)return t;const n=Date.parse(e);return Number.isFinite(n)?n:t}async function wI({initialMap:e,read:t,publish:n,isCurrent:o,now:r=Date.now,wait:i=db,intervalMs:s=lb,timeoutMs:a=ub}){if(!o())return{kind:"stale"};if(e.status!=="analyzing")return{kind:"terminal",map:e};let c=e;const l=fb(e.startedAt,r())+a;for(;o();){const u=l-r();if(u<=0)return{kind:"timeout",map:c};if(await i(Math.min(s,u)),!o())return{kind:"stale"};if(r()>=l)return{kind:"timeout",map:c};const m=await cb(t,o);if(m.kind==="stale")return m;if(m.kind==="error")return{kind:"error",map:c,error:m.error};if(c=m.value,n(c),c.status!=="analyzing")return{kind:"terminal",map:c}}return{kind:"stale"}}const mb={transcript:["transcribe","transcribe_video_audio"],analysis:["analyze_video"]};function pb(e){return e==="transcript"?"Transcription failed":"Video analysis failed"}function SI(e){const t=e.jobs.filter(o=>o.artifactId===e.artifactId&&mb[e.insight].includes(o.type)&&o.enqueuedAt>=e.since),n=t.find(o=>o.state==="failed"||o.state==="aborted");return n?{kind:"failed",message:n.error?.message??pb(e.insight)}:t.some(o=>o.state==="done")?{kind:"ready"}:e.hasInsight&&!e.hadInsight?{kind:"ready"}:{kind:"continue"}}const gb=new Set(["audio","image","video","extract_audio","split_video","prompt","character","analyze","analysis","generate_video","generate_image","generate_audio","concat","splice","timeline","goal","post"]);function II(e){if(!Array.isArray(e))throw new Error("The server returned invalid asset history");return e.map(t=>{const n=h(t),o=n&&b(n.hash),r=n&&b(n.message),i=n&&b(n.date);if(!n||!o||r===null||!i)throw new Error("The server returned an invalid asset revision");return{hash:o,message:r,date:i,...b(n.author)?{author:b(n.author)}:{},...b(n.operation)?{operation:b(n.operation)}:{}}})}function hb(e){return e.content?.find(n=>n.type==="text")?.text??null}function xI(e){const t=e,n=hb(e);if(t.isError)throw new Error(n??"MCP tool failed");if(!n)return null;try{return JSON.parse(n)}catch{return n}}function AI(e,t){if(typeof e=="string")return e;const n=h(e);if(!n)return t;for(const o of["message","job_id","notebook_id","address","bookId"]){const r=b(n[o]);if(r)return`${t}: ${r}`}return t}function bb(e){const t=h(e),n=b(t?.stepId),o=b(t?.tool),r=b(t?.title),i=b(t?.reason);return!n||!o||!r||!i?null:{stepId:n,index:typeof t?.index=="number"?t.index:0,total:typeof t?.total=="number"?t.total:1,tool:o,title:r,address:b(t?.address),params:h(t?.params)??{},estimateUsd:typeof t?.estimateUsd=="number"?t.estimateUsd:null,estimateUnavailable:t?.estimateUnavailable!==!1,reason:i}}function EI(e){const t=h(e),n=b(t?.chain_id),o=b(t?.status);if(b(t?.kind)!=="chain-run"||!n||!o)return null;const r=Array.isArray(t?.steps)?t.steps.flatMap(i=>{const s=h(i),a=b(s?.id),c=b(s?.tool),l=b(s?.status);return!a||!c||!l?[]:[{id:a,tool:c,status:l,error:b(s?.error),requiresApproval:s?.requires_approval===!0,review:bb(s?.review)}]}):[];return{chainId:n,status:o,error:b(t?.error),awaitingStepId:b(t?.awaiting_step_id),steps:r}}function CI(e){const t=h(e);return b(t?.artifact_id)!==null&&b(t?.assetId)!==null&&b(t?.job_id)?.startsWith("download-")===!0}function MI(e){const t=h(e),n=h(t?.params),o=h(t?.confirmation),r=b(t?.kind),i=b(t?.planId),s=b(t?.bookId),a=b(t?.prompt),c=b(t?.routedTool),l=b(t?.tool),u=b(t?.message)??"",m=b(t?.summary),d=b(t?.effect),f=b(o?.reason),g=o?.required;if(r!=="chat-action-plan"||!i||!s||!a||!c||!l||!n||!m||d!=="mutation"&&d!=="generation"&&d!=="view"||typeof g!="boolean"||!f)throw new Error("The server returned an invalid chat action plan");return{kind:r,planId:i,bookId:s,prompt:a,routedTool:c,tool:l,params:n,message:u,summary:m,effect:d,confirmation:{required:g,reason:f}}}function Ns(e){return Array.isArray(e)?e.flatMap(t=>{const n=h(t),o=n&&b(n.bookId),r=n&&b(n.name),i=n&&F(n.createdAt);return!n||!o||!r||i===null?[]:[{bookId:o,name:r,createdAt:i,artifactCount:F(n.artifactCount)??0,notebookCount:F(n.notebookCount)??0}]}):[]}function TI(e){return Ns([e])[0]??null}function yb(e){const t=h(e),n=t&&b(t.id),o=t&&b(t.type),r=t&&b(t.label),i=t&&h(t.slot),s=i&&F(i.row),a=i&&F(i.column);if(!t||!n||s===null||a===null||!Number.isInteger(s)||!Number.isInteger(a)||s<0||s>=de||a<0||a>=X||!gb.has(o??""))return null;const c=h(t.inputs),l=Array.isArray(t.references)?t.references:void 0,u=Array.isArray(t.pinned_results??t.pinnedResults)?t.pinned_results??t.pinnedResults:void 0;return{id:n,type:o,...r?{label:r}:{},slot:{row:s,column:a},...b(t.output_entity_id)?{outputEntityId:b(t.output_entity_id)}:{},...b(t.prompt)!==null?{prompt:b(t.prompt)}:{},...b(t.provider)!==null?{provider:b(t.provider)}:{},...b(t.model)!==null?{model:b(t.model)}:{},...b(t.operation)!==null?{operation:b(t.operation)}:{},...b(t.tool)!==null?{tool:b(t.tool)}:{},...c?{inputs:c}:{},...l?{references:l}:{},...u?{pinnedResults:u}:{},...b(t.output_artifact_id??t.outputArtifactId)?{outputArtifactId:b(t.output_artifact_id??t.outputArtifactId)}:{}}}function _b(e){const t=h(e),n=t&&b(t.id),o=t&&b(t.name),r=t&&b(t.created_at??t.createdAt);if(!t||!n||!o||!r)return null;const i=Array.isArray(t.cells)?t.cells.flatMap(a=>{const c=yb(a);return c?[c]:[]}):[],s=Array.isArray(t.edges)?t.edges.flatMap(a=>{const c=h(a),l=c&&b(c.id),u=c&&b(c.source),m=c&&b(c.target),d=c&&b(c.targetInput??c.target_input);return l&&u&&m&&d?[{id:l,source:u,target:m,targetInput:d}]:[]}):[];return{id:n,name:o,createdAt:r,...b(t.revision)?{revision:b(t.revision)}:{},...b(t.description)?{description:b(t.description)}:{},...b(t.lifecycleState??t.lifecycle_state)?{lifecycleState:b(t.lifecycleState??t.lifecycle_state)}:{},...F(t.workflowVersion??t.workflow_version)!==null?{workflowVersion:F(t.workflowVersion??t.workflow_version)}:{},...b(t.analysisRevision??t.analysis_revision)?{analysisRevision:b(t.analysisRevision??t.analysis_revision)}:{},...h(t.fixture)?{fixture:h(t.fixture)}:{},...h(t.execution)?{execution:h(t.execution)}:{},...Array.isArray(t.generationPlans??t.generation_plans)?{generationPlans:t.generationPlans??t.generation_plans}:{},...Array.isArray(t.notebookRunPlans??t.notebook_run_plans)?{notebookRunPlans:t.notebookRunPlans??t.notebook_run_plans}:{},...Array.isArray(t.posts)?{posts:t.posts}:{},cells:i,edges:s}}function vb(e){return Array.isArray(e)?e.flatMap(t=>{const n=_b(t);return n?[n]:[]}):[]}function Ps(e){const t=h(e),n=t&&b(t.id),o=t&&b(t.artifact_id??t.artifactId),r=t&&b(t.type);if(!t||!n||!o||!r)return null;const i=h(t.audio_info),s=i&&b(i.codec),a=i&&F(i.sample_rate_hz),c=i&&F(i.channels),l=i&&b(i.channel_layout),u=i&&F(i.duration_seconds),m=s&&a!==null&&c!==null&&l&&u!==null?{codec:s,sampleRateHz:a,channels:c,channelLayout:l,durationSeconds:u}:null,d=h(t.analysis_info??t.analysisInfo),f=d&&F(d.source_duration_seconds??d.sourceDurationSeconds),g=Array.isArray(d?.shots)?d.shots.flatMap(w=>{const k=h(w),I=k&&F(k.ordinal),E=k&&b(k.label),C=k&&F(k.start_seconds??k.startSeconds),A=k&&F(k.end_seconds??k.endSeconds),$=k&&F(k.duration_seconds??k.durationSeconds);return I!==null&&E!==null&&C!==null&&A!==null&&$!==null?[{ordinal:I,label:E,startSeconds:C,endSeconds:A,durationSeconds:$}]:[]}):[],p=d?.llm_exchanges??d?.llmExchanges,y=Array.isArray(p)?p.flatMap(w=>{const k=h(w),I=k&&b(k.provider),E=k&&b(k.model),C=k&&b(k.stage),A=k&&h(k.response_format??k.responseFormat),$=A&&b(A.type);return I&&E&&C?[{provider:I,model:E,responseFormat:$?{name:b(A?.name),strict:A?.strict===!0,type:$}:null,stage:C}]:[]}):[],v=f!==null?{sourceDurationSeconds:f,llmExchanges:y,outputJson:d?.output_json??d?.outputJson??null,outputUrl:b(d?.output_url??d?.outputUrl),shots:g}:null,S=Array.isArray(t.waveform)?t.waveform.flatMap(w=>typeof w=="number"&&Number.isFinite(w)?[Math.max(-1,Math.min(1,w))]:[]):null;return{id:n,artifactId:o,label:b(t.label)??n,objectHash:b(t.object_hash??t.objectHash),type:r,createdAt:b(t.created_at??t.createdAt)??"",mediaUrl:b(t.media_url??t.mediaUrl),thumbnailUrl:b(t.thumbnail_url??t.thumbnailUrl),status:b(t.status)??"ready",origin:b(t.origin),prompt:b(t.prompt),width:F(t.width),height:F(t.height),duration:F(t.duration),fps:F(t.fps),waveform:S,audioInfo:m,analysisInfo:v,transcript:qd(t.transcript),visionAnalysis:Ud(t.vision_analysis??t.visionAnalysis),tags:yi(t.tags)}}function kb(e){const t=h(e);return(Array.isArray(e)?e:Array.isArray(t?.assets)?t.assets:[]).flatMap(o=>{const r=Ps(o);return r?[r]:[]})}function wb(e){const t=h(e);return{ready:Math.max(0,F(t?.ready)??0),processing:Math.max(0,F(t?.processing)??0),error:Math.max(0,F(t?.error)??0)}}function RI(e,t){const n=h(e),o=Array.isArray(n?.assets)?n.assets:[],r=h(n?.page),i=F(r?.offset)??0,s=F(r?.limit)??24,a=F(r?.total)??0,c=Array.isArray(n?.books_with_errors)?n.books_with_errors:[];return{unindexedVisualAssets:Math.max(0,F(n?.unindexed_visual_assets)??0),receivedCount:o.length,assets:o.flatMap(l=>{const u=h(l),m=Ps(u);if(!m)return[];const d=(u&&b(u.owning_book_id))??t?.owningBookId,f=(u&&b(u.owning_book_name))??t?.owningBookName,g=h(u?.assetWork),p=h(g?.meta),y=b(h(p?.error)?.message),v=(u&&b(u.last_used_at))??null;return d&&f?[{...m,owningBookId:d,owningBookName:f,errorMessage:y,lastUsedAt:v}]:[]}),page:{offset:i,limit:s,total:a,hasMore:r?.hasMore===!0},statusCounts:wb(n?.status_counts??n?.statusCounts),booksWithErrors:c.flatMap(l=>{const u=h(l),m=u&&b(u.book_id),d=u&&b(u.message);return m&&d?[{bookId:m,message:d}]:[]})}}function $I(e){const t=h(e),n=b(t?.status)==="in_use"?"in_use":"forgotten",o=Array.isArray(t?.references)?t.references:[];return{status:n,artifactId:b(t?.artifact_id)??"",label:b(t?.label),references:o.flatMap(r=>{const i=h(r),s=i&&b(i.kind),a=i&&b(i.id);return s&&a?[{kind:s,id:a}]:[]}),clearedCells:F(t?.cleared_cells)??0,forgottenObjects:F(t?.forgotten_objects)??0,sharedObjects:F(t?.shared_objects)??0,reclaimedBytes:F(t?.reclaimed_bytes)??0}}function Sb(e){return Array.isArray(e)?e.flatMap(t=>{const n=h(t),o=n&&b(n.artifactId),r=n&&b(n.state),i=n&&h(n.phases);return!o||!r||!i?[]:[{artifactId:o,state:r,missingOutputs:Array.isArray(n.missingOutputs)?n.missingOutputs.flatMap(s=>typeof s=="string"?[s]:[]):[],phases:Object.fromEntries(Object.entries(i).flatMap(([s,a])=>typeof a=="string"?[[s,a]]:[]))}]}):[]}function Ib(e){const t=h(e);return t&&b(t.sequenceId)&&b(t.revision)&&Array.isArray(t.tracks)&&Array.isArray(t.clips)&&Array.isArray(t.captions)?e:null}function xb(e){const t=h(e);if(!t||t.planVersion!==1||!b(t.planId)||!Array.isArray(t.stages))throw new Error("The server returned an invalid CommandPlan");const n=e;return gi(n),n}function Ab(e){return Array.isArray(e)?e.flatMap(t=>{const n=h(t),o=n&&F(n.id),r=n&&b(n.type),i=n&&b(n.state),s=n&&b(n.operationId??n.operation_id);if(!n||o===null||!r||!i||!s)return[];const a=h(n.error),c=n.payload,l=c&&typeof c=="object"&&!Array.isArray(c)?c:null,u=h(n.result);return[{id:o,operationId:s,type:r,state:i,artifactId:b(n.artifactId??n.artifact_id),attempts:F(n.attempts)??0,maxAttempts:F(n.maxAttempts??n.max_attempts)??1,error:a&&b(a.message)?{message:b(a.message),code:b(a.code)}:null,payload:l,result:u,providerTask:ui(n.providerTask),enqueuedAt:F(n.enqueuedAt??n.enqueued_at)??0,startedAt:F(n.startedAt??n.started_at),finishedAt:F(n.finishedAt??n.finished_at)}]}):[]}function NI(e){return Array.isArray(e)?e.flatMap(t=>{const n=h(t),o=b(n?.planId),r=b(n?.cellId),i=b(n?.status),s=b(n?.createdAt),a=b(n?.updatedAt);if(!n||!o||!r||!i||!s||!a)return[];try{return[{planId:o,cellId:r,status:i,plan:xb(n.plan),outputArtifactId:b(n.outputArtifactId),error:b(n.error),createdAt:s,updatedAt:a}]}catch{return[]}}):[]}function Eb(e){return Array.isArray(e)?e.filter(t=>{const n=h(t);return n!==null&&typeof n.command=="string"&&typeof n.description=="string"}):[]}function PI(e){if(!e)return null;const t=Ns(e.bookValue),n=vb(e.notebookValue);return{books:t,bookId:e.bookId,notebook:n.find(o=>o.id===e.notebookId)??null,assets:kb(e.assetValue),ingestStatuses:Sb(e.ingestStatusValue),sequence:Ib(e.sequenceValue),jobs:Ab(e.jobValue),commands:Eb(e.commandValue),chatModelCatalog:Hh(e.chatModelValue),generationActions:dd(e.actionValue)}}function eo(e){return e!==null&&Number.isFinite(e)&&e>0}function Cb(e,t){return eo(e)&&eo(t)?`${e}×${t}`:null}function Os(e,t){const n=e??t;if(!n)return null;const o=bd(n);return{key:"generator",label:o,title:o,announce:`Generator ${o}`,emphasis:"generator"}}function Ls(e){return e?{key:"provenance",label:e,title:`Extracted from ${e}`,announce:`Extracted from ${e}`,emphasis:"generator"}:null}function OI(e){const t=Cb(e.width,e.height),n=on(e.width,e.height);return[t?{key:"dimensions",label:t,title:"Dimensions",announce:`Dimensions ${t}`,emphasis:"plain"}:null,n?{key:"aspect",label:n,title:"Aspect ratio",announce:`Aspect ratio ${n}`,emphasis:"plain"}:null,Os(e.tool,e.model),Ls(e.provenance)].filter(o=>o!==null)}function LI(e){const t=e.aspectRatio??on(e.width,e.height);return[t?{key:"aspect",label:t,title:"Aspect ratio",announce:`Aspect ratio ${t}`,emphasis:"plain"}:null,Os(e.tool,e.model),Ls(e.provenance)].filter(n=>n!==null)}function FI(e){const t=io(e);return[{key:"role",label:t.role,title:"Audio role",announce:`Audio role ${t.role}`,emphasis:"generator"},...t.details.map((o,r)=>({key:`detail-${r}`,label:o,title:o,announce:o,emphasis:"plain"}))]}function Mb(e){return eo(e)?{label:me(Math.floor(e)),seconds:e}:null}function DI(e){return Mb(io(e).durationSeconds)}function VI(e,t,n,o){return[`${e} metadata`,...t.map(r=>r.announce),n?`Duration ${n.label}`:null,o?`Prompt: ${o}`:null].filter(r=>!!r).join(". ")}const jI={title:6,continuity:30,frame:20,storyboard:32,ending:12,video:12};function GI(e){return e.trim().split(/\s+/u).filter(Boolean).length}function qI(e,t){const n=Math.max(0,e/t),o=Math.floor(n/60),r=n-o*60;return`${o}:${r.toFixed(2).padStart(5,"0")}`}function UI(e,t){const n=e.trim(),o=/^f(\d+)$/i.exec(n);if(o)return Number(o[1]);const r=/^(?:(\d+):)?(\d+(?:\.\d+)?)$/.exec(n);if(!r)return null;const i=r[1]?Number(r[1]):0,s=Number(r[2]);return r[1]&&s>=60?null:Math.round((i*60+s)*t)}const{fontFamily:Tb}=Ys();function Rb(e){return e==="left"?"flex-start":e==="right"?"flex-end":"center"}function $b(e){return e==="left"?"left bottom":e==="right"?"right bottom":"center bottom"}function Nb(e,t){const n=`0 ${Math.round(t*.04)}px ${Math.round(t*.3)}px rgba(0,0,0,0.5)`;if(e.shadowBlur<=0)return n;const o=Math.round(e.shadowBlur/2);return`${o}px ${o}px ${e.shadowBlur}px rgba(0,0,0,${e.shadowOpacity/100}), ${n}`}const Br=e=>{const t=ne.c(33),{words:n,fontSize:o,time:r,fade:i,settings:s,side:a,finish:c,last:l}=e,u=Math.min(c.strokeWidth,o*.035);let m;t[0]!==a?(m=Rb(a),t[0]=a,t[1]=m):m=t[1];let d;t[2]!==o?(d=Math.round(o*.2),t[2]=o,t[3]=d):d=t[3];const f=o*Zt;let g;t[4]!==o||t[5]!==l?(g=l?0:rh(o),t[4]=o,t[5]=l,t[6]=g):g=t[6];let p;t[7]!==o||t[8]!==m||t[9]!==d||t[10]!==f||t[11]!==g?(p={display:"flex",justifyContent:m,gap:d,fontSize:o,lineHeight:Zt,height:f,marginBottom:g,whiteSpace:"nowrap"},t[7]=o,t[8]=m,t[9]=d,t[10]=f,t[11]=g,t[12]=p):p=t[12];let y;if(t[13]!==i||t[14]!==c||t[15]!==o||t[16]!==s||t[17]!==a||t[18]!==u||t[19]!==r||t[20]!==n){let S;t[22]!==i||t[23]!==c||t[24]!==o||t[25]!==s||t[26]!==a||t[27]!==u||t[28]!==r?(S=(w,k)=>{const I=ph(w,r,s,o,i);return Be.jsx("span",{style:{display:"inline-block",opacity:I.opacity,color:I.color,transform:`translateY(${I.translateY}px) scale(${I.scale})`,transformOrigin:$b(a),WebkitTextStroke:u>0?`${u}px ${c.strokeColor}`:void 0,paintOrder:u>0?"stroke fill":void 0,textShadow:Nb(c,o)},children:w.text.toUpperCase()},`${w.start}-${k}`)},t[22]=i,t[23]=c,t[24]=o,t[25]=s,t[26]=a,t[27]=u,t[28]=r,t[29]=S):S=t[29],y=n.map(S),t[13]=i,t[14]=c,t[15]=o,t[16]=s,t[17]=a,t[18]=u,t[19]=r,t[20]=n,t[21]=y}else y=t[21];let v;return t[30]!==p||t[31]!==y?(v=Be.jsx("div",{style:p,children:y}),t[30]=p,t[31]=y,t[32]=v):v=t[32],v};function Hr(e,t){return{position:"absolute",left:e.x,top:t,width:e.width,display:"flex",flexDirection:"column",fontFamily:Tb,fontWeight:400,userSelect:"none",pointerEvents:"none"}}const BI=e=>{const t=ne.c(14);let n,o,r;t[0]!==e?({cues:n,settings:r,...o}=e,t[0]=e,t[1]=n,t[2]=o,t[3]=r):(n=t[1],o=t[2],r=t[3]);const i=Js(),{fps:s}=Zs(),a=i/s;let c,l,u;if(t[4]!==n||t[5]!==o||t[6]!==r||t[7]!==a){u=Symbol.for("react.early_return_sentinel");e:{const d=lh(n,a);if(!d){u=null;break e}const f=uh(d,a);if(r.style==="punch"){const g=dh(d,a);if(!g){u=null;break e}const p=sh(g,d.column,r.energySizing),y=d.column.y+(d.column.height-p*Zt)/2;u=Be.jsx("div",{style:Hr(d.column,y),children:Be.jsx(Br,{words:[g],fontSize:p,time:a,fade:f,settings:r,side:d.column.side,finish:o,last:!0})});break e}c=Hr(d.column,d.blockTop),l=d.lines.map((g,p)=>Be.jsx(Br,{words:g.words,fontSize:g.fontSize,time:a,fade:f,settings:r,side:d.column.side,finish:o,last:p===d.lines.length-1},`${d.id}-${p}`))}t[4]=n,t[5]=o,t[6]=r,t[7]=a,t[8]=c,t[9]=l,t[10]=u}else c=t[8],l=t[9],u=t[10];if(u!==Symbol.for("react.early_return_sentinel"))return u;let m;return t[11]!==c||t[12]!==l?(m=Be.jsx("div",{style:c,children:l}),t[11]=c,t[12]=l,t[13]=m):m=t[13],m};export{lv as $,xv as A,pv as B,$l as C,rv as D,Iv as E,u_ as F,d_ as G,f_ as H,Sv as I,j_ as J,m_ as K,gv as L,p_ as M,ov as N,Ov as O,Vb as P,uv as Q,B_ as R,Q_ as S,sn as T,Tv as U,Nv as V,Pv as W,Fv as X,iv as Y,H_ as Z,sv as _,wy as a,W_ as a$,av as a0,fv as a1,nv as a2,wv as a3,kv as a4,r_ as a5,Iu as a6,ek as a7,O as a8,Ze as a9,Jd as aA,lw as aB,sw as aC,dw as aD,hn as aE,x_ as aF,E_ as aG,sf as aH,af as aI,ww as aJ,Sw as aK,Qi as aL,uf as aM,Cw as aN,Mw as aO,yw as aP,Ew as aQ,vw as aR,kw as aS,_w as aT,Xw as aU,Yw as aV,Jw as aW,ki as aX,El as aY,xl as aZ,Dn as a_,_e as aa,rk as ab,ik as ac,me as ad,sk as ae,ak as af,s_ as ag,c_ as ah,a_ as ai,ck as aj,Wi as ak,Qa as al,Ty as am,Ek as an,Lk as ao,Ok as ap,Fk as aq,Dk as ar,Zk as as,Xv as at,nw as au,ow as av,iw as aw,uw as ax,aw as ay,cw as az,hy as b,UI as b$,bv as b0,J_ as b1,Ji as b2,Yi as b3,Nk as b4,Pk as b5,K_ as b6,oS as b7,cS as b8,aS as b9,iS as bA,Dy as bB,fy as bC,jy as bD,vt as bE,si as bF,b as bG,bd as bH,h as bI,By as bJ,FI as bK,DI as bL,OI as bM,LI as bN,Mb as bO,nn as bP,Gy as bQ,ja as bR,F as bS,VI as bT,Ms as bU,ii as bV,Uy as bW,sS as bX,jo as bY,y_ as bZ,qI as b_,dS as ba,fS as bb,pm as bc,uS as bd,US as be,WS as bf,Sp as bg,t0 as bh,e0 as bi,n0 as bj,Va as bk,my as bl,gy as bm,py as bn,Py as bo,Ly as bp,Oy as bq,Ky as br,ro as bs,v_ as bt,ok as bu,__ as bv,_v as bw,Rw as bx,Vi as by,um as bz,Db as c,Fw as c$,oi as c0,ea as c1,Oa as c2,sy as c3,ni as c4,tn as c5,Ca as c6,et as c7,ya as c8,no as c9,vS as cA,bp as cB,_p as cC,dp as cD,Zm as cE,Cy as cF,sp as cG,lp as cH,FS as cI,Qm as cJ,My as cK,Cp as cL,Pp as cM,Ry as cN,Ny as cO,Uw as cP,Pf as cQ,Nf as cR,Vf as cS,Df as cT,$f as cU,Rf as cV,Af as cW,jf as cX,Mf as cY,Cf as cZ,$y as c_,ti as ca,Qb as cb,Bb as cc,Ro as cd,Ub as ce,qb as cf,Xb as cg,Wb as ch,Kb as ci,vo as cj,Ja as ck,Sk as cl,td as cm,$k as cn,nd as co,Ce as cp,SS as cq,kS as cr,ye as cs,IS as ct,xS as cu,AS as cv,gS as cw,So as cx,ES as cy,CS as cz,L_ as d,Yt as d$,Of as d0,jw as d1,Sr as d2,tc as d3,ec as d4,Wf as d5,Hf as d6,Jv as d7,Yv as d8,Zv as d9,pw as dA,Hi as dB,qy as dC,fk as dD,hd as dE,Ak as dF,pk as dG,bo as dH,nt as dI,fw as dJ,Tw as dK,hv as dL,bf as dM,M0 as dN,C0 as dO,gt as dP,Qe as dQ,ht as dR,xr as dS,cg as dT,GI as dU,jI as dV,Ne as dW,k0 as dX,w0 as dY,S0 as dZ,v0 as d_,Qv as da,t_ as db,lk as dc,Ic as dd,Qk as de,uk as df,rw as dg,dk as dh,Ck as di,kk as dj,Qu as dk,gd as dl,zi as dm,ln as dn,St as dp,Rk as dq,Tk as dr,go as ds,Mk as dt,xk as du,vk as dv,_k as dw,Vy as dx,nk as dy,mw as dz,G_ as e,tk as e$,_0 as e0,y0 as e1,zn as e2,As as e3,jb as e4,Gb as e5,I0 as e6,Jp as e7,pt as e8,x0 as e9,h0 as eA,l_ as eB,T_ as eC,gk as eD,q_ as eE,zS as eF,Iy as eG,DS as eH,QS as eI,Ya as eJ,Hk as eK,bI as eL,yI as eM,qk as eN,NI as eO,$_ as eP,xI as eQ,F_ as eR,P_ as eS,O_ as eT,N0 as eU,E0 as eV,A0 as eW,Pw as eX,mS as eY,b_ as eZ,k_ as e_,ig as ea,eg as eb,Lv as ec,lh as ed,Hg as ee,BI as ef,th as eg,Wg as eh,K0 as ei,z0 as ej,W0 as ek,G0 as el,q0 as em,V0 as en,U0 as eo,B0 as ep,H0 as eq,Or as er,PI as es,pI as et,d0 as eu,Bh as ev,mI as ew,VS as ex,p0 as ey,u0 as ez,lt as f,w_ as f$,V_ as f0,Eo as f1,Qy as f2,e_ as f3,Zy as f4,vv as f5,xb as f6,Yy as f7,Xy as f8,T0 as f9,Ay as fA,TS as fB,Em as fC,Fd as fD,Wk as fE,Kk as fF,zk as fG,Xk as fH,Yk as fI,_I as fJ,mg as fK,Fy as fL,wo as fM,i_ as fN,SI as fO,ew as fP,tw as fQ,cb as fR,vb as fS,Ib as fT,dd as fU,wI as fV,ci as fW,Ns as fX,S_ as fY,$I as fZ,I_ as f_,i0 as fa,R0 as fb,$0 as fc,gI as fd,_b as fe,Ab as ff,sI as fg,rI as fh,gc as fi,iI as fj,kb as fk,cI as fl,hg as fm,a0 as fn,qp as fo,mk as fp,r0 as fq,s0 as fr,zv as fs,Bv as ft,Q0 as fu,Z0 as fv,Uv as fw,Hv as fx,g0 as fy,xy as fz,Jy as g,Hc as g$,z_ as g0,X_ as g1,Eb as g2,Hh as g3,Gh as g4,f0 as g5,m0 as g6,TI as g7,Nw as g8,Ww as g9,Uk as gA,MI as gB,No as gC,vy as gD,ky as gE,Yb as gF,jS as gG,GS as gH,qS as gI,A_ as gJ,M_ as gK,l0 as gL,gw as gM,bw as gN,ey as gO,eI as gP,tI as gQ,Wv as gR,Zw as gS,zy as gT,o_ as gU,n_ as gV,lS as gW,o0 as gX,Kv as gY,BS as gZ,HS as g_,h_ as ga,yv as gb,Yf as gc,Bw as gd,XS as ge,ZS as gf,YS as gg,ay as gh,JS as gi,pS as gj,It as gk,KS as gl,Y_ as gm,rS as gn,qv as go,Ik as gp,jv as gq,Xl as gr,Gv as gs,Rv as gt,Vv as gu,Bt as gv,R_ as gw,D_ as gx,uc as gy,kI as gz,g_ as h,qw as h$,j0 as h0,X0 as h1,Y0 as h2,Aw as h3,xw as h4,Iw as h5,dv as h6,Dv as h7,hI as h8,mv as h9,J0 as hA,cv as hB,aI as hC,kr as hD,Zd as hE,Jk as hF,bS as hG,un as hH,_m as hI,oI as hJ,$v as hK,Qw as hL,eS as hM,D0 as hN,tS as hO,nS as hP,F0 as hQ,lI as hR,ty as hS,ny as hT,Hw as hU,Xf as hV,Bf as hW,Tf as hX,Ff as hY,us as hZ,Ef as h_,Ow as ha,Lw as hb,wS as hc,Gk as hd,bk as he,jk as hf,Vk as hg,Zb as hh,Jb as hi,zb as hj,hw as hk,c0 as hl,C_ as hm,RI as hn,II as ho,Hb as hp,ry as hq,oy as hr,CI as hs,AI as ht,hk as hu,hS as hv,L0 as hw,O0 as hx,P0 as hy,b0 as hz,yy as i,Vw as i0,Gw as i1,Gf as i2,Dw as i3,yk as i4,Bk as i5,EI as i6,RS as i7,PS as i8,$S as i9,Uf as iA,fI as iB,NS as ia,OS as ib,LS as ic,MS as id,_y as ie,iy as ig,zw as ih,Kw as ii,Hy as ij,Wy as ik,ly as il,uy as im,cy as io,by as ip,vI as iq,Zi as ir,nI as is,$w as it,uI as iu,dI as iv,wk as iw,yS as ix,_S as iy,qf as iz,zo as j,Et as k,Cl as l,N_ as m,ev as n,U_ as o,dy as p,Z_ as q,tv as r,Ml as s,Gl as t,Sy as u,Av as v,Ev as w,Ey as x,Cv as y,Mv as z};