videobook 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +135 -0
- package/dist/asset-media-projection.js +161 -0
- package/dist/command-reference.js +3 -1
- package/dist/diagnostics.js +10 -4
- package/dist/generation-reference-mentions.js +19 -0
- package/dist/goal-plan-v3.js +21 -6
- package/dist/goal-plan.js +1 -1
- package/dist/goal-store.js +2 -2
- package/dist/har-capture.js +36 -3
- package/dist/jobs/_image-edit-adapter.js +2 -0
- package/dist/jobs/_kie-upload.js +3 -1
- package/dist/jobs/assess-media-probes.js +94 -0
- package/dist/jobs/complete-provider-task.js +2 -5
- package/dist/jobs/generate-media.js +22 -12
- package/dist/jobs/image-subjects.js +2 -0
- package/dist/jobs/kie-paygate.js +3 -3
- package/dist/jobs/register-all.js +2 -0
- package/dist/jobs/run-notebook.js +16 -1
- package/dist/library-asset-projection.js +141 -0
- package/dist/lightning-defaults.js +4 -4
- package/dist/media/catalog.js +12 -6
- package/dist/media/descriptor.js +16 -7
- package/dist/media/frontier-gaps.js +0 -1
- package/dist/media/har-endpoint.js +25 -0
- package/dist/media/json-schema.js +3 -0
- package/dist/media/listing.js +26 -4
- package/dist/media/preferred-defaults.js +161 -0
- package/dist/media/prompt-dialects.js +9 -1
- package/dist/media-library.js +158 -153
- package/dist/notebook-sticky-settings.js +60 -0
- package/dist/provider-usage.js +24 -9
- package/dist/tools/estimate-cost.js +9 -4
- package/dist/tools/reconcile-project-work.js +37 -184
- package/dist/tools/videobook-domain.js +16 -1
- package/dist/usage-providers.js +3 -3
- package/package.json +15 -15
- package/ui/assets/{alive-captions-Cj8C1tCN.js → alive-captions-BWk_4aX0.js} +1 -1
- package/ui/assets/confirm-bodies-CNW9vLsi.js +1 -0
- package/ui/assets/{fullscreen-DyEncSdm.js → fullscreen-ND_H86Ih.js} +1 -1
- package/ui/assets/{goal-ui-BdFeoSWh.js → goal-ui-CCTD4lxi.js} +1 -1
- package/ui/assets/index-CTPstLYq.css +1 -0
- package/ui/assets/index-D0ftggO4.js +37 -0
- package/ui/assets/inspector-BZnbKsEZ.js +1 -0
- package/ui/assets/{jobs-ui-BudI4w0r.js → jobs-ui-BNK0IPSl.js} +1 -1
- package/ui/assets/{music-video-CT4C55ok.js → music-video-CoOI0cgW.js} +1 -1
- package/ui/assets/{ui-mq0uIS5P.css → ui-BBM3YCY6.css} +1 -1
- package/ui/assets/ui-koLWlu0t.js +2 -0
- package/ui/assets/vendor-Ca2-b3hB.js +19 -0
- package/ui/assets/{vendor-flow-nqTFQmTh.js → vendor-flow-C2NYBYCL.js} +1 -1
- package/ui/assets/vendor-icons-D3KrGMJY.js +1 -0
- package/ui/assets/{vendor-mcp-D_C3EZPv.js → vendor-mcp-9gUvOX4H.js} +2 -2
- package/ui/assets/videobook-B8dYNQrG.js +21 -0
- package/ui/index.html +14 -14
- package/ui/assets/confirm-bodies-BxWXwDf0.js +0 -1
- package/ui/assets/index-DWfR79lA.css +0 -1
- package/ui/assets/index-QZ8lbemN.js +0 -37
- package/ui/assets/inspector-BC6xWkJU.js +0 -1
- package/ui/assets/ui-z5r-p0K9.js +0 -2
- package/ui/assets/vendor-D8XcMav4.js +0 -19
- package/ui/assets/vendor-icons-CGqhCIXV.js +0 -1
- package/ui/assets/videobook-CsW453sb.js +0 -21
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import{c as ne,a as _,j as Ke}from"./vendor-react-Dj7D1fD4.js";import{n as It,a as Zs,t as Ht,T as ti,b as ue,N as de,d as X,e as an,f as ke,S as Qs,i as ni,g as ea,s as co,h as ta,j as Xe,k as Dn,l as na,m as Ee,o as oa,p as Do,q as Vn,r as ra,u as oi,M as ia,v as ri,w as Fe,x as ii,y as Wt,z as sa,A as aa,B as si,C as Yt,D as ca}from"./vendor-Ca2-b3hB.js";import{o as te,n as V,a as ae,s as j,_ as Ze,l as ai,b as Te,C as la,S as ua}from"./vendor-mcp-9gUvOX4H.js";import{l as da,u as fa,a as ma}from"./vendor-remotion-CH1HXrlc.js";const ly=["x","instagram","tiktok","youtube","other"],uy=["views","impressions","likes","replies","reposts","quotes","bookmarks","shares","clicks"];function pa(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"book"}function ci(e,t,n){return`${pa(e)}/post-${t.replace(/^@/u,"")}-${n.slice(-6)}`}function ga(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 ha="9:16",ba="4K",ya="jpg",dy=25,_a="9:16",va="1080p",ka=12,wa="mp4",Sa=!0,fy=60,Ia={resolution:va,aspect_ratio:_a,duration:ka,output_format:wa,generate_audio:Sa},xa={aspect_ratio:ha,resolution:ba,output_format:ya},Aa=3,Ea=2.3,Ca=.3,Ma="th",Ta=["fyp","bkk"],Ra={profileUrl:"https://www.tiktok.com/@jtbkk",includePlatformIcon:!0,includeHandleBorder:!0,handlePaddingX:15,handlePaddingY:12,handleRounding:56,handlePlacement:"center",handleVerticalPercent:10,handleStartSeconds:0,handleEndSeconds:Aa,handleOpacity:.28,qrLeadSeconds:Ea,qrOpacity:.37,fadeSeconds:Ca};function $a(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 my=["en","th"],Na={en:"English",th:"Thai"},Pa={x:280,instagram:2200,tiktok:2200,youtube:5e3,other:2200},li={x:2,instagram:10,tiktok:5,youtube:15,other:8},lo={x:"X",instagram:"Instagram",tiktok:"TikTok",youtube:"YouTube Shorts",other:"Other"},Oa=/^#[\p{L}\p{M}\p{N}_]+$/u;function La(e){return e.trim().replace(/^#+/u,"").replace(/[^\p{L}\p{M}\p{N}_]/gu,"")}function cn(e,t=Number.POSITIVE_INFINITY){const n=new Set,o=[];for(const r of e){const i=La(r),s=i.toLocaleLowerCase();if(!(!i||n.has(s))&&(n.add(s),o.push(i),o.length>=t))break}return o}function Fa(e){const t=e.trim().split(/\s+/u);return t.length>0&&t.every(n=>Oa.test(n))}function Da(e){const n=e.trimEnd().split(`
|
|
2
|
+
`),o=n[n.length-1]??"";return!o.trim()||!Fa(o)?{body:e,tags:[]}:{body:n.slice(0,-1).join(`
|
|
3
|
+
`).trimEnd(),tags:cn(o.trim().split(/\s+/u))}}function Va(e,t){const n=cn(t).map(r=>`#${r}`).join(" "),o=e.trimEnd();return n?o?`${o}
|
|
4
|
+
|
|
5
|
+
${n}`:n:o}const py=[{id:"x",label:"X"},{id:"tiktok",label:"TikTok"},{id:"instagram",label:"Instagram"},{id:"youtube",label:"YT Shorts"},{id:"other",label:"Other"}],gy=["Longer caption","Punchier","More emoji","Fewer tags","Add a call to action"],ja=/[-]/u;function Ga(e){return ja.test(e)?"th":"en"}function hy(e){const t=e.definition.caption,n=e.definition.platform==="tiktok"&&!t.trim(),o=n?Ma:Ga(t),r=Da(t),i=t.trim()?{[o]:{versions:[{body:r.body,tags:r.tags,origin:"saved",instruction:null}],index:0}}:n?{th:{versions:[{body:"",tags:[...Ta],origin:"auto",instruction:null}],index:0}}:{};return{language:o,platform:e.definition.platform,tracks:i,prompt:"",drafting:null,error:null}}function tt(e){const t=e.tracks[e.language];return t?.versions[t.index]??null}function pt(e){const t=tt(e);return t?Va(t.body,t.tags):""}function qa(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 ui(e,t){const n=tt(e)??{body:"",tags:[],origin:"edited",instruction:null};return qa(e,{...n,...t,origin:"edited"})}function by(e,t){const n=tt(e)?.tags??[],o=cn([...n,...t.split(/[\s,]+/u)]);return o.length===n.length?e:ui(e,{tags:o})}function yy(e,t){const n=tt(e)?.tags??[];return ui(e,{tags:n.filter(o=>o!==t)})}function _y(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 vy(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 ky(e,t,n){const o=e.tracks[t],r=o?.versions[o.index]?.body.trim()??"";return!n&&!e.drafting&&r.length===0}function wy(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 Sy(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:cn(o)}}function Iy(e){const t=tt(e),n=Na[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 Ua(e){const t=pt(e).length,n=Pa[e.platform],o=tt(e)?.tags.length??0;return{length:t,limit:n,over:t>n,tooManyTags:o>li[e.platform]}}function Ba(e){const t=Ua(e),n=lo[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 ${li[e.platform]} tags or fewer.`:null}const Ha=new Set(["posting","needs_reconciliation","scheduled"]),Vo=25e3,Wa="iCloud Drive isn't available on this Mac.";function Ka(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 xy(e,t,n,o){const r=n?.trim();return r?e.find(i=>Ka(i,t,r))??null:e.find(i=>i.id===o)??null}const za=new Set(["image","video","generate_image","generate_video","concat","splice","split_video"]);function Ay(e,t){const n=t.trim().replace(/^@/u,"").toLowerCase();return e.find(o=>o.type!=="post"&&!!o.outputArtifactId&&za.has(o.type)&&[o.id,o.outputArtifactId,It(o.slot)].some(r=>r?.toLowerCase()===n))??null}function Ey(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 Cy(e,t){return e.runtime.icloud?.folder??ci(t,e.address,e.id)}function My(e,t){return e.runtime.dropbox?.folder?e.runtime.dropbox.folder:`/Videobook/${ci(t,e.address,e.id)}`}function Xa(e,t){return e==="dropbox"||t&&!t.available?"dropbox":"icloud"}function Ty(e,t){return{...e,icloud:t,destination:e.pinnedDestination?e.destination:Xa(e.entry,t)}}function xt(e){return!!e.runtime.outbound}function Ya(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 Ja(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 Za(e,t){return e?e.definition.source?.snapshotArtifactId?Ha.has(e.runtime.status)?`Resolve or cancel ${e.address}'s current publication first.`:t.length>Vo?`Shorten the caption to ${Vo.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 Ry(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 Qa(e,t){return!e||xt(e)?null:t.copy.drafting?"Astra is writing the caption…":null}function jo(e,t){return e&&!xt(e)?Ba(t.copy):null}function $y(e,t){const n=Za(e,pt(t.copy))??Qa(e,t);if(t.destination==="dropbox"){const i=n??Ya(t.dropboxFolder)??Ja(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.":jo(e,t);return{blocking:i,notice:i?null:s}}const o=t.icloud?t.icloud.available?null:t.icloud.reason??Wa:"Checking iCloud Drive…",r=n??o??ga(t.icloudFolder);return{blocking:r,notice:r?null:jo(e,t)}}function Ny(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,...!xt(e)&&pt(t.copy)!==e.definition.caption?{caption:pt(t.copy)}:{}}}function Py(e,t){return xt(e)||t.copy.platform===e.definition.platform?null:{book_id:t.bookId,post_cell_id:e.id,platform:t.copy.platform}}function Oy(e,t){if(xt(e))return null;const n=pt(t.copy),o={...t.copy.platform!==e.definition.platform?{platform:t.copy.platform}:{},...n!==e.definition.caption?{caption:n}:{}};return Object.keys(o).length>0?{book_id:t.bookId,post_cell_id:e.id,...o}:null}function Ly(e){return e==="icloud"?"save_post_to_icloud":"upload_post_to_dropbox"}function ec(e){const t=[];return e.runtime.icloud?.completedAt&&t.push("iPhone"),e.runtime.dropbox?.completedAt&&t.push("Dropbox"),t}function di(e){return!e.runtime.url&&ec(e).length>0}function Fy(e){const t=e.definition.platform;return t==="other"?"Posted it? Paste the link":`Posted on ${lo[t]}? Paste the link`}function Go(e){return lo[e.definition.platform]}function Dy(e){return di(e)?"needs_link":e.runtime.status}function Vy(e){return e.runtime.postedAt||e.runtime.url?null:di(e)?e.definition.platform==="other"?"Paste the published link":`Paste ${Go(e)} link`:e.definition.platform==="other"?"Save to iPhone or paste link":`Save to iPhone or paste ${Go(e)} link`}function jy(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:tc(t[o])})):[]}function tc(e){return new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(e)}function qy(e){return`On iPhone · iCloud Drive › Videobook › ${e}`}function Uy(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 By(e,t){return e==="uploading"?"Uploading to iCloud…":e==="uploaded"?"On iCloud":e==="error"?t?.trim()||"iCloud upload failed":null}function nc(e){return e===null||e==="uploading"}function oc(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 uo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}async function qo(e){const t=uo(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 Hy(e){const t=uo(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 Wy(e){const t=uo(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 qo(e);for(let r=0;r<90&&o.pending&&!o.connected&&n();r+=1)await t(2e3),o=await qo(e);return o}const rc=3e3,ic=12e4;function zy(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 f=Date.now()+ic,d=async()=>{if(!(m||Date.now()>f))try{const g=oc(await t("post_icloud_sync_status",{book_id:n,post_cell_id:o},{background:!0}));if(m)return;s.current(g),nc(g.phase)||(m=!0)}catch(g){const y=g;if(m)return;m=!0,s.current({phase:"error",error:y instanceof Error?y.message:"iCloud upload failed"})}};d();const p=window.setInterval(()=>{if(m||Date.now()>f){window.clearInterval(p);return}d()},rc);return()=>{m=!0,window.clearInterval(p)}},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 Xy(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 At=280,Uo=25,jn=4,sc=5e3,ac=3600*1e3,Bo=300*1e3;function cc(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 Yy(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:cc(e.followups)}}function Jy(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 Zy(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 lc="Add a title for the post.";function uc(e,t=Date.now(),n=At){if(e.postText.trim()==="")return lc;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>Uo)return`Thread has ${e.followups.length} replies; X posts support at most ${Uo} 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>jn)return`Follow-up ${r+1} has more than ${jn} 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<=sc?"Scheduled time must be in the future.":null}function Qy(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 e_(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toISOString()}function t_(e=Date.now()){const t=e+ac,n=Math.ceil(t/Bo)*Bo;return new Date(n).toISOString()}function dc(e){return e==="fal:minimax/h3-max/insert-video"||e==="minimax/h3-max/insert-video"}function fc(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 mc(e){return e.find(t=>t.targetInput==="video")??e.find(t=>t.type==="video"||t.type==="final")}function n_(e,t,n){if(!dc(e))return null;const o=mc(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.":fc(t,r)}const pc=["x","tiktok"],o_={x:"X",tiktok:"TikTok"},r_={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 i_(e,t="x"){return t==="tiktok"?`https://www.tiktok.com/@${e}`:`https://x.com/${e}`}function gc(e){return e==="x"||e==="tiktok"}function fi(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 hc=new Set(["generate_audio","generate_image","generate_video"]),mi=["audio","image","video"],bc=new Set([...mi,"character"]),yc=new Set(mi),_c={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 pi(e){return _c[e]}function Et(e){return hc.has(e)}function fo(e){return bc.has(e)}function vc(e){return yc.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 kc=[["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]],wc=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"]),Sc={analyze:"Analyze",concat:"Concatenate",extract_audio:"Extract",generate_audio:"Generate",generate_image:"Generate",generate_video:"Generate",prompt:"Rewrite",splice:"Splice",split_video:"Split"};function dt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function _n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ic(e){return e.type!=="analysis"&&!fo(e.type)&&!!(e.operation??e.tool??e.model)}function ln(e){return wc.has(e)}function xc(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 s_=3,Ac={1:"QUEUED",2:"PROVIDER GENERATING",3:"DOWNLOAD & COMMIT"};function Ec(e){return e==="queued"?1:e==="running"||e==="generating"||e==="awaiting-output"?2:e==="downloading"||e==="completing"?3:null}function a_(e){const t=Ec(e);return t===null?null:{step:t,label:Ac[t]}}function Cc(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 c_(e,t,n){return t==="error"?{overlay:"failed",label:null,startedAt:null,error:n?.error??(fo(e)?"Media processing failed":"Generation failed"),tone:"error"}:ln(t)?{overlay:"clock",label:xc(t,e),startedAt:Cc(n?.startedAt),error:null,tone:t==="queued"?"queued":"active"}:{overlay:null,label:null,startedAt:null,error:null,tone:null}}function l_(e,t){const n=h(e.execution),o=n&&h(n[t]);return{error:W(o?.error),status:W(o?.status)}}function Mc(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&&ln(i)?"active":"pending",status:i}}function u_(e,t){if(!Ic(e))return null;const n=ln(t);return Et(e.type)?{disabled:n,label:"Gen"}:{disabled:n,label:e.outputArtifactId||t==="completed"||t==="error"?"Re-run":"Run"}}function d_(e,t){const n=Sc[e];return n?t==="Re-run"?`${n} again`:n:t}function f_(e,t){return fo(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 Tc(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 un(e,t){if(e===null||t===null||!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0)return null;const n=e/t,o=kc.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=Tc(r,i);return`${r/s}:${i/s}`}function mo(e){const t=dt(e.inputs?.startSeconds),n=dt(e.inputs?.endSeconds),o=dt(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 gi(e){const t=e.inputs?.mediaRole;return e.type==="image"&&t==="generate-image-output"||e.type==="video"&&t==="generate-video-output"}function m_(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 Rc(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 p_(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||!_n(a,"input")||!_n(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:Rc(a.input),stage:W(a.stage)??`call_${s+1}`}]});if(o.length>0)return o;const r=h(t.request);return!r||!_n(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 $c(e){return{first:W(e?.firstFrameArtifactId),last:W(e?.lastFrameArtifactId)}}function g_(e){const t=dt(e?.startSeconds),n=dt(e?.endSeconds);return t!==null&&n!==null&&n>t?{startSeconds:t,endSeconds:n}:null}function h_(e){return e.replace(/^generate_/,"gen_").replaceAll("_"," ").toUpperCase()}function Ye(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid cold-open response");return e}function Nc(e){const t=Ye(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"||fi(t.startSeconds,t.endSeconds,t.durationSeconds))throw new Error("The server returned an invalid cold-open selection");return t}async function hi(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=Ye(i[0]);if(s.state==="done")return Ye(s.result);if(s.state==="failed"||s.state==="aborted")throw new Error(String(Ye(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 b_(e,t,n){const o=Ye(await e("prepare_cold_open",{book_id:t.bookId,notebook_id:t.notebookId,asset_id:t.assetId})),r=o.status==="ready"?o:await hi(e,t.bookId,o.job_id,n),i=Nc(r.suggestion);if(!n()||i.sourceArtifactId!==t.assetId)throw new Error("Workspace changed. Reopen the cold-open review.");return{...t,suggestion:i}}async function y_(e,t,n){const o=t.suggestion;if(!o)throw new Error("Find a highlight first");const r=fi(o.startSeconds,o.endSeconds,o.durationSeconds);if(r)throw new Error(r);const i=Ye(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 hi(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 bi="nano-banana-2-1";function __(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 v_(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 k_(e,t){(!e||e.isCurrent())&&t()}function w_(e,t,n){e&&!e.isCurrent()||(e?.review(t),n())}function gt(e){return["sending","working","queued","review"].includes(e.status)}function S_(e,t=!0){if(!t&>(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&>(e)&&e.status!=="review"?`${n[e.status]} · ${o} of ${e.work.length} complete`:n[e.status]}function Gn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ue(e){return typeof e=="string"&&e?e:void 0}function ft(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 Pc(e,t,n){const o=Gn(n);if(!o)return[];const r=o.job_id??o.jobId??o.retry_job_id,i=Ue(r)??Ue(o.operation_id??o.operationId),s=Ue(o.run_id??o.runId),a=Array.isArray(o.cell_ids)?o.cell_ids:Array.isArray(t.cell_ids)?t.cell_ids:[],c=Ue((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=Ue(o.output_artifact_id??o.outputArtifactId??o.artifact_id??o.artifactId??o.asset_id??o.assetId),u=e.replaceAll("_"," ").replace(/^./u,f=>f.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":ft(o.status)}),Array.isArray(o.steps))for(const f of o.steps){const d=Gn(f);if(!(!d||!Array.isArray(d.child_job_ids)))for(const p of d.child_job_ids)typeof p=="number"&&m.push({key:`job:${p}`,jobId:p,label:Ue(d.tool)?.replaceAll("_"," ")??u,state:ft(d.status)})}return m}function Oc(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 qn(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 Lc(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:ft(a.state),detail:a.error?.message};if(i.runId&&n?.id===e.notebookId){const f=(i.cellId?[i.cellId]:Object.entries(n.execution??{}).filter(([,p])=>Gn(p)?.runId===i.runId).map(([p])=>p)).map(p=>Mc(n,p,i.runId));if(f.length&&f.every(p=>p.state==="completed"))return{...i,state:"completed"};const d=f.find(p=>p.state==="error");return d?{...i,state:"failed",detail:d.error??void 0}:{...i,state:s.some(p=>p.state!=="queued")?"working":i.state}}const c=s.find(m=>["queued","running","completing"].includes(m.state));if(c)return{...i,state:ft(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:ft(u.status)}:l&&!u?{...i,artifactId:l,state:"working"}:{...i,state:"completed"}});return qn({...e,work:r})}const I_=2400;function x_(e,t){const n=t.filter(o=>!e.has(o));return n.length===0?e:new Set([...e,...n])}function A_(e,t){const n=[...e].filter(o=>!t.includes(o));return n.length===e.size?e:new Set(n)}const Fc=new Set(["queued","running","completing"]);function yi(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 Dc(e,t,n){return gi(e)?yi(e,t,n):null}function Vc(e,t,n){const o=(n??[]).filter(r=>{if(r.type!=="await_notebook_output"||!Fc.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 Ho(e,t){const n=e?.payload?.[t];return typeof n=="string"&&n?n:null}function Wo(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:Ho(n,"providerArtifactId"),runId:Ho(n,"runId")},kind:o||n===null||n.state==="queued"?"queued":"generating"}}function E_(e){if(!gi(e.cell))return{kind:"ready"};const t=yi(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=Vc(e.cell.id,n,e.jobs);return r?Wo(e.cell,t,r,e.queuedCellIds?.has(e.cell.id)??!1):e.queuedCellIds?.has(e.cell.id)?Wo(e.cell,t,null,!0):{kind:"ready"}}function C_(e){return e==="video"||e==="generate_video"?"video":e==="image"||e==="generate_image"?"image":e==="audio"||e==="generate_audio"?"audio":"generation"}function jc(e,t){const n=[e,t].filter(o=>typeof o=="string"&&o.length>0);return n.length===0?null:n.join(" · ")}function M_(e){const t=e.error.trim()||"the provider rejected the request",n=jc(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 T_(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 _i(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.provider!=="kie"&&t.provider!=="fal"&&t.provider!=="machgen"?null:{provider:t.provider,model:typeof t.model=="string"?t.model:null,taskId:typeof t.taskId=="string"?t.taskId:null}}function De(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ne(e){return typeof e=="string"&&e?e:null}function Gc(e){const t=De(e),n=Ne(t?.taskId),o=Ne(t?.submittedAt);return!t||!n||!o?null:{taskId:n,submittedAt:o,completing:t.completing===!0}}function qc(e){return e==="off"||e==="failures"||e==="all"?e:null}function Uc(e){const t=De(e),n=qc(t?.mode);return!t||!n?null:{mode:n,hasCapture:t.hasCapture===!0,captures:typeof t.captures=="number"?t.captures:0,path:Ne(t.path),outcome:Ne(t.outcome)}}function R_(e){const t=De(e)??{},n=_i(t.providerTask),o=Uc(t.har);return{payload:t.payload??null,taskType:Ne(t.taskType),task:Gc(t.task),errorMessage:Ne(De(t.error)?.message),...n?{providerTask:n}:{},...o?{har:o}:{}}}function vi(e){const t=De(e);return t?De(t.input)??t:null}function $_(e){return Ne(vi(e)?.prompt)??Ne(De(e)?.prompt)}const Bc=new Set(["prompt","model","callBackUrl"]);function Hc(e){return typeof e=="number"||typeof e=="boolean"?String(e):typeof e!="string"||!e||/^https?:\/\//i.test(e)?null:e}function N_(e){const t=vi(e);return t?Object.entries(t).flatMap(([n,o])=>{if(Bc.has(n))return[];const r=Hc(o);return r===null?[]:[{key:n,value:r}]}):[]}function Wc(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 P_(e){const t=Wc(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"}))}async function O_(e,t,n){const o=h(await e("get_generation_har",{book_id:t,generation_id:n},{background:!0})),r=h(o?.har);if(!r)throw new Error("No HAR capture for this attempt");return{filename:b(o?.filename)||`videobook-generation-${n}.har`,text:`${JSON.stringify(r,null,2)}
|
|
6
|
+
`}}function L_(e){const t=URL.createObjectURL(new Blob([e.text],{type:"application/json"})),n=document.createElement("a");n.href=t,n.download=e.filename,n.hidden=!0,document.body.append(n),n.click(),n.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),1e4)}let Ko=0;function Jt(){return Ko+=1,Ko}function F_(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),f=_.useRef(null),d=_.useRef(null);let p,g;n[5]!==e||n[6]!==t?(p=()=>{c.current={bookId:e,notebookId:t},l.current=l.current+1,f.current=s.current.filter(M=>M.bookId===e&&M.notebookId===t).at(-1)?.id??null,d.current=null},g=[e,t],n[5]=e,n[6]=t,n[7]=p,n[8]=g):(p=n[7],g=n[8]),_.useLayoutEffect(p,g);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=d.current===null?void 0:m.current.get(d.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=Jt();f.current=q,d.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(Yc));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()&&f.current===q&&s.current.find(K=>K.id===q)?.status!=="cancelled",working:()=>J(Xc),review:K=>{K&&ge.isCurrent()?d.current=q:d.current===q&&(d.current=null),J(H=>({...H,status:K?"review":"working"}))},accept:(K,H,U)=>{const we=Pc(K,H,U);we.length&&J(Q=>qn({...Q,work:Oc(Q.work,we)}))},finish:K=>J(H=>H.status==="cancelled"?H:qn({...H,reply:K.message,executing:!1,status:K.status??(d.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=Jt(),R=l.current;f.current=M;let D=!1;for(const[q,J]of m.current)J.visible===!1&&q!==d.current&&m.current.delete(q);const z={id:M,visible:!1,isInScope:()=>l.current===R,isCurrent:()=>!D&&l.current===R&&f.current===M,working:zc,accept:Kc,finish:q=>{q.status==="cancelled"&&(D=!0)},review:q=>{q&&z.isCurrent()?d.current=M:d.current===M&&(d.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)&>(J)?Lc(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=d.current;d.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 Kc(){}function zc(){}function Xc(e){return{...e,status:"working"}}function Yc(e,t,n){return t>=n.length-256||gt(e)}const ki="data:text/javascript;base64,Y2xhc3MgVm9pY2VDYXB0dXJlIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsKICAgIHN1cGVyKCkKICAgIHRoaXMuZnJhbWVTaXplID0gTWF0aC5yb3VuZChzYW1wbGVSYXRlIC8gNTApCiAgICB0aGlzLmZyYW1lID0gbmV3IEFycmF5QnVmZmVyKHRoaXMuZnJhbWVTaXplICogMikKICAgIHRoaXMudmlldyA9IG5ldyBEYXRhVmlldyh0aGlzLmZyYW1lKQogICAgdGhpcy5vZmZzZXQgPSAwCiAgfQoKICBwcm9jZXNzKGlucHV0cykgewogICAgY29uc3Qgc2FtcGxlcyA9IGlucHV0c1swXT8uWzBdCiAgICBpZiAoIXNhbXBsZXMpIHJldHVybiB0cnVlCiAgICBmb3IgKGNvbnN0IHNhbXBsZSBvZiBzYW1wbGVzKSB7CiAgICAgIGNvbnN0IGNsYW1wZWQgPSBNYXRoLm1heCgtMSwgTWF0aC5taW4oMSwgc2FtcGxlKSkKICAgICAgdGhpcy52aWV3LnNldEludDE2KHRoaXMub2Zmc2V0ICogMiwgY2xhbXBlZCAqIChjbGFtcGVkIDwgMCA/IDMyNzY4IDogMzI3NjcpLCB0cnVlKQogICAgICB0aGlzLm9mZnNldCArPSAxCiAgICAgIGlmICh0aGlzLm9mZnNldCA9PT0gdGhpcy5mcmFtZVNpemUpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5mcmFtZSwgW3RoaXMuZnJhbWVdKQogICAgICAgIHRoaXMuZnJhbWUgPSBuZXcgQXJyYXlCdWZmZXIodGhpcy5mcmFtZVNpemUgKiAyKQogICAgICAgIHRoaXMudmlldyA9IG5ldyBEYXRhVmlldyh0aGlzLmZyYW1lKQogICAgICAgIHRoaXMub2Zmc2V0ID0gMAogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZQogIH0KfQoKcmVnaXN0ZXJQcm9jZXNzb3IoJ3ZpZGVvYm9vay12b2ljZS1jYXB0dXJlJywgVm9pY2VDYXB0dXJlKQo=";class Jc{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(ki),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),p=>p.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 p=0;p<u.length;p+=1)u[p]=c.getInt16(p*2,!0)/32768;const m=Math.max(r.currentTime+.015,this.nextAt);this.nextAt=m+l.duration;let f=this.items.find(p=>p.itemId===o);if(!f){f={responseId:n,itemId:o,startAt:m,duration:0},this.items.push(f);const p=window.setTimeout(()=>{this.timers.delete(p),this.stopped||this.options.onStarted(n)},Math.max(0,(m-r.currentTime)*1e3));this.timers.add(p)}f.duration+=l.duration;const d=r.createBufferSource();d.buffer=l,d.connect(i),this.sources.add(d),d.onended=()=>{d.disconnect(),this.sources.delete(d),!this.stopped&&this.sources.size===0&&this.completed.has(n)&&(this.options.onFinished(n),this.items=[],this.completed.clear())},d.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 Zc="videobook-voice";class Qc{connectAt=0;permissionStartAt=0;permissionEndAt=0;utteranceEndAt=0;turnAt=0;extra={};setSession(t){this.extra={...this.extra,...t}}mark(t,n){performance.mark(Zc,{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 wi(e){return e!=="xai"}function el(e){const t={bookId:e.bookId,mode:e.mode,sampleRate:e.sampleRate};return e.notebookId&&(t.notebookId=e.notebookId),wi(e.mode)&&e.sdp&&(t.sdp=e.sdp),{url:"/api/voice",body:t}}function vn(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 tl{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 Qc;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(ki).catch(()=>{});const o=!wi(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(vn(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}=el({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 Jc({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(`
|
|
7
|
+
`);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(vn(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(vn(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 nl=6e4;function ol(e){return e.text.trim().length>0||!!e.interrupted}function D_(e,t,n=[],o=[]){const r=e.filter(ol).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&>(u.turn))}function V_(e){return e.at(-1)?.sequence??0}function j_(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 G_(e){if(e.runningCalls>0)return!0;switch(e.voicePhase){case"connecting":case"thinking":case"speaking":case"review":return!0;default:return!1}}function q_(e){if(!e.open||e.held)return()=>{};const t=e.setTimeoutFn??setTimeout,n=e.clearTimeoutFn??clearTimeout,o=t(e.onClose,e.delayMs??nl);return()=>{n(o)}}function U_(e,t,n){return t>0?!1:n?e==="off"||e===void 0:!0}const Si="videobook.voice-provider";function rl(){try{const e=localStorage.getItem(Si);return e==="openai"||e==="xai"?e:"auto"}catch{return"auto"}}function B_(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,f]=_.useState(!1),[d,p]=_.useState(!1),[g,y]=_.useState(rl),[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),f(!1),p(!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=()=>{f(!1),p(!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]!==g?(R=()=>{if(E.current?.active){M();return}const U=C.current;if(!U.available||U.disabled)return;S(null),k(void 0),p(!1),o("connecting"),i("Connecting voice");const we=new Set,Q=new tl({bookId:U.bookId,notebookId:U.notebookId,mode:g,onProvider:(B,P)=>{E.current===Q&&(S(B),k(P))},onPhase:(B,P)=>{E.current!==Q&&B!=="off"||(o(B),(B==="off"||B==="error")&&f(!1),B!=="thinking"&&p(!1),P&&i(P))},onRetrying:B=>{E.current===Q&&p(B)},onCaption:B=>{E.current===Q&&(B.role==="user"&&B.final&&B.text.trim()&&!we.has(B.id)&&(we.add(B.id),C.current.onUserTurn?.()),c(P=>{const Y=P.findIndex(Se=>Se.id===B.id);if(Y<0)return[...P,{...B,sequence:B.sequence??Jt()}].slice(-256);const Me=P[Y]?.sequence??B.sequence;return P.map(Se=>Se.id===B.id?{...B,sequence:Me}:Se)}))},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."};f(!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(sl);return E.current===Q&&f(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(il);return E.current===Q&&f(P.status==="review"),P},onLevel:B=>I.current?.style.setProperty("--voice-level",String(B)),onPlaybackBlocked:u});E.current=Q,Q.start()},t[10]=g,t[11]=R):R=t[11];const D=R;let z;t[12]!==g?(z=U=>{if(U!==g){f(!1),p(!1),E.current?.stop("Voice provider changed. Start voice to connect."),y(U),S(null),k(void 0);try{localStorage.setItem(Si,U)}catch{return}}},t[12]=g,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"&&f(!1),E.current?.reportOutcome(U)},ge=(U,we)=>E.current?.shareTypedTurn(U,we),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]!==g||t[21]!==m||t[22]!==n||t[23]!==l||t[24]!==v||t[25]!==d||t[26]!==z||t[27]!==q||t[28]!==J||t[29]!==D?(H={phase:n,message:r,captions:a,playbackBlocked:l,pendingReview:m,retrying:d,meterRef:I,toggle:D,stop:M,mode:g,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]=g,t[21]=m,t[22]=n,t[23]=l,t[24]=v,t[25]=d,t[26]=z,t[27]=q,t[28]=J,t[29]=D,t[30]=H):H=t[30],H}function il(e){return{status:"failed",message:e instanceof Error?e.message:"The review command failed."}}function sl(e){return{status:"failed",message:e instanceof Error?e.message:"Voice action failed."}}async function al(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 cl=1;function Ii(e){if(e.planVersion!==cl)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 H_(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]),[f,d]=_.useState(null),p=_.useRef(0);_.useEffect(()=>{const w={key:r,active:!0,pending:!1};return i.current=w,()=>{w.active=!1}},[r]);async function g(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=++p.current;await g(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!==p.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);d(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 g(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 al(o),edits:[w]});if(Ii(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($),d(null))})}async function S(w,k){await g(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:f?.scope===r?f:null,openPicker:w=>y(w,0,!1),loadMore:()=>f?.offset!==null&&f?y(f.trackId,f.offset,!0):Promise.resolve(),closePicker:()=>{p.current+=1,d(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 zo=te({timeSeconds:V().finite().nonnegative(),confidence:V().min(0).max(1).nullable()}),ll=te({algorithmId:j().min(1),algorithmVersion:j().min(1),hopSeconds:V().finite().positive(),values:ae(V().finite().min(0).max(1)).max(2e4)}),ul=te({id:j().min(1).max(100),timeSeconds:V().finite().nonnegative().max(3600),quality:V().min(0).max(1)}),dl=te({algorithmId:j().min(1),algorithmVersion:j().min(1),candidates:ae(ul).max(200)}),fl=te({analysisId:j(),artifactId:j().uuid(),objectHash:j(),streamId:j().uuid(),durationSeconds:V().finite().positive().max(3600),analyzerVersion:j(),beats:ae(zo).max(24e3),bpm:V().finite().positive().nullable(),confidence:V().min(0).max(1).nullable(),bars:ae(zo).max(24e3).nullable(),beatsPerBar:V().int().min(1).max(16).nullable(),barSource:Ze(["detected","estimated"]).nullable().default(null),waveform:ae(V().finite().min(0).max(1)).max(65536),lowConfidence:Te(),energy:ll.nullable().default(null),sections:dl.nullable().default(null)}),ml=["intro","verse","chorus","drop","break","bridge","outro"];te({schemaVersion:ai(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:Ze(["ready","unavailable"]),reason:j().nullable().default(null),createdAt:V().finite().positive(),labels:ae(te({candidateId:j().min(1).max(100),label:Ze(ml),confidence:V().min(0).max(1),rationale:j().max(500)})).max(200).default([])});const pl=te({id:j().min(1).max(100),timeSeconds:V().finite().nonnegative().max(3600),bar:Te(),manual:Te()}),gl=te({masterClipId:j().uuid().nullable(),correction:te({objectHash:j(),analysisId:j().nullable(),markers:ae(pl).max(24e3),bpm:V().finite().min(20).max(400).nullable(),beatsPerBar:V().int().min(1).max(16).nullable()}).nullable()});function kn(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 hl(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 bl(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 W_(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=bl(r,o);return r.map((a,c)=>({...a,bar:(s[c]-s[i])%n===0,manual:!0}))}function Xo(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 yl(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 _l(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:yl(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 K_(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 z_(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=Xo(i,e.timelineStartFrame+a/r*e.durationFrames,o),l=Xo(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 f=0;for(let d=u;d<m;d++)f=Math.max(f,t[d]??0);return f})}const Yo={revision:"none",settings:{masterClipId:null,correction:null},canUndo:!1,canRedo:!1};function Jo(e){const t=h(e);if(!t||typeof t.revision!="string")throw new Error("Invalid beat map response");return{revision:t.revision,settings:gl.parse(t.settings),canUndo:t.canUndo===!0,canRedo:t.canRedo===!0}}function Zo(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?fl.parse(t.analysis):null}}function X_({bookId:e,ready:t,sequence:n,call:o,onSequence:r}){const i=`${e}:${n?.sequenceId??""}`,s=_.useRef(0),[a,c]=_.useState({scope:i,rhythm:Yo,analysis:null}),[l,u]=_.useState({scope:i,busy:!1,error:""});_.useEffect(()=>()=>{s.current+=1},[i]);const m=a.scope===i?a.rhythm:Yo,f=n?kn(n,m.settings):null,d=a.scope===i&&a.analysis?.analysis?.artifactId===f?.source.artifactId?a.analysis?.analysis??null:null,p=_.useMemo(()=>hl(f,m.settings,d),[f,m.settings,d]),g=_.useMemo(()=>n?_l(f,p,n):[],[f,p,n]),y=a.scope===i?a.analysis?.status??"missing":"missing";async function v(A,$=n){if(!$)return null;const T=kn($,A);return T?Zo(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=kn($,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 $=Jo(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=Jo(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||!f)return;const $=++s.current;u({scope:i,busy:!0,error:""});const T={book_id:e,asset_id:f.source.artifactId,stream_id:f.source.range.streamId};try{const N=Zo(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:f,analysis:d,markers:p,mapped:g,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 Un=[{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 vl(e,t){const n=Un.find(o=>o.kind===e);return n?`${t} ${t===1?n.one:n.many}`:`${t} ${e}`}function kl(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function wl(e){const t=new Map;for(const r of e)t.set(r.kind,(t.get(r.kind)??0)+1);const o=[...Un.filter(r=>t.has(r.kind)).map(r=>r.kind),...[...t.keys()].filter(r=>!Un.some(i=>i.kind===r))].map(r=>vl(r,t.get(r)??0));return o.length>0?kl(o):"something else in this book"}function Sl(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 Y_(e,t){const n=[t.reclaimedBytes>0?`${Sl(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 J_(e){return`Forget ${e}?
|
|
8
|
+
|
|
9
|
+
This deletes the asset and destroys its stored content. Files shared with another asset are kept. This cannot be undone.`}function Z_(e,t){return`${e} is still used by ${wl(t)}.
|
|
10
|
+
|
|
11
|
+
Clear those references and forget it anyway?`}const Il=[{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"]}],xl=[{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"]}],Al=[{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"]}],El={people:Il,places:xl,editing:Al,custom:[]},Qo=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 xi(e){return e.normalize("NFKC").toLowerCase().replace(/[_/]+/gu," ").replace(/[^\p{L}\p{N}\s-]+/gu,"").replace(/\s+/gu," ").trim()}const Cl=new Map(Object.entries(El).flatMap(([e,t])=>t.flatMap(n=>[n.label,...n.aliases].map(o=>[`${e}:${xi(o)}`,{facet:e,label:n.label}]))));function Ai(e,t=[]){const n=Zs(e.label),o=Ht(n),r=e.facet?[e.facet]:["people","places","editing"];for(const s of r){const a=Tl(s,n);if(a)return{...a,label:Ht(a.label)===o?n:a.label}}const i=!e.facet&&t.find(s=>Ht(s.label)===o);return{facet:e.facet??(i?i.facet:"custom"),label:n}}function Ml(e){if(Qo.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)&&!Qo.has(n)&&!["not","without","never","maybe","possibly"].includes(n))}function Tl(e,t,n={}){const o=xi(t);if(!o||o.length>40)return null;const r=Cl.get(`${e}:${o}`);return r||(n.allowUnlisted&&e==="places"&&Ml(o)?{facet:e,label:o}:null)}const Rl={effective:[],manual:[],automatic:[],dismissed:[],analysis:null,fingerprint:""};function po(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function Re(e){return typeof e=="string"&&e.trim()?e:null}function $l(e){return typeof e=="string"&&ti.includes(e)?e:null}function Kt(e){const t=po(e),n=$l(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 Nl(e){const t=Kt(e);return t?{facet:t.facet,key:t.key,label:t.label}:null}function Nt(e,t){return Array.isArray(e)?e.flatMap(n=>{const o=t(n);return o?[o]:[]}):[]}function Pl(e){const t=po(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 Ei(e){const t=po(e);return t?{effective:Nt(t.effective,Kt),manual:Nt(t.manual,Kt),automatic:Nt(t.automatic,Kt),dismissed:Nt(t.dismissed,Nl),analysis:Pl(t.analysis),fingerprint:Re(t.fingerprint)??""}:null}function wn(e){const t=new Map(ti.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 Ci(e,t){return`${e}/${t}`}function Ol(e){return e.trim()?Ht(e):""}function le(e){return Ci(e.facet,e.key)}function Q_(e){return e.origin==="manual"?"Added by you":"From analysis"}function Be(e,t){return e.filter(n=>le(n)!==t)}function er(e,t,n){const o=e??Rl;if(!t.label.trim())return o;t=Ai(t,[...o.effective,...o.dismissed]);const r=Ol(t.label);if(!r)return o;const i=t.facet??"custom",s=Ci(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:Be(o.dismissed,s),manual:wn([...o.manual,l]),effective:wn([...Be(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:Be(o.effective,s),manual:Be(o.manual,s),dismissed:[...Be(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:Be(o.dismissed,s),effective:c?wn([...o.effective,c]):o.effective}}function ev(e,t){const n=le(t);return e.some(r=>le(r)===n)?e.filter(r=>le(r)!==n):[...e,t]}function tv(e){return{facet:e.facet,key:e.key,label:e.label}}function nv(e){return e.length===0?{}:{tags_all:e.map(t=>({facet:t.facet,label:t.label}))}}function ov(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 Ll(e,t,n=8){const o=new Set(t.map(le));return e.filter(r=>!o.has(le(r))).slice(0,n)}const rv={calls:[]},iv=420,tr=140,nr=400,Fl={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"},Dl=new Set(["get_notebook","list_chat_models","list_jobs","list_prompt_history","list_workspace_actions","slash_commands"]);function sv(e){return!Dl.has(e)}function av(e){const t=Fl[e];return t||e.split("_").filter(Boolean).map(n=>n[0]?.toUpperCase()+n.slice(1)).join(" ")}function Zt(e,t){const n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t)}… (${n.length} chars)`}function Vl(e){if(typeof e=="string")return Zt(e,tr);if(typeof e=="number"||typeof e=="boolean")return String(e);try{return Zt(JSON.stringify(e)??String(e),tr)}catch{return String(e)}}function cv(e){return Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>({name:t,value:Vl(n)}))}function lv(e){if(typeof e=="string")return Zt(e,nr);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 Zt(t[n],nr);return""}function jl(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 uv(e){return e.phase==="running"?"working":e.phase==="failed"?"failed":jl(e.elapsedMs)}function dv(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 fv(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 mv(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 pv(e){return e.calls.filter(t=>t.phase==="running").length}function gv(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 hv(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 bv(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 Mi(e,t=e.length,n=t){if(t!==n)return null;const o=an(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 yv(e,t,n=t.length,o=n,r){const i=Mi(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 _v(e,t,n=e.length,o=n){const r=Mi(e,n,o);if(!r)return null;const i=`@${ke(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 vv(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 kv(e){return e.handler.kind==="tool"&&["list_entities","list_notebooks","asset_history","list_book_actions","search_archive"].includes(e.handler.tool)}function go(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function wv(e){const t=go(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 Sv(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??Gl(s),required:i.inputSchema.required?.includes(s)??!1,type:a.type==="number"||a.type==="integer"?"number":a.type==="boolean"?"boolean":"string"}))}))]}function Iv(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 Gl(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 Ti(e){const t=e.oneOf??e.anyOf;return t?t.flatMap(n=>{const o=Ti(n);return o.length?o:[n]}):[]}function ql(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=go(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 Ul(e,t){const n=Ti(e);if(!n.length)return e;const o=n.find(a=>ql(a,t))??n.find(a=>a.type!=="null")??n[0],{anyOf:r,oneOf:i,...s}=e;return{...s,...o}}function Bn(e,t=!1){if("const"in e)return e.const;if(e.default!==void 0)return structuredClone(e.default);if(!t)return;const n=Ul(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,Bn(i,o.has(r))]).filter(([,r])=>r!==void 0))}if(n.type==="array")return Array.from({length:n.minItems??0},()=>Bn(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 xv(e,t){const n=go(Bn(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 Av(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 Ev(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 Pt=new Qs({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 ni(t)?{token:t}:!1}}]}}});function Bl(e,t=!0){const n=[];let o=0;if(t)for(const r of co(e))r.index>o&&n.push(Pt.text(e.slice(o,r.index))),n.push(Pt.nodes.reference.create({token:r.raw})),o=r.end;return o<e.length&&n.push(Pt.text(e.slice(o))),Pt.nodes.doc.create(null,n)}function or(e,t=0,n=e.content.size){return e.textBetween(t,n,"",o=>String(o.attrs.token??""))}function Cv(e,t,n){return{start:or(e,0,Math.min(t,n)).length,end:or(e,0,Math.max(t,n)).length,backward:t>n}}function rr(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 Hl(e,t,n=1){const o=rr(e.doc,t.start,t.start===t.end?n:-1),r=rr(e.doc,t.end,n);return e.setSelection(ea.create(e.doc,t.backward?r:o,t.backward?o:r))}function Mv(e,t,n,o=!0){const r=Bl(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 Hl(e,n)}function Ot(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 ir(e,t){return e.lastIndexOf(`
|
|
12
|
+
`,Math.max(0,t-1))+1}function sr(e,t){const n=e.indexOf(`
|
|
13
|
+
`,t);return n===-1?e.length:n}function ar(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 Wl(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 Tv(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=ar(t,n);return{value:t,selectionStart:l,selectionEnd:l}}if(s&&c==="f"){const l=Wl(t,o);return{value:t,selectionStart:l,selectionEnd:l}}if(!i)return null;if(c==="a"){const l=ir(t,n);return{value:t,selectionStart:l,selectionEnd:l}}if(c==="e"){const l=sr(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 Ot(t,n,o,a);if(c==="k"){const l=n===o?Math.min(t.length,sr(t,o)+1):o;return{...Ot(t,n,l,""),killedText:t.slice(n,l)}}if(c==="u"){const l=n===o?ir(t,n):n;return{...Ot(t,l,o,""),killedText:t.slice(l,o)}}if(c==="w"){const l=n===o?ar(t,n):n;return{...Ot(t,l,o,""),killedText:t.slice(l,o)}}return null}const Ri="videobook.elevenlabs-voice",Kl="/speak ";function zl(e){return/^\/speak(\s|$)/.test(e)}function Rv(e,t){return t&&e.some(n=>n.voiceId===t)?t:e[0]?.voiceId??""}function cr(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 $v(){return typeof window>"u"?null:window.localStorage.getItem(Ri)}function Nv(e){typeof window>"u"||!e||window.localStorage.setItem(Ri,e)}function Pv(e,t,n){return e.key==="ArrowDown"?{type:"select",voiceId:cr(t,n,1)}:e.key==="ArrowUp"?{type:"select",voiceId:cr(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 Ov(e,t){if(!(!zl(e)||!t))return{speakVoiceId:t}}function Lv(e){if(e.command==="/voices")return{kind:"prefill",nextInput:Kl,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 Fv(e,t){const n=e.trim().toLowerCase();return t.some(o=>[o.label,...o.aliases??[]].some(r=>r.toLowerCase()===n))}function Dv(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 Vv(e){const t=e.match(/^\s*\/apply(?:\s+([\s\S]*?))?\s*$/iu);return t?{promptOverride:(t[1]?.trim()??"")||null}:null}function jv(e,t){const n=e.nextInput??(e.ok?void 0:t);return n===void 0?null:{value:n,select:e.selectInput??!e.ok}}function Gv(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 zt="videobook.composer-drafts.v1",Xl=50,$i=1e6;function Ni(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>$i)&&(t.push([i,s]),o+=s.length,t.length===Xl)))break}return t.reverse()}function qv(){if(typeof window>"u")return new Map;try{const e=window.sessionStorage.getItem(zt);if(!e||e.length>$i*6+1e4)return new Map;const t=JSON.parse(e);return new Map(Array.isArray(t)?Ni(t):[])}catch{return new Map}}function Uv(e,t,n){if(typeof window>"u")return;const o=new Map(e);o.delete(t),o.set(t,n);const r=Ni([...o]);try{r.length===0?window.sessionStorage.removeItem(zt):window.sessionStorage.setItem(zt,JSON.stringify(r))}catch{try{window.sessionStorage.removeItem(zt)}catch{return}}}const lr=new WeakMap,dn='.command-composer [aria-label="Videobook command input"]',Pi='input:not([type="file"]), textarea, select, [contenteditable="true"], video[controls], audio[controls]',Yl='dialog[open], :popover-open, [aria-modal="true"], [role="menu"], details.canvas-add-menu[open]';function nt(e){const t=lr.get(e);if(t)return t;const n={epoch:0,scope:"",enabled:!1,composerOwnedFocus:!1,modality:"initial",pending:null,frame:null};return lr.set(e,n),n}function Jl(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(Yl)].at(-1);if(r&&!r.contains(o))return;const i=e.activeElement;if(i&&i!==o&&i.matches(Pi)&&!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 ho(e,t){t.frame!==null&&e.defaultView?.cancelAnimationFrame(t.frame),t.frame=e.defaultView?.requestAnimationFrame(()=>{t.frame=null,Jl(e,t)})??null}function Hn(e,t){t.pending={epoch:t.epoch,scope:t.scope,resolve:()=>e.querySelector(dn)},ho(e,t)}function fn(e=()=>document.querySelector(dn),t){const n=document,o=nt(n),r={epoch:o.epoch,scope:o.scope,resolve:e,afterFocus:t};return()=>{o.epoch!==r.epoch||o.scope!==r.scope||(o.pending=r,ho(n,o))}}function Bv(){return nt(document).modality==="pointer"?fn():()=>{}}function Hv(e){const t=nt(document).modality==="pointer",n=!!e?.closest(".command-composer");return fn(()=>{const o=document.querySelector(dn);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 Wv(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(Zl,o);let r,i;n[1]!==t||n[2]!==e?(r=()=>{const s=nt(document),a=s.scope!==e,c=!s.enabled&&t;if(s.scope=e,s.enabled=t,a&&(s.pending=null),!!t){if(s.pending){ho(document,s);return}if(a||c){if(c&&s.composerOwnedFocus&&s.modality!=="touch"&&document.activeElement===document.body){Hn(document,s);return}s.modality==="initial"&&document.activeElement!==document.body||s.modality!=="initial"&&!(a&&s.modality==="pointer")||window.matchMedia("(pointer: fine)").matches&&Hn(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 Zl(){const e=nt(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(dn)},i=s=>{if(s.detail===0||e.modality!=="pointer")return;const a=s.target;!(a instanceof Element)||a.closest(Pi)||a.closest("[data-composer-focus]")?.getAttribute("data-composer-focus")==="return"&&Hn(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 Ql(){const e=nt(document);e.epoch+=1,e.pending=null}function Kv(e){Ql();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 zv(e,t=n=>window.requestAnimationFrame(n)){if(typeof document>"u"){t(()=>e()?.focus({preventScroll:!0}));return}fn(e)()}function eu(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 Xv(e){const t=eu(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 Yv(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 tu=/page is hidden|paused for media playback|You are offline/i;function nu(e,t){return t?e==="connecting"||e==="thinking"||e==="listening"||e==="speaking":!1}function ou(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||nu(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"&&tu.test(e.voiceMessage??"")?{kind:"paused",label:"Voice paused. Start voice to resume.",busy:!1}:{kind:"idle",label:t==="off"?"Offline":"",busy:!1}}const ru=new Set(["idle","listening","review"]);function iu(e){return!ru.has(e.kind)&&e.label!==""}function Jv(e){if(!e)return null;const t=ou({sending:!1,mcpRunning:0,voicePhase:e.phase,voiceMessage:e.message,retrying:e.phase!=="off"&&e.retrying,pendingReview:e.pendingReview}),n=iu(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 Oi=e=>new Audio(e);function su(e=Oi){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 Zv(e){const t=ne.c(13),n=Oi;let o;t[0]!==n?(o=()=>su(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 p=r.subscribe(s);return()=>{p(),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=(p,g)=>{r.toggle(p,g)},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 f=m;let d;return t[9]!==i||t[10]!==f||t[11]!==u?(d={playingVoiceId:i,toggle:u,stop:f},t[9]=i,t[10]=f,t[11]=u,t[12]=d):d=t[12],d}const au=["auto","openai","xai"],Li={auto:"Auto",openai:"OpenAI",xai:"xAI"},cu={auto:"Tries OpenAI, then xAI if it cannot connect",openai:null,xai:null};function Qv(e){return Li[e]}function lu(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 uu(e,t){const n=e.voiceMode;return n?au.map((o,r)=>({id:`speech:${o}`,position:t+r,label:Li[o],detail:null,note:cu[o],checked:o===n,choice:{kind:"speech",mode:o}})):[]}function ek(e){const t=[],n=lu(e);n.length>0&&t.push({id:"model",label:"Chat model",items:n});const o=uu(e,n.length);return o.length>0&&t.push({id:"speech",label:"Speech",items:o}),t}function tk(e){return e.flatMap(t=>t.items)}function nk(e){const t=e.findIndex(n=>n.checked);return t===-1?0:t}function ok(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 rk="Collapse chat";function ik(e){return e==="selection"||e==="action"||e==="expand"||e==="reopen"}function sk(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 ak(e){return e}function ck(e){e.stopVoice?.(),e.pauseMedia?.(),e.setOpen(!1)}function lk(e){if(e)for(const t of e.querySelectorAll("video, audio"))t instanceof HTMLMediaElement&&t.pause()}function uk(e){return e==="applied"||e==="timeline"?"media":"music"}function dk(e){return e.dockOpen&&e.panelHasHeader&&!e.reviewPriority}function fk(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 Fi(e){return{row:Math.round(e.row),column:Math.round(e.column)}}function Ve(e){const t=Fi(e);return{row:Math.min(de-1,Math.max(0,t.row)),column:Math.min(X-1,Math.max(0,t.column))}}function ve(e){return`${e.row}:${e.column}`}function du(e){return Ve({row:Math.round((e.y-O.originY)/O.rowPitch),column:Math.round((e.x-O.originX)/O.columnPitch)})}function Qe(e){const t=Ve(e);return{x:O.originX+t.column*O.columnPitch,y:O.originY+t.row*O.rowPitch}}function mk(e,t,n){const o=e.find(i=>i.id===t),r=Ve(o?.data.kind==="timeline"?{...n,column:0}:n);return e.map(i=>i.id===t?{...i,position:Qe(r)}:i)}function fu(e,t,n){const o=e.find(c=>c.id===t);if(!o)return[...e];const r=Ve(o.data.kind==="timeline"?{...n,column:0}:n),i=o.data.slot,s=new Set(Ee({type:String(o.data.kind),slot:r}).map(ve)),a=e.find(c=>c.id!==t&&Ee({type:String(c.data.kind),slot:c.data.slot}).some(l=>s.has(ve(l))));return a&&(o.data.kind==="timeline"||a.data.kind==="timeline")?e.map(c=>c.id===t?{...c,position:Qe(i)}:c):e.map(c=>{const l=c.id===t?r:c.id===a?.id?i:null;return l?{...c,position:Qe(l),data:{...c.data,slot:l}}:c})}function pk(e,t,n,o){const r=new Set(n);r.add(t);const i=e.filter(d=>r.has(d.id));if(i.length<=1)return fu(e,t,o);const s=i.find(d=>d.id===t);if(!s)return[...e];const a=Fi(o),c=a.row-s.data.slot.row,l=a.column-s.data.slot.column,u=new Map(i.map(d=>{const p={row:d.data.slot.row+c,column:d.data.slot.column+l};return[d.id,p]})),m=new Set(i.flatMap(d=>Ee({type:String(d.data.kind),slot:u.get(d.id)})).map(ve));return[...u.values()].some(d=>!oa(d))||i.some(d=>d.data.kind==="timeline"&&l!==0)||e.some(d=>!r.has(d.id)&&Ee({type:String(d.data.kind),slot:d.data.slot}).some(p=>m.has(ve(p))))?e.map(d=>r.has(d.id)?{...d,position:Qe(d.data.slot)}:d):e.map(d=>{const p=u.get(d.id);return p?{...d,position:Qe(p),data:{...d.data,slot:p}}:d})}function gk(e,t){const n=new Map(e.map(o=>[o.id,ve(o.data.slot)]));return t.filter(o=>n.get(o.id)!==ve(o.data.slot))}const mu=new Set(["image","generate_image","character"]);function pu(e){return mu.has(e)}function bo(e){return e?Ve(e):null}const gu=new Set(["generate_image","generate_audio","extract_audio"]);function yo(e,t=[],n=null){const o=Xe(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 Do(s,c,o)}const r=bo(n);if(r)return Vn(r,o);let i=-1;for(const s of e)pu(s.type)&&s.slot.row>i&&(i=s.slot.row);return Do(i+1,0,o)}function mn(e,t=[],n=null){const o=Xe(e);if(t.length===0){const a=bo(n);return Dn(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 Dn(s,o)}function hk(e,t,n=null){if(e==="timeline")return ta(Xe(t));if(e==="generate_video")return yo(t,[],n);if(gu.has(e))return mn(t,[],n);const o=bo(n);return o?Dn(o,Xe(t)):na(Xe(t))}function pn(e){return Number.isFinite(e)&&e>0?e:1}function bk(e){return 1/Math.max(pn(e),O.detailZoomFloor)}function hu(e,t=0){return!Number.isFinite(e)||e<=0?1:Math.max(Number.isFinite(t)?t:0,e/Di())}function Di(){return O.originX*2+X*O.squareSize+(X-1)*O.gap}function bu(e,t){if(!Number.isFinite(e)||e<=0)return O.minimumRowCount;const n=e/pn(t);return Math.max(O.minimumRowCount,Math.ceil((n-O.originY*2+O.gap)/O.rowPitch))}function yk(e,t){const n=pn(t);return{width:e.width*n,height:e.height*n}}function _k(e,t,n=0){return{x:0,y:Number.isFinite(n)?n:0,zoom:pn(t)}}function vk(e,t){return du(e)}function kk(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 wk(e,t={}){const n=t.preview?[...e,Ve(t.preview)]:e,o=Math.max(-1,...n.map(a=>Ve(a).row)),r=Math.min(de,Math.max(O.minimumRowCount,bu(t.viewportHeight??0,t.zoom??1),o+2)),i=Di(),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 Vi="post_to_x";function Ge(e){return e?.inputs?.sourceOperation===Vi}function yu(){return"X · POSTED"}function _u(e){const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString().replace("T"," ").replace(/\.\d{3}Z$/," UTC"):e}function vu(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 ku(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 Sk(e){if(e?.sourceOperation!==Vi)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=vu(s);return a?[a]:[]}):[],i=e.status==="partially_posted"?"partially_posted":"posted";return{badge:"Posted to X",tweetId:t,tweetUrl:n,postedAt:o,postedAtLabel:_u(o),replyCount:r.length,replyLabel:r.length===1?"1 reply":`${r.length} replies`,replies:r,status:i,followupError:ku(e.followupError??e.followup_error)}}const wu={run_notebook:"Run notebook",semantic_index:"Semantic index",extract_waveform:"Extract waveform",extract_video_poster:"Create video poster",assess_video_proxy:"Check video proxy",backfill_media_duration:"Measure media duration",extract_audio:"Extract audio",transcribe:"Transcribe"},Su={attention:"Needs attention",running:"Running",queued:"Queued",finished:"Finished"},Iu=["attention","running","queued","finished"];function _o(e){const t=wu[e];if(t)return t;const n=e.replace(/[_-]+/g," ").trim();return n.length===0?e:n.charAt(0).toUpperCase()+n.slice(1)}function ur(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 vo(e){return e.slice(0,8)}function xu(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 Au(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 ji(e){switch(e){case"review":case"failed":return"attention";case"running":return"running";case"queued":return"queued";default:return"finished"}}function Gi(e){return e.toUpperCase()}function qi(e){return e?{tag:ue(e.slot),label:e.label??e.prompt??null}:{tag:null,label:null}}function Eu(e,t){if(!e.artifactId)return{tag:null,label:null};const n=t.find(o=>!Ge(o)&&o.outputArtifactId===e.artifactId);return n?qi(n):{tag:null,label:`artifact ${vo(e.artifactId)}`}}function dr(e,t){const n=e?.[t];return typeof n=="string"&&n.trim().length>0?n:null}function Cu(e){const t=[dr(e.payload,"provider"),dr(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 Tu(e,t){const n=e.startedAt===null?null:ur((e.finishedAt??t)-e.startedAt);switch(e.state){case"queued":return{summary:"Waiting for a worker",note:`waiting ${ur(t-e.enqueuedAt)}`,duration:null,live:!1};case"running":return{summary:`${_o(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 Ru(e){const t=e.error?.code??null;return t&&t!=="Error"?t:null}function $u(e,t,n){const o=xu(e.state),r=o==="done"&&e.state!=="done"?e.state.toUpperCase():Gi(o),i=e.error?[`${e.error.code?`${e.error.code} · `:""}${e.error.message}`,`operation ${e.operationId} · enqueued ${new Date(e.enqueuedAt).toLocaleString()}`].join(`
|
|
14
|
+
`):null;return{key:`job:${e.id}`,providerTask:e.providerTask,source:{kind:"job",jobId:e.id},tone:o,band:ji(o),statusLabel:r,title:_o(e.type),detail:Cu(e),target:Eu(e,t),...Tu(e,n),errorCode:Ru(e),errorDetail:i,attempt:`${e.attempts}/${e.maxAttempts}`,timestamp:e.enqueuedAt,sortAt:e.finishedAt??e.startedAt??e.enqueuedAt,actions:Mu(e.state)}}function Ui(e){const t=e.plan.stages.find(n=>n.kind==="queued"&&n.jobType==="generation");return t?.kind==="queued"?t:null}function Nu(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 Pu(e){const t=Ui(e),n=[];return t?.estimatedCostUsd!==void 0&&n.push(`est. $${t.estimatedCostUsd.toFixed(2)}`),e.outputArtifactId&&n.push(`output ${vo(e.outputArtifactId)}`),n.length>0?n.join(" · "):null}function Ou(e,t){const n=Pu(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 ${vo(e.outputArtifactId)}`:null};default:return{summary:"Generation finished",note:n}}}function Sn(e){const t=Date.parse(e);return Number.isFinite(t)?t:0}function Lu(e,t,n){return t?.type.startsWith("generate_")?_o(t.type):n?"Generate":e.plan.summary}function Fu(e,t,n){const o=n.some(c=>c.artifactId===e.outputArtifactId&&c.status==="ready"&&!!c.mediaUrl),r=Au(e.status,o),i=Ui(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:ji(r),statusLabel:Gi(r),title:Lu(e,s,i),detail:a&&a.length>0?a:null,target:qi(s),...Ou(e,o),errorCode:null,errorDetail:e.error,attempt:"1/1",timestamp:Sn(e.createdAt),sortAt:Sn(e.updatedAt)||Sn(e.createdAt),duration:null,live:r==="running",actions:Nu(e,o)}}function Ik({jobs:e,plans:t,cells:n,assets:o=[],now:r}){return[...t.map(i=>Fu(i,n,o)),...e.map(i=>$u(i,n,r))]}function Du(e){return e.map((t,n)=>({...t,summary:n===0?"Next up":`${n} ahead in queue`}))}function Vu(e,t){switch(e){case"running":return[...t].sort((n,o)=>n.sortAt-o.sortAt);case"queued":return Du([...t].sort((n,o)=>n.timestamp-o.timestamp));default:return[...t].sort((n,o)=>o.sortAt-n.sortAt)}}function xk(e){return Iu.map(t=>({id:t,label:Su[t],rows:Vu(t,e.filter(n=>n.band===t))}))}function Ak(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 Ek(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],ju=[.25,.5,.75],Bi={sourceSide:"bottom",sourcePortIndex:1,targetSide:"top",targetPortIndex:1,sourceBusOffset:Ae[1],targetBusOffset:Ae[1],riverOffset:Ae[1],riverSide:"right",directRowGutter:!1,targetPrimary:!0};function Ct(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 ko(e,t){return t===1?1:t===2?e%2===0?0:2:e%Ae.length}function Hi(e,t){return Ae[ko(e,t)]}function Gu(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(Ct);o.set(r,new Map(s.map((a,c)=>[a.id,Hi(c,s.length)])))}return o}function Mt(e){return e.targetColumn<e.sourceColumn?"left":e.targetColumn>e.sourceColumn?"right":"bottom"}function qu(e){const t=new Map;for(const o of e){const r=`${o.sourceId}:${Mt(o)}`,i=t.get(r)??[];i.push(o),t.set(r,i)}const n=new Map;for(const o of t.values())o.sort(Ct),o.forEach((r,i)=>{n.set(r.id,ko(i,o.length))});return n}function Qt(e){return e.sourceColumn<e.targetColumn?"left":"top"}function Uu(e){const t=new Map;for(const o of e){const r=`${o.targetId}:${Qt(o)}`,i=t.get(r)??[];i.push(o),t.set(r,i)}const n=new Map;for(const o of t.values())o.sort(Ct),o.forEach((r,i)=>{n.set(r.id,ko(i,o.length))});return n}function Bu(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(Ct);const r=o[0];r&&n.add(r.id)}return n}function Hu(e){const t=new Map;for(const o of e){if(Mt(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(Ct),o.forEach((r,i)=>{n.set(r.id,o.length===1||i%2===1?"right":"left")});return n}function Wi(e,t){const n=Mt(e);return n==="bottom"?t.get(e.id)??"right":n}function fr(e,t){return Wi(e,t)==="right"?e.sourceColumn:e.sourceColumn-1}function en(e){return e.targetRow===e.sourceRow+1&&e.targetColumn===e.sourceColumn}function Wu(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)Mt(i)==="bottom"&&!en(i)&&n(i.sourceRow,`source:${i.id}`,i.sourceColumn,"source",i),Qt(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=Hi(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)en(i)&&o.set(i.id,r.get(i.id)??Ae[1]);return{source:o,target:r}}function Ku(e,t,n){return e.get(String(t))?.get(n)??Ae[1]}function Ki(e){const t=new Map(e.cells.map(u=>[u.id,u])),n=e.edges.flatMap(u=>{const m=t.get(u.source),f=t.get(u.target);return!m||!f?[]:[{id:u.id,sourceId:m.id,targetId:f.id,sourceRow:m.slot.row,sourceColumn:m.slot.column,targetRow:f.slot.row,targetColumn:f.slot.column,targetInput:u.targetInput}]}),o=qu(n),r=Uu(n),i=Bu(n),s=Hu(n),a=Wu(n),c=Gu(n.filter(u=>!en(u)),u=>[String(Qt(u)==="left"?u.targetColumn-1:fr(u,s))]),l=new Map;for(const u of n){const m=Wi(u,s),f=Qt(u),d=f==="left"?u.targetColumn-1:fr(u,s);l.set(u.id,{sourceSide:Mt(u),sourcePortIndex:o.get(u.id)??1,targetSide:f,targetPortIndex:r.get(u.id)??1,sourceBusOffset:a.source.get(u.id)??Ae[1],targetBusOffset:a.target.get(u.id)??Ae[1],riverOffset:Ku(c,d,u.id),riverSide:m,directRowGutter:en(u),targetPrimary:i.has(u.id)})}return l}function zu(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 Xu=8;function In(e,t){return t.x===e.x?`V ${t.y}`:t.y===e.y?`H ${t.x}`:`L ${t.x} ${t.y}`}function Ck(e,t){const n=zu(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(Xu,c/2,l/2);if(u<1){o.push(In(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},f={x:s.x+(a.x-s.x)/l*u,y:s.y+(a.y-s.y)/l*u};o.push(In(r,m),`Q ${s.x} ${s.y} ${f.x} ${f.y}`),r=f}return o.push(In(r,n[n.length-1])),o.join(" ")}function zi(e,t){return`route-${e}-${t%ju.length}`}function Mk(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=(p,g,y)=>{const v=y===void 0?o:y,S=v?.cells.find(C=>C.id===p);if(!n||!v||!p||g===void 0&&(!S||!Et(S.type))){c.current=null,a(null);return}const w=`${n}:${v.id}`,k={scope:w,cellId:p};if(g!==void 0){c.current=null,a({...k,value:g,loading:!1,error:null});return}if(!S||!r)return;const I=JSON.stringify([w,S,v.edges.filter(C=>C.target===p)]);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,f=s?.scope===l?s:null;let d;return t[5]!==m||t[6]!==f?(d={preview:f,select:m},t[5]=m,t[6]=f,t[7]=d):d=t[7],d}function Tk(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=(...d)=>{const p=d;i(),o.current=setTimeout(()=>{o.current=null,e(...p)},350)},n[4]=e,n[5]=c):c=n[5];const l=c;let u;n[6]!==e?(u=(...d)=>{const p=d;i(),e(...p)},n[6]=e,n[7]=u):u=n[7];const m=u;let f;return n[8]!==m||n[9]!==l?(f={schedule:l,cancel:i,run:m},n[8]=m,n[9]=l,n[10]=f):f=n[10],f}const Yu=720;function Xi(e){return Math.abs(e)}function Ju(e,t){const n=[];for(let o=0;o<e.length;o+=t)n.push(Math.max(...e.slice(o,o+t).map(Xi)));return n}function Zu(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(Xi)))}return n}function Rk(e){if(e.length===0)return"";const t=Math.max(1,Math.ceil(e.length/Yu)),n=Ju(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 $k(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=Zu(e,s),c=Math.max(...a),l=o/2,u=o-i;return a.map((m,f)=>{const d=r*f+r/2,p=c>0?m/c:0,g=Math.max(i,p*u),y=l-g/2,v=l+g/2;return`M${d.toFixed(2)} ${y.toFixed(2)}V${v.toFixed(2)}`}).join("")}function Nk(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 Pk(e,t){return ra(e,t)}function Ok(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 Lk(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 Qu={image:9/16,video:16/9,audio:16/9},ed={image:"Image",video:"Video",audio:"Audio"};function ht(e){return e!=null&&Number.isFinite(e)&&e>0}function Fk(e){return e==="image"||e==="video"||e==="audio"?e:null}function Dk(e){return ed[e]}function Vk(e,t){return e!=="audio"&&t&&ht(t.width)&&ht(t.height)?t.width/t.height:Qu[e]}function Oe(e,t,n,o="plain"){return n===null?null:{key:e,term:t,value:n,emphasis:o}}function td(e){return ht(e.width)&&ht(e.height)?`${e.width} × ${e.height}`:null}function nd(e){return ht(e)?me(e):null}function jk(e,t,n,o){const r=Oe("address","Address",`@${t}`,"address");if(e==="audio"){const i=mo({audioInfo:n.audioInfo,durationSeconds:n.duration,hasOutput:!0,inputs:o});return[r,Oe("role","Role",i.role),Oe("duration","Duration",i.duration),Oe("format","Format",i.details.length>0?i.details.join(" · "):null)].filter(s=>s!==null)}return[r,Oe("dimensions","Dimensions",td(n)),Oe("aspect","Aspect",un(n.width,n.height)),e==="video"?Oe("duration","Duration",nd(n.duration)):null].filter(i=>i!==null)}async function Gk(e){e.onStarting?.();try{const t=await e.start();return e.onAccepted?.(),t}catch(t){throw e.onRejected?.(),t}}async function qk(e){return!e.valid||e.dirty&&await e.onUpdate(e.patch)===!1?!1:(await e.onRun(e.cellId),!0)}function xn(e){return e!==null&&Number.isFinite(e)&&e>0}function Uk(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:It(i.slot)}})}function Bk(e,t){return oi(e,t.map(n=>({reference:n.cellAddress,replacement:`@${n.artifactId}`})))}function od(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yi(e,t){let n=e;for(const{token:o,replacement:r}of t){const i=ke(o);i&&(n=n.replace(new RegExp(`(?<![\\w./-])@?${od(i)}(?![\\w-])`,"giu"),r))}return n}function Hk(e,t){return Yi(e,t.map(n=>({token:n.artifactId,replacement:`@${n.cellAddress}`})))}function Wk(e,t,n){const o=new Map(n.flatMap(r=>r.outputArtifactId?[[r.outputArtifactId,r]]:[]));return Yi(e,t.flatMap(r=>{const i=o.get(r.artifactId);return i?[{token:r.artifactId,replacement:`@${It(i.slot)}`}]:[]}))}function Ji(e){const t=[e.type.toUpperCase()];xn(e.width)&&xn(e.height)&&t.push(`${e.width}×${e.height}`),xn(e.duration)&&t.push(me(e.duration));const n=e.status.trim().toLowerCase();return n&&n!=="ready"&&t.push(n.replaceAll("_"," ").toUpperCase()),t}function Zi(e){return e.thumbnailUrl??(e.type==="image"?e.mediaUrl:null)}function Wn(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 rd(e,t,n=new Set){const o=an(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 id(e,t,n=new Set){const o=an(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 sd=8,ad=16;function Kk(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 rd(e,n,o))s.has(c.value)||(s.add(c.value),a.push({value:c.value,label:c.label,description:Ji(c.asset).join(" · "),caption:i.get(c.value)??null,thumbnailUrl:Zi(c.asset),mediaKind:Wn(c.asset.type),empty:!1}));for(const c of id(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?Wn(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??sd),...a.filter(c=>c.empty).slice(0,r.empties??ad)]}function zk(e,t,n){const o=an(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=It(s.slot),c=r.get(a);return{value:`@${i}`,label:`@${i}`,description:[`@${a}`,...c?Ji(c):[s.type.replaceAll("_"," ").toUpperCase()]].join(" · "),caption:s.label?.trim()||null,thumbnailUrl:c?Zi(c):null,mediaKind:Wn(c?.type??s.type),empty:!1}})}const Qi={first_frame:"firstframe",last_frame:"lastframe"},cd=new Set(["replace_audio"]),ld=["image","video","audio"];function ud(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 mr(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 dd(e,t){return[...e].sort((n,o)=>{const r=mr(n.targetInput,t)??Number.MAX_SAFE_INTEGER,i=mr(o.targetInput,t)??Number.MAX_SAFE_INTEGER;return r-i})}function fd(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?ud(i.type):null;return s?[{kind:s,sourceCellId:r.source,targetInput:r.targetInput}]:[]})}function md(e){return Object.entries(Qi).flatMap(([t,n])=>{const o=e.find(r=>r.kind==="image"&&r.targetInput===t);return o?[{...o,token:n}]:[]})}function pd(e,t,n){const o=e.filter(r=>r.kind===t&&!(n!=="r2v"&&t==="image"&&r.targetInput in Qi)&&!cd.has(r.targetInput));return dd(o,t).map((r,i)=>({...r,token:`${t}${i+1}`}))}function gd(e,t,n,o){const r=t.find(a=>a.id===e)?.inputs?.generationMode,i=o??r,s=fd(e,t,n);return[...i==="r2v"?[]:md(s),...ld.flatMap(a=>pd(s,a,typeof i=="string"?i:void 0))]}function Xk(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 es(e,t,n){return e==="r2v"&&t==="image"&&(n==="first_frame"||n==="last_frame")?"image":n}function hd(e,t){const n=t.map(i=>({...i,target:es(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 Lt(e){return e==="replace_audio"?"replacement audio":e==="first_frame"?"first frame":e==="last_frame"?"last frame":`${e} reference`}function wo(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=hd(e,t).sort((l,u)=>+(u.target!==u.kind)-+(l.target!==l.kind));for(const l of i){const u=e.slots.filter(d=>d.kind===l.kind&&d.targets.includes(l.target));if(u.length===0)return`${o} does not accept ${Lt(l.target)} inputs. Change the type or remove that input.`;const f=u.filter(d=>d.max===null||(r.get(d.field)??0)<d.max).sort((d,p)=>{const g=+((r.get(d.field)??0)<d.min);return+((r.get(p.field)??0)<p.min)-g||d.targets.length-p.targets.length})[0];if(!f){const d=u.reduce((p,g)=>p+(g.max??0),0);return`${o} accepts at most ${d} ${Lt(l.target)} input${d===1?"":"s"}. Remove an input or change the model.`}r.set(f.field,(r.get(f.field)??0)+1)}const s=e.slots.find(l=>(r.get(l.field)??0)<l.min);if(s)return`Add at least ${s.min} ${Lt(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(Lt))].join(" or ")} input for ${n}.`:null}const ts={duration:["duration"],aspect:["aspect_ratio","aspectRatio","image_size"],resolution:["resolution","output_resolution","size","mode"],quality:["quality"],bitrate:["bitrate_mode"]};function ns(e){const t=Object.entries(ts).find(([,n])=>n.includes(e));return t?t[0]:null}function Kn(e){if(typeof e=="number")return e;const t=/^(\d+(?:\.\d+)?)\s*(p|k|sq)?$/iu.exec(e.trim());if(!t)return null;const n=Number(t[1]);return t[2]?.toLowerCase()==="k"?n*1e3:n}function bd(e,t){const n=Kn(e),o=Kn(t);return n!==null&&n===o&&String(e).toLowerCase().replace(/p$/u,"")===String(t).toLowerCase().replace(/p$/u,"")}function yd(e,t){return e.find(n=>n===t)??e.find(n=>String(n).toLowerCase()===String(t).toLowerCase())??e.find(n=>typeof n!="boolean"&&typeof t!="boolean"&&bd(n,t))}function _d(e,t){if(e.options.length>0)return yd(e.options,t);if(e.valueType!=="number")return;const n=Number(t);if(Number.isFinite(n)&&!(e.minimum!==void 0&&n<e.minimum)&&!(e.maximum!==void 0&&n>e.maximum))return n}function os(e,t){return typeof t!="string"&&typeof t!="number"?!1:e!=="resolution"||Kn(t)!==null}function Yk(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{const o=ns(t);return!o||!os(o,n)?[]:[[o,n]]}))}function vd(e){return Object.hasOwn(ts,e)}function kd(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>vd(t)&&os(t,n)?[[t,n]]:[]))}function Jk(e,t){return Object.fromEntries(e.flatMap(n=>{const o=ns(n.name),r=o?t[o]:void 0,i=r===void 0?void 0:_d(n,r);return i===void 0?[]:[[n.name,i]]}))}function wd(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 Zk(e){const t=wd(e).promptLeaks;return t.length===0?null:`Fix prompt references before generating: ${t.map(o=>o.message).join("; ")}`}function Sd(e){return e.length>0&&e.every(t=>t.includes("historical average per call"))}function Qk(e){const t=h(h(e)?.estimate),n=Array.isArray(t?.warnings)?t.warnings.filter(r=>typeof r=="string"):[],o=Sd(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))}}const rs=["t2i","i2i","t2v","i2v","r2v","v2v"];function is(e){return Array.isArray(e)?e.filter(t=>{if(!t||typeof t!="object")return!1;const n=t;return rs.some(o=>o===n.type)&&typeof n.rank=="number"&&Number.isFinite(n.rank)&&n.rank>0&&typeof n.elo=="number"&&Number.isFinite(n.elo)&&typeof n.priceLabel=="string"&&typeof n.sourceUrl=="string"&&typeof n.capturedOn=="string"}):[]}function Id(e,t,n,o){const r=rs.find(s=>s===t);if(r)return r;if(t==="v2v_refs")return"v2v";if(e==="generate_image")return n==="layer_image"?null:o.some(a=>a.type==="image"||a.type==="generate_image")||n==="edit_image"||n==="image_to_image"?"i2i":"t2i";if(e!=="generate_video")return null;const i={text_to_video:"t2v",image_to_video:"i2v",reference_to_video:"r2v",edit_video:"v2v"};return i[n]?n!=="text_to_video"?i[n]:o.some(s=>s.targetInput==="first_frame"||s.targetInput==="last_frame")?"i2v":o.some(s=>s.type==="video"||s.type==="generate_video")?"v2v":o.some(s=>s.type==="image"||s.type==="generate_image")?"r2v":i[n]:null}function xd(e,t){const n=e.map(s=>({action:s,ranking:t?s.frontier?.find(a=>a.type===t):void 0})),o=n.filter(s=>s.ranking&&s.action.available!==!1).sort((s,a)=>s.ranking.rank-a.ranking.rank),r=n.filter(s=>!s.ranking&&s.action.available!==!1),i=n.filter(s=>s.action.available===!1);return[{label:"Frontier models",rows:o},{label:o.length?"Other models":"Models",rows:r},{label:"Unavailable · provider not configured",rows:i}].filter(s=>s.rows.length>0)}function ew(e,t,n){const o=n.refs&&typeof n.refs=="object"?n.refs:{},r=Object.entries(o).filter(([,a])=>!!a&&(!Array.isArray(a)||a.length>0)).map(([a])=>({type:a==="first_frame"||a==="last_frame"?"image":a,targetInput:a})),i=typeof n.operation=="string"?n.operation:t==="image"?"text_to_image":"text_to_video",s=Id(`generate_${t}`,typeof n.mode=="string"?n.mode:"",i,r);return xd(e,s).flatMap(a=>a.rows.map(({action:c,ranking:l})=>({...c,group:a.label,label:`${l?`#${l.rank} · `:""}${c.label}`,detail:[c.detail,l?`Elo ${l.elo} · ${l.priceLabel}`:"",c.available===!1?"unavailable":""].filter(Boolean).join(" · ")})))}function An(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 ot(e,t,n,o){if(!An(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||!An(t,s.source,o));return An(i,n,o)?null:i}function tw(e,t,n=[]){const o=t.source,r=t.target;return!o||!r?!1:ot(n,e,o,r)!==null}function nw(e,t,n){return new Set(e.filter(o=>ot(e,t,o.id,n)===null).map(o=>ue(o.slot)))}function ss(e,t){return t[e.name]??e.defaultValue}function ow(e,t){return Object.fromEntries(e.flatMap(n=>{const o=ss(n,t);return o===void 0?[]:[[n.name,o]]}))}function Ad(e,t){return e.minimum===void 0?!1:e.exclusiveMinimum?t<=e.minimum:t<e.minimum}function Ed(e,t){return e.maximum===void 0?!1:e.exclusiveMaximum?t>=e.maximum:t>e.maximum}function Cd(e,t){const n=ss(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`:Ad(e,n)?e.exclusiveMinimum?`${e.label}: Must be greater than ${e.minimum}`:`${e.label}: Must be at least ${e.minimum}`:Ed(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 rw(e,t){const n=e.flatMap(o=>{const r=Cd(o,t);return r?[r]:[]});return n.length>0?n.join("; "):null}function bt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Md(e){return e==="image"||e==="video"||e==="audio"?e:null}function as(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function pr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:void 0}function Td(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=pr(t?.defaultValue),c=Array.isArray(t?.options)?t.options.flatMap(m=>{const f=pr(m);return f===void 0?[]:[f]}):[],l=bt(t?.minimum),u=bt(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 Rd(e){const t=h(e),n=x(t?.field),o=Md(t?.kind),r=as(t?.targets),i=bt(t?.min),s=t?.max,a=s===null?null:bt(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 $d(e){const t=h(e),n=x(t?.id);if(!n||!Array.isArray(t?.slots))return null;const o=t.slots.map(Rd).filter(i=>i!==null),r=Array.isArray(t.requiredGroups)?t.requiredGroups.map(as).filter(i=>i.length>0):[];return{id:n,slots:o,requiredGroups:r}}function Nd(e){const t=h(e);if(!Array.isArray(t?.modes))return null;const n=t.modes.map($d).filter(o=>o!==null);return n.length>0?{modes:n}:null}function Pd(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=Nd(r.inputContract),m=Array.isArray(r.controls)?r.controls.map(Td).filter(p=>p!==null):[],f=Array.isArray(r.cellTypes)?r.cellTypes.filter(p=>typeof p=="string"&&Et(p)):[];if(!i||!s||!a||!c||!u||f.length===0)return[];const d=bt(r.defaultPriority);return[{id:x(r.id)??`generation.${c}`,cellTypes:f,provider:i,providerLabel:x(r.providerLabel)??i,model:s,operation:a,tool:c,title:l??c,isDefault:r.isDefault===!0,defaultPriority:d,inputContract:u,controls:m,...typeof r.available=="boolean"?{available:r.available}:{},...Array.isArray(r.frontier)?{frontier:is(r.frontier)}:{},...r.existingCellOnly===!0?{existingCellOnly:!0}:{}}]}):[]}function So(e,t,n=!1){return e.filter(o=>o.cellTypes.includes(t)&&(n||!o.existingCellOnly))}function zn(e){return{provider:e.provider,model:e.model,operation:e.operation,tool:e.tool}}function Od(e){return{provider:e.provider?.trim()??"",model:e.model?.trim()??"",operation:e.operation?.trim()??"",tool:e.tool?.trim()??""}}function Ft(e,t){return["provider","model","operation","tool"].reduce((n,o)=>t[o]&&e[o]===t[o]?n+1:n,0)}function cs(e,t,n){const o=So(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)=>Ft(l,n)-Ft(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||Ft(l,n)>Ft(c,n)?l:c,null)}function Xn(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 ls(e,t){return t==="first_frame"||t==="last_frame"||e==="audio"&&t==="replace_audio"?t:e}function iw(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?Xn(i):null;return s?[{kind:s,target:ls(s,r.targetInput)}]:[]})}function Ld(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}_${n}`);)n+=1;return`${e}_${n}`}function sw(e,t,n,o,r){const i=e.inputContract.modes.find(d=>d.id===t);if(!i)return[];const s=new Map(o.map(d=>[d.id,d])),a=r.filter(d=>d.target===n),c=a.flatMap(d=>{const p=s.get(d.source),g=p?Xn(p):null;return g?[{sourceCellId:d.source,targetInput:d.targetInput,target:es(t,g,ls(g,d.targetInput)),kind:g}]:[]}),l=new Set(a.map(d=>d.source)),u=new Set(a.map(d=>d.targetInput)),m=[],f=new Set;for(const d of o.filter(p=>p.id!==n).sort((p,g)=>p.slot.row-g.slot.row||p.slot.column-g.slot.column)){if(l.has(d.id)||ot(o,r,d.id,n)===null)continue;const p=Xn(d);if(p)for(const g of i.slots){if(g.kind!==p)continue;const y=c.filter(v=>v.kind===g.kind&&g.targets.includes(v.target)).length;if(!(g.max!==null&&y>=g.max))for(const v of g.targets){const S=`${d.id}:${v}`;f.has(S)||(f.add(S),m.push({sourceCellId:d.id,targetInput:Ld(v,u),target:v,kind:p}))}}}return m}function Tt(e,t){return e.inputContract.modes.filter(n=>wo(n,t)===null)}function aw(e,t,n){const o=e.inputContract.modes.find(r=>r.id===t);return!!(o&&wo(o,n)===null)}function cw(e,t,n=""){return n&&e.inputContract.modes.some(o=>o.id===n)?n:Tt(e,t)[0]?.id??e.inputContract.modes[0]?.id??""}function lw(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 gn(e,t){return e.inputContract.modes.some(n=>wo(n,t)===null)}function Fd(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 Dd(e,t,n,o=!1){return So(e,t,o).filter(r=>gn(r,n)).sort(Fd)}function Vd(e,t,n=[]){if(!Et(e.type))return null;const o=Od(e),r=cs(t,e.type,o);if(r)return zn(r);if(Object.values(o).every(Boolean))return o;const i=Dd(t,e.type,n)[0];return i?zn(i):null}function Io(e){return zn(e)}function jd(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 uw="Edit video follows the source aspect ratio and duration. Connect one 4–30 second video plus optional image or audio references.";function us(e,t){return e==="kie:bytedance/seedance-2-5"&&t==="v2v"}const En=[{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"]}],Cn={aspect_ratio:"auto",duration:5,generate_audio:!0,resolution:"720p",reasoning_level:"high"},Gd=[{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"}}],qd=[{id:"i2v",label:"Image to video",roles:["first_frame"]},{id:"r2v",label:"References",roles:["image"],defaults:{duration:10}},{id:"v2v",label:"Edit video",roles:["video"],requireAny:["video"]}],it={id:"i2v",label:"Frames",roles:["first_frame","last_frame"],requireAny:["first_frame"]},Dt=["image","video","audio"];function st(e,t,n=t){return[{id:"t2v",label:"Text to video",roles:[]},e,{id:"r2v",label:"References",roles:t,requireAny:n}]}function Vt(e){const t={minimum:2e3,maximum:e*1e3,maximumTotal:e*1e3};return{refDurationMs:{video:t,audio:t}}}const at=["text_to_video","image_to_video","reference_to_video"],tn="Speaker 1";function gr(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:tn,voice_name:"Kore",accent:"Neutral"}],dialogue_turns:[{speaker_id:tn}]}}}function hr(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:tn,voice_name:"Fola"}],dialogue_turns:[{speaker_id:tn}]}}}function br(e,t){return{id:e,media:"audio",operations:["speech"],title:t,defaults:{voice:"Rachel"}}}function ct(e){return{id:`fal:minimax/h3-max/styles/${e}`,media:"video",operations:["text_to_video","image_to_video"],dialect:"strip_frames"}}const Ud=[{id:"kie:nano-banana-2-1",media:"image",operations:["text_to_image","edit_image"],dialect:"natural_numbered",defaults:{...xa}},{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:[...En,{id:"v2v",label:"Edit video",roles:["video","image","audio"],requireAny:["video"]}],defaults:{...Ia},frameOptions:{aspect_ratio:"adaptive"}},{id:"kie:bytedance/seedance-2-5-draft",media:"video",operations:["upscale_video"],title:"Seedance 2.5 Draft Complete",description:"Render the 1080p final of a Seedance 2.5 draft: a 480p kie:bytedance/seedance-2-5 run with draft on. Pass that run's Kie task id as draft_task_id.",defaults:{resolution:"1080p"}},{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-video-1-5-preview",media:"video",operations:["image_to_video"],title:"Grok Imagine Video 1.5 Preview (Kie)",guide:"grok_imagine",dialect:"natural_strip_frames"},{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",defaults:{aspect_ratio:"auto"},pinnedDefaults:["aspect_ratio"]},{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"},outputLength:"video"},{id:"kie:kling-4.0/reference-to-video",media:"video",operations:["reference_to_video"],dialect:"kling4"},{id:"kie:kling-4.0/keyframe-to-video",media:"video",operations:["image_to_video"],dialect:"kling4_keyframes",refs:{image:"keyframe_urls"}},{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:En},{id:"kie:wan/3-0-video-prime",media:"video",operations:["text_to_video","image_to_video","reference_to_video"],dialect:"seedance",modes:En},{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",outputLength:"video"},{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:ia}},{id:"kie:volcengine/video-to-video-lip-sync",media:"video",operations:["lip_sync"],outputLength:"audio"},{id:"kie:omnihuman-1-5",media:"video",operations:["image_to_video","lip_sync"],dialect:"natural",outputLength:"audio"},{id:"kie:omnihuman-2-0",media:"video",operations:["image_to_video","lip_sync"],dialect:"natural",defaults:{enable_watermark:!1},outputLength:"audio"},{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:pixverse-v6-max/text-to-video",media:"video",operations:["text_to_video"],defaults:{quality:"1080p"}},{id:"kie:pixverse-v6-max/image-to-video",media:"video",operations:["image_to_video"],dialect:"strip_frames",defaults:{quality:"1080p"}},{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:qd},{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:kling/v4/text-to-video",media:"video",operations:["text_to_video"],dialect:"seedance"},{id:"fal:kling/v4/image-to-video",media:"video",operations:["image_to_video"],dialect:"seedance",modes:rt},{id:"fal:kling/v4/reference-to-video",media:"video",operations:["reference_to_video"],dialect:"seedance"},{id:"fal:kling/v4/video-to-video/edit",media:"video",operations:["edit_video"],dialect:"seedance"},{id:"fal:heygen/heygen-video/text-to-video",media:"video",operations:["text_to_video"],dialect:"natural"},{id:"fal:heygen/heygen-video/image-to-video",media:"video",operations:["image_to_video"],dialect:"strip_frames",refs:{first_frame:"image_url"}},{id:"fal:heygen/heygen-video/reference-to-video",media:"video",operations:["reference_to_video"],dialect:"natural",modes:[{id:"r2v",label:"References",roles:["image","video","audio"],requireAny:["image","video"]}]},...[3,4].map(e=>({id:`fal:fal-ai/heygen/avatar${e}/digital-twin`,media:"video",operations:["text_to_video"],dialect:"plain",prompt:"voice.prompt",defaults:{character:{avatar:"Abigail Office Front"},voice:{voice:"Ivy"}},aliases:{avatar:"character.avatar",avatar_style:"character.avatar_style",voice:"voice.voice",voice_id:"voice.voice_id",speed:"voice.speed"}})),{id:"fal:fal-ai/heygen/avatar5/digital-twin",media:"video",operations:["text_to_video"],dialect:"plain"},{id:"fal:fal-ai/heygen/avatar4/image-to-video",media:"video",operations:["image_to_video"],dialect:"plain",defaults:{voice:"Ivy"}},{id:"fal:fal-ai/heygen/v2/video-agent",media:"video",operations:["text_to_video"],dialect:"plain"},{id:"fal:fal-ai/heygen/v3/video-agent",media:"video",operations:["text_to_video"],dialect:"plain"},{id:"fal:blackforestlabs/flux-3-max/text-to-video",media:"video",operations:["text_to_video"],title:"FLUX 3 Max",defaults:Cn},{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:Cn},{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:Cn},{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"]},ct("16bit-pixel"),ct("hand-drawn"),ct("low-poly"),ct("retro-toon-70s"),ct("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:Gd,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:"machgen:MiniMax-H3",media:"video",operations:at,title:"MiniMax H3 (MachGen)",dialect:"natural_strip_frames",modes:st({...it,requireAny:["first_frame","last_frame"]},Dt),rules:Vt(15)},{id:"machgen:Seedance-2.5",media:"video",operations:at,title:"Seedance 2.5 (MachGen)",guide:"seedance25",dialect:"natural_strip_frames",modes:st(it,Dt),frameOptions:{aspect_ratio:"adaptive"},rules:Vt(30)},{id:"machgen:Seedance-2.0",media:"video",operations:at,title:"Seedance 2.0 (MachGen)",guide:"seedance2",dialect:"natural_strip_frames",modes:st(it,Dt,["image","video"]),rules:Vt(15)},{id:"machgen:Alibaba-Wan-3.0",media:"video",operations:at,title:"Wan 3.0 (MachGen)",dialect:"natural_strip_frames",modes:st(it,Dt),rules:Vt(15)},{id:"machgen:HappyHorse-1.1",media:"video",operations:at,title:"HappyHorse 1.1 (MachGen)",dialect:"natural_strip_frames",modes:st({...it,roles:["first_frame"]},["image"])},{id:"machgen:Grok-Imagine-Video-1.5",media:"video",operations:["image_to_video"],title:"Grok Imagine Video 1.5 (MachGen)",guide:"grok_imagine",dialect:"natural_strip_frames"},{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"]},br("kie:elevenlabs/text-to-speech-multilingual-v2","ElevenLabs Multilingual v2 (Kie)"),br("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"}]}},gr("kie:google/gemini-2-5-pro-tts","Gemini 2.5 Pro TTS (Kie)"),gr("kie:google/gemini-3-1-flash-tts","Gemini 3.1 Flash TTS (Kie)"),hr("kie:google/gemini-3-8-flash-tts","Gemini 3.8 Flash TTS (Kie)"),hr("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"}}],Bd=new Map(Ud.map(e=>[e.id,e]));function Hd(e){return Bd.get(e)}const dw="Frame mode follows the first image’s aspect ratio (adaptive).";function Wd(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 ds(e,t){const n=Hd(e)?.frameOptions?.aspect_ratio;if(typeof n!="string")return;const o=t.generationMode??t.mode;if(o!=="r2v")return o==="i2v"||Wd(t.refs)?n:void 0}const Kd=200,zd={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 Xd(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 Yd(e){const t=Xd(e);if(!t)return e;try{return JSON.parse(t)}catch{return null}}function Jd(e){const t=h(e);return typeof t?.model=="string"&&t.model?t.model:typeof t?.tool=="string"&&t.tool?t.tool:""}function Zd(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:Jd(t.params),createdAt:typeof t.created_at=="number"?t.created_at:0}]}function Qd(e){const t=h(Yd(e));return(Array.isArray(t?.entries)?t.entries:[]).flatMap(Zd)}function ef(e){const t=new Set;return e.filter(n=>{const o=n.prompt.trim();return t.has(o)?!1:(t.add(o),!0)})}function fw(e,t){const n=t.trim().toLowerCase();return n?e.filter(o=>o.prompt.toLowerCase().includes(n)):[...e]}function mw(e,t){const n=e.filter(r=>t.has(r.prompt)),o=e.filter(r=>!t.has(r.prompt));return[...n,...o]}function tf(e){return{book_id:e.bookId,scope:e.scope,limit:Kd,...e.surfaceFilter==="surface"?{surface:e.surface}:{}}}function pw(e){return zd[e]??e.replaceAll("_"," ")}function nf(e){return e<1e12?e*1e3:e}function gw(e,t){if(!e)return"";const n=Math.max(0,Math.floor((t-nf(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 fs(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 ms(e){const t=co(e).map(n=>n.reference);return[...new Set(t)]}function xo(e,t){const n=ke(t),o=ri(n);if(o){const a=fs(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 ps(e){return ms(e)}function Ao(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 of(e,t){return t==="first_frame"||t==="last_frame"||e==="audio"&&t==="replace_audio"?t:e}function gs(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 hs(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 bs(e){const t=e.preferredModel?So(e.actions,e.cellType).find(o=>o.model===e.preferredModel):void 0;if(t&&gn(t,e.connectedInputs))return t;const n=Vd({type:e.cellType},e.actions,e.connectedInputs);return n?cs(e.actions,e.cellType,n):null}function rf(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 hw(e){return ps(e)}function yr(e){return typeof e=="string"?[e]:Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function bw(e){const n=[...e.refs&&typeof e.refs=="object"&&!Array.isArray(e.refs)?Object.values(e.refs).flatMap(yr):[],...Object.entries(e).flatMap(([o,r])=>/(?:^|_)(?:ref|refs)$/u.test(o)?yr(r):[])];return ps(n.map(o=>o.startsWith("@")?o:`@${o}`).join(" "))}function yw(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 ys(e,t){const n=Ao(t);if(!n)throw new Error(`${Z(t)} is not a media-producing cell`);if(!Fe(e,t))throw new Error(`${Z(t)} does not have media output yet`);return{cell:t,kind:n}}function sf(e,t){return t.map(n=>ys(e,xo(e,n)))}function _w(e,t=[],n){const o=new Set(t);return e.cells.flatMap(r=>{if(o.has(r.id))return[];if(n&&ot(e.cells,e.edges,r.id,n)===null)return[];const i=Ao(r);return!i||!Fe(e,r)?[]:[{cell:r,kind:i}]})}function vw(e){const t=sf(e.document,e.command.sourceReferences),n=t.find(p=>ot(e.document.cells,e.document.edges,p.cell.id,e.cellId)===null);if(n)throw new Error(`Connecting ${Z(n.cell)} would create a cycle`);let o=null,r=[];for(const p of hs(t)){const g=bs({actions:e.actions,cellType:e.command.cellType,connectedInputs:p,...e.preferredModel?{preferredModel:e.preferredModel}:{}});if(g){o=g,r=p;break}}if(!o)throw new Error(`No available ${e.command.mediaKind} generation action accepts these references`);const i=Io(o),s=Tt(o,r)[0],a=rf(o,e.routedParams),c={...s?{generationMode:s.id}:{},...Object.keys(a).length>0?{generationSettings:a}:{}},l=t.map(p=>p.cell.slot),u=e.lastWorkSlot??null,m=e.command.cellType==="generate_video"?yo(e.document.cells,l,u):e.command.cellType==="generate_image"||e.command.cellType==="generate_audio"?mn(e.document.cells,l,u):e.fallbackSlot,f={id:e.cellId,type:e.command.cellType,slot:m,prompt:e.command.prompt,...i,...Object.keys(c).length>0?{inputs:c}:{}},d=gs(r);return{action:o,cell:f,connections:t.map((p,g)=>({sourceCellId:p.cell.id,targetInput:d[g]??p.kind})),sourceCellIds:t.map(p=>p.cell.id),sourceAddresses:t.map(p=>Z(p.cell))}}function kw(e,t){const n=new Set(e.sourceCellIds);for(const o of ms(e.cell.prompt??"")){const r=xo(t,o);if(!n.has(r.id))throw new Error(`@${o} is referenced but not connected`)}}function af(e,t){const n=e.connections.map(r=>({source:r.sourceCellId,target:e.cell.id,targetInput:r.targetInput})),o=new Map(gd(e.cell.id,t.cells,n,x(e.cell.inputs?.generationMode)??void 0).map(r=>[r.sourceCellId,r.token]));return oi(e.cell.prompt??"",t.cells.flatMap(r=>{const i=o.get(r.id);return i?[{reference:It(r.slot),replacement:`@${i}`}]:[]}))}function ww(e,t){return e.connections.flatMap(n=>{const o=t.cells.find(i=>i.id===n.sourceCellId),r=o?Ao(o):null;return r?[{kind:r,target:of(r,n.targetInput)}]:[]})}function Eo(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(us(e.action.model,t?.generationMode))return{...o,aspect_ratio:"adaptive",duration:-1};const r=ds(e.action.model,t??{});return r?{...o,aspect_ratio:r}:o}function Sw(e,t){return{...e,cell:{...e.cell,prompt:t}}}function Iw(e,t,n){if(!t.cellTypes.includes(e.cell.type)||!gn(t,n))throw new Error("The selected generation model does not accept these inputs");const o=Tt(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=Eo(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,...Io(t),inputs:{...r,generationMode:s.id,generationSettings:c}}}}function xw(e,t,n){const o=Tt(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 Aw(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=Eo(e);return n===void 0?delete o[t]:o[t]=n,{...e,cell:{...e.cell,inputs:{...h(e.cell.inputs)??{},generationSettings:o}}}}function Ew(e){const t=e.draft.cell.type,n=[...new Set(e.sourceCellIds)].map(d=>{const p=e.document.cells.find(g=>g.id===d);if(!p)throw new Error("The selected source cell is no longer available");if(ot(e.document.cells,e.document.edges,p.id,e.draft.cell.id)===null)throw new Error(`Connecting ${Z(p)} to ${Z(e.draft.cell)} would create a cycle`);return ys(e.document,p)}),o=hs(n);let r=null,i=[];for(const d of o)if(gn(e.draft.action,d)){r=e.draft.action,i=d;break}if(!r)for(const d of o){const p=bs({actions:e.actions,cellType:t,connectedInputs:d});if(p){r=p,i=d;break}}if(!r){const d=t==="generate_audio"?"audio":t==="generate_image"?"image":"video";throw new Error(`No available ${d} generation action accepts these references`)}const s=Tt(r,i),a=h(e.draft.cell.inputs)??{},c=x(a.generationMode),l=s.find(d=>d.id===c)??s[0];if(!l)throw new Error("The selected generation model does not have a compatible mode");const u=Eo(e.draft),m=Object.fromEntries(r.controls.flatMap(d=>{const p=u[d.name];return p===void 0?[]:[[d.name,p]]})),f=gs(i);return{action:r,cell:{...e.draft.cell,...Io(r),inputs:{...a,generationMode:l.id,generationSettings:m}},connections:n.map((d,p)=>({sourceCellId:d.cell.id,targetInput:f[p]??d.kind})),sourceCellIds:n.map(d=>d.cell.id),sourceAddresses:n.map(d=>Z(d.cell))}}async function Cw(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:af(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 cf=new Set(["","text","number","url","search","email","tel","date","time","datetime-local","password"]);function lf(e){return!e||e.tagName.toLowerCase()!=="input"?!1:cf.has((e.type??"").toLowerCase())}function Mw(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||lf(e.target)?"apply":"none"}const Tw={transcribing:!1,analyzing:!1,error:null};function Rw(e,t){return e.transcribing}function $w(e,t){return e==="transcript"?{transcribing:t}:{analyzing:t}}const Nw="GPT-4o Translation",Pw="ElevenLabs Transcript";function uf(e){return e==="timed"||e==="plain"||e==="silence"?e:null}function _r(e){return Array.isArray(e)?e.flatMap(t=>{const n=x(t);return n?[n]:[]}):[]}function _s(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function df(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 Mn(e){const t=h(e),n=t&&uf(t.kind);return!t||!n?null:{kind:n,languageCode:x(t.language_code??t.languageCode),text:typeof t.text=="string"?t.text:"",wordCount:_s(t.word_count??t.wordCount),words:df(t.words)}}function ff(e){const t=h(e);if(!t)return null;if("elevenlabs"in t||"plain"in t){const o=Mn(t.elevenlabs),r=Mn(t.plain);return!o&&!r?null:{elevenlabs:o,plain:r}}const n=Mn(t);return n?n.kind==="plain"?{elevenlabs:null,plain:n}:{elevenlabs:n,plain:null}:null}function mf(e){const t=h(e);return t?{summary:typeof t.summary=="string"?t.summary:"",mood:x(t.mood),setting:x(t.setting),tags:_r(t.tags),subjects:_r(t.subjects),sceneCount:_s(t.scene_count??t.sceneCount)}:null}function We(e){return e==="video"||e==="audio"||e==="final"}function Ow(e){return!!(e&&e.kind!=="silence"&&e.text.trim())}function pf(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 gf=.4,hf=12;function bf(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>gf||s||n.length>=hf)){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 yf(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 _f(e){return bf(e).map(t=>`${yf(t.start)} ${t.text}`).join(`
|
|
15
|
+
`)}function Lw(e,t){return t==="json"&&e?"json":"text"}function vf(e){const t=e.transcript;return!t||t.kind==="silence"?"":e.source==="elevenlabs"&&t.kind==="timed"&&t.words.length>0?_f(t.words):t.text}function kf(e){return e.view==="json"?e.jsonText??"":vf(e)}function Fw(e){return kf(e)}function Dw(e){return e.view==="json"?e.jsonFile?`Raw sidecar · ${e.jsonFile}`:"Raw sidecar":e.transcript?pf(e.transcript):null}function Vw(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 jw(e){return e?.kind==="timed"}async function wf(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 Gw({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 wf(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 Sf(e){const t=e;return t?Ei(t.tags):null}function If(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 qw({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 f=i;(i.targetKey!==o||i.source!==r)&&(f={targetKey:o,source:r,canonical:n,pending:i.targetKey===o?i.pending:[],error:i.targetKey===o?i.error:null},s(f));const d=f.pending.reduce((I,E)=>er(I,E.edit,E.action),f.canonical),p=_.useCallback((I,E)=>{if(!e||!t)return Promise.resolve();let C;try{C=Ai(I,[...d?.effective??[],...d?.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=Sf(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:er(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,d,a,r,t,o]),g=_.useCallback(I=>p(I,"add"),[p]),y=_.useCallback(I=>p(I,"remove"),[p]),v=_.useCallback(I=>p(I,"restore"),[p]),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:If(A)})}catch{m.current===C&&c({targetKey:o,tags:[]})}},[e,t,o]),w=_.useMemo(()=>Ll(a.targetKey===o?a.tags:[],d?.effective??[]),[d,a,o]),k=_.useCallback(()=>s(I=>({...I,error:null})),[]);return{tags:d,busy:f.pending.length>0,error:f.error,canEdit:!!(e&&t),suggestions:w,addTag:g,removeTag:y,restoreTag:v,loadSuggestions:S,clearError:k}}const vs="videobook.prompt-history.pins";function xf(){try{const e=window.localStorage.getItem(vs),t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(n=>typeof n=="string"):[])}catch{return new Set}}function Af(e){try{window.localStorage.setItem(vs,JSON.stringify([...e]))}catch{return}}function Ef(e){return e instanceof Error?e.message:String(e)}function Uw({call:e,bookId:t,surface:n,prompt:o,onApply:r}){const[i,s]=_.useState(!1),[a,c]=_.useState(!1),[l,u]=_.useState(null),[m,f]=_.useState(null),[d,p]=_.useState(0),[g,y]=_.useState("book"),[v,S]=_.useState("surface"),[w,k]=_.useState(""),[I,E]=_.useState(xf),[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 Se={bookId:t,surface:n,scope:P,surfaceFilter:Y};c(!0),u(null);try{const $t=ef(Qd(await e("list_prompt_history",tf(Se))));return N.current!==Me?null:(f($t),p(Date.now()),$t)}catch($t){return N.current===Me&&u(Ef($t)),null}finally{N.current===Me&&c(!1)}},q=(P,Y,Me)=>{if(Y<0){A(-1),r(Me);return}const Se=P[Y];Se&&(A(Y),r(Se.prompt))},J=()=>{if(!M)return;if(D>=0&&m){q(m,D+1,$);return}const P=o;T(P),z(g,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(g,v)},H=P=>{y(P),A(-1),z(P,v)},U=P=>{S(P),A(-1),z(g,P)},we=P=>{const Y=new Set(I);Y.has(P)?Y.delete(P):Y.add(P),E(Y),Af(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:d,scope:g,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:we,use:Q,older:J,newer:pe,handlePromptKeyDown:B}}const Cf={generate_image:"image_generate",generate_video:"video_generate",generate_audio:"audio_generate"};function Bw(e){return Cf[e]??null}function Mf(e){return e==="image-reverse"?"image":"video"}async function Hw(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:Mf(o),...i?{source_start_seconds:i.startSeconds,source_duration_seconds:i.durationSeconds}:{}});return ks(s,r)}function Tf(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 Ww(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 Kw(e,t,n){if(!Tf(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(lt(s,"error")??"Could not prepare search reference");const a=ks(s);return a.previewUrl?a:{...a,previewUrl:URL.createObjectURL(e),localPreview:!0}}async function Rf(e){e&&(e.localPreview&&e.previewUrl&&URL.revokeObjectURL(e.previewUrl),await fetch(`/api/search-references/${encodeURIComponent(e.referenceId)}`,{method:"DELETE"}).catch(()=>{}))}function ks(e,t){const n=lt(e,"reference_id"),o=lt(e,"kind"),r=lt(e,"name"),i=vr(e,"expires_at");if(!n||o!=="image"&&o!=="video"||!r||i===null)throw new Error("The server returned an invalid search reference");const s=vr(e,"duration_ms"),a=lt(e,"preview_url")??t;return{referenceId:n,kind:o,name:r,expiresAt:i,...s===null?{}:{durationMs:s},...a?{previewUrl:a}:{}}}function lt(e,t){if(typeof e!="object"||e===null)return null;const n=e[t];return typeof n=="string"?n:null}function vr(e,t){if(typeof e!="object"||e===null)return null;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null}const ws=.25,kr=.01;function Yn(e){return Math.min(1,Math.max(0,e))}function jt(e){return Math.round(Yn(e)*1e6)/1e6}function $f(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 zw(e,t){const n=jt(Math.min(e.x,t.x)),o=jt(Math.min(e.y,t.y)),r=jt(Math.min(1-n,Math.abs(t.x-e.x))),i=jt(Math.min(1-o,Math.abs(t.y-e.y)));return r<kr||i<kr?null:{x:n,y:o,width:r,height:i}}function Xw(e,t,n){return n.width<=0||n.height<=0?{x:0,y:0}:{x:Yn((e-n.left)/n.width),y:Yn((t-n.top)/n.height)}}function Nf(e,t,n=ws){return t.flatMap(r=>{if(!r.box)return[];const i=$f(e,r.box);return i>=n?[{subjectId:r.id,iou:i,box:r.box}]:[]}).sort((r,i)=>i.iou-r.iou)[0]??null}function Yw(e,t,n=ws){const o=Nf(e.box,t,n);return o?{...e,box:o.box,matchedSubjectId:o.subjectId}:e}function Jw(e,t,n={}){return{subjectIds:[...e],regions:t.map(o=>({id:o.id,box:o.box,...o.matchedSubjectId?{matchedSubjectId:o.matchedSubjectId}:{}})),replacements:{...n}}}const Pf="Mention a replacement image (for example @g7) or assign one in the panel.",Of="Mention one image for every region, or one image to use for all of them.",Lf="Draw a region or select a person or object to replace.";function Ss(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 Zw(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 Qw(e,t){return e.length>0&&e.every(n=>!!t[n.key]?.trim())}function eS(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 tS(e,t,n){if(e.length===0)return{ok:!1,error:Lf};const o={};for(const s of e){const a=t[s.key]?.trim();a&&(o[s.key]=a)}const r=Ss(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:Of};i.forEach((s,a)=>{o[s.key]=r[a]})}return e.every(s=>!!o[s.key])?{ok:!0,replacements:o}:{ok:!1,error:Pf}}function nS(e,t){const n=new Map(t.map(i=>[i.cellAddress.toLowerCase(),i])),o=[],r=new Set;for(const i of Ss(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 oS(e){return`region-${e.length+1}-${Math.random().toString(36).slice(2,8)}`}function rS(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 iS(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 Ff(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 sS(e){const t=[];return e.width&&e.height&&t.push(`${e.width} × ${e.height}`),e.duration&&e.type!=="image"&&t.push(Ff(e.duration)),t.push(e.type==="final"?"VIDEO":e.type.toUpperCase()),t}const Df=["button","input","select","textarea","[href]",'[contenteditable="true"]',"[tabindex]"].join(", ");function Vf(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 jf(e){return[...e.querySelectorAll(Df)].filter(Vf)}function Gf(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 aS(e,t){if(e.key==="Escape"){t.busy||(e.preventDefault(),t.onClose());return}if(e.key!=="Tab"||!t.container)return;const n=jf(t.container),o=t.activeElement===void 0?document.activeElement:t.activeElement,r=Gf(n,o,e.shiftKey);r&&(e.preventDefault(),r.focus())}async function wr(e,t,n,o){await e("delete_notebook_cell",{book_id:t,notebook_id:n,cell_id:o}).catch(()=>{})}function qf(e){const t=h(e);return x(t?.id)}async function Uf(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 qf(c)}return null}async function cS(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=mn(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 Uf(e.callTool,e.bookId,e.document.id,r)),a&&await wr(e.callTool,e.bookId,e.document.id,a),r&&await wr(e.callTool,e.bookId,e.document.id,r),s}}function Bf(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 Hf(e){return Bf(await e("list_elevenlabs_voices",{},{background:!0}))}function Sr(){return{voices:[],status:"fallback",warning:null,loading:!1,error:null}}function Wf(e){let t=e.ready,n=e.load,o=0,r=!1,i=Sr(),s=null;const a=new Set,c=m=>{i=m;for(const f of a)f()},l=()=>{o+=1,r=!1,s=null,c(Sr())},u=()=>{if(!t)return Promise.resolve(null);if(s)return s;const m=o,f=Promise.resolve().then(()=>n()).then(d=>o!==m||s!==f?null:(r=!0,s=null,c({...d,loading:!1,error:null}),d),d=>(o!==m||s!==f||(r=!1,s=null,c({...i,loading:!1,error:d instanceof Error?d.message:String(d)})),null));return s=f,c({...i,loading:!0,error:null}),f};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 lS(e){const t=ne.c(25),{callTool:n,ready:o}=e;let r;t[0]!==n?(r=()=>Hf(n),t[0]=n,t[1]=r):r=t[1];const i=r;let s;t[2]!==i||t[3]!==o?(s=()=>Wf({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 f=_.useSyncExternalStore(a.subscribe,a.getSnapshot,a.getSnapshot);let d;t[13]!==a?(d=()=>a.ensureLoaded(),t[13]=a,t[14]=d):d=t[14];const p=d;let g;t[15]!==a?(g=()=>a.refresh(),t[15]=a,t[16]=g):g=t[16];const y=g;let v;return t[17]!==p||t[18]!==y||t[19]!==f.error||t[20]!==f.loading||t[21]!==f.status||t[22]!==f.voices||t[23]!==f.warning?(v={voices:f.voices,status:f.status,warning:f.warning,loading:f.loading,error:f.error,ensureLoaded:p,refresh:y},t[17]=p,t[18]=y,t[19]=f.error,t[20]=f.loading,t[21]=f.status,t[22]=f.voices,t[23]=f.warning,t[24]=v):v=t[24],v}function Kf(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 zf(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=Kf(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??bi,lastUsedModelId:x(t?.last_used_model)}}function uS(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 f;t[0]!==n||t[1]!==r||t[2]!==o?(f=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(zf(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]=f):f=t[3];const d=f;let p;t[4]!==r?.models?(p=r?.models??[],t[4]=r?.models,t[5]=p):p=t[5];const g=r?.defaultModelId??bi,y=r?.lastUsedModelId??null;let v;return t[6]!==d||t[7]!==c||t[8]!==s||t[9]!==p||t[10]!==g||t[11]!==y?(v={models:p,defaultModelId:g,lastUsedModelId:y,loading:s,error:c,ensureLoaded:d},t[6]=d,t[7]=c,t[8]=s,t[9]=p,t[10]=g,t[11]=y,t[12]=v):v=t[12],v}function dS(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 fS(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 Xf=["top-left","top-center","top-right","middle-left","middle-center","middle-right","bottom-left","bottom-center","bottom-right"],Yf=33,Jf=10,Zf=90,Qf=.5,em=.05,tm=1,Is=32,nm=0,om=96,rm=88,im=26,mS=480,sm=100,am=0,cm=100,lm=["center","above-qr","on-qr","below-qr"];function pS(e){return Number.isFinite(e)?Math.min(Zf,Math.max(Jf,e)):Yf}function gS(e){return Number.isFinite(e)?Math.min(tm,Math.max(em,e)):Qf}function um(e){return Number.isFinite(e)?Math.round(Math.min(om,Math.max(nm,e))):Is}function hS(e){const t=um(e);return Math.max(im+4,rm+2*(t-Is))}function dm(e){return typeof e=="string"&&lm.includes(e)}function bS(e){return Number.isFinite(e)?Math.round(Math.min(cm,Math.max(am,e))):sm}function fm(e){return e==="auto"||Xf.includes(e)}const mm=.5,pm=0,gm=2,hm=.001;function yS(e){if(!Number.isFinite(e))return mm;const t=Math.min(gm,Math.max(pm,e));return Math.round(t*10)/10}function bm(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-hm;return{fadeIn:r>0?a:0,fadeOut:c?a:0}}function _S(e,t,n,o,r,i){if(e<t||n!==null&&e>n)return 0;const s=bm(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 xs="videobook.watermark-review.v1:",mt=new Map;function Ir(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Co(e){const t=Ir(e);if(!t)return{};const n={};gc(t.platform)&&(n.platform=t.platform),fm(t.position)&&(n.position=t.position),dm(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=Ir(t.handles);if(o){n.handles={};for(const r of pc)typeof o[r]=="string"&&(n.handles[r]=o[r])}return n}function ym(e){if(!e)return{};const t=mt.get(e);if(t)return t;try{const n=window.localStorage.getItem(`${xs}${e}`);if(n!==null)return Co(JSON.parse(n))}catch{return mt.get(e)??{}}return mt.get(e)??{}}function vS(e,t,{handle:n,...o}){if(!e)return;const r=ym(e),i={...r,...Co(o),platform:o.platform??t,handles:n===void 0?r.handles:{...r.handles,[t]:n}};try{window.localStorage.setItem(`${xs}${e}`,JSON.stringify(i)),mt.delete(e)}catch{mt.set(e,i)}}function _m(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 vm(e,t,n){const o=Ra,r=n&&n>0?$a(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 kS(e,t,n){const o=t.platform??e.platform??"tiktok",r=o==="tiktok"?vm(e,t,n):e;return{..._m(r,n),...Co(t),platform:o,handles:t.handle===void 0?e.handles:{...e.handles,[o]:t.handle}}}const km=new Set(["queued","running","completing"]);function xr(e){return e.state==="failed"||e.state==="aborted"}function wS(e,t,n,o){const r=o.find(a=>a.id===t);if(!r)return{kind:"missing"};if(xr(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(xr);return s||n?.status==="error"?{kind:"failed",message:s?.error?.message??"Post-watermark processing failed"}:i.some(a=>km.has(a.state))?{kind:"continue"}:n&&n.status!=="ready"?{kind:"continue"}:{kind:"completed",result:r.result}}function SS(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 IS(e,t,n,o){return`Burning ${e?t?`QR + @${n} watermarks`:"QR watermark":`@${n} watermark`} into ${o}…`}function xS(e){return e===1?"1 artifact":`${e} artifacts`}function AS(e){return e===1?"1 notebook":`${e} notebooks`}function ES(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 nn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function fe(e,t){const n=Array.isArray(e)?e:nn(e)?.[t];return Array.isArray(n)?n.flatMap(o=>{const r=nn(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 CS(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 f=fe(await n("list_entities",{}),"entities");i.choices.entity_id=ie(f,["id"],["name"]),i.entities=Object.fromEntries(f.filter(d=>typeof d.id=="string").map(d=>[String(d.id),d])),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 f=l&&o.commit_hash?fe(await n("asset_history",{asset_id:l,limit:200}),"commits"):fe(await n("list_book_actions",{limit:200}),"actions"),d=ie(f,["hash","revision"],["message","operation"]);i.choices.commit_hash=d,i.choices.target_revision=d;const p=f.flatMap(y=>{const v=nn(y.details)?.actionId;return typeof v=="string"?[{...y,actionId:v}]:[]}),g=ie(p,["actionId"],["operation","message"]);i.choices.action_id=r==="get_history_action"?ie(f,["hash","revision"],["operation","message"]):g,i.choices.target_action_id=g,r==="read_file_at_commit"&&(s=ie(f.flatMap(y=>{const v=nn(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 f=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(f,["planId","plan_id"],["prompt","status"])})()),o.model&&e.generation&&a.push((async()=>{const f=fe(await n("list_generation_models",{media:e.generation?.mediaType}),"models");i.choices.model=f.flatMap(d=>ie([d],["id"],["title"]).map(p=>({...p,...typeof d.available=="boolean"?{available:d.available}:{},frontier:is(d.frontier)})))})()),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 f=fe(await n("get_image_subject_map",{artifact_id:l,object_hash:t.object_hash}),"subjects");i.choices.subject_id=ie(f,["id","subjectId"],["label","name"]),i.choices.subject_ids=i.choices.subject_id})());const m=(await Promise.allSettled(a)).flatMap(f=>f.status==="rejected"?[f.reason instanceof Error?f.reason.message:String(f.reason)]:[]);if(m.length)throw new Error(`Could not load action choices: ${m.join(" · ")}`);if(s.length){const f=new Map((i.choices.filename??[]).map(d=>[d.value,d]));for(const d of s)f.has(d.value)||f.set(d.value,{...d,detail:"Historical file"});i.choices.filename=[...f.values()]}return i}const MS={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 TS(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=Cm(t.ratio)),e==="sidebar_sort"&&(o.sort=Am(t.order)),e==="viewer_toggle_info"&&(o.name="original"),e==="settings_bg"){const i=Em(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"?Mm(r):e==="settings_audio"?Tm(r):As[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:Rm(r,i,s)}return o}const wm=["newest","oldest"],Sm=["blur","black"],As={"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"},Im={position:["top","middle","bottom"],highlight_style:["impact","highlight","alive"],font_size:["small","medium","large"]},xm={position:{mid:"middle"},font_size:{s:"small",m:"medium",l:"large"}};function RS(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 $S(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 Am(e){const t=String(e??"newest").trim().toLowerCase();if(t==="newest"||t==="oldest")return t;throw new Error(`Usage: /sort ${wm.join("|")}`)}function Em(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 ${Sm.join("|")}`)}function Cm(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 Mm(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 Tm(e){const t=As[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 Rm(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=Im[t];if(!o)return n;const r=n.trim().toLowerCase(),i=xm[t]?.[r]??r;if(o.includes(i))return i;throw new Error(`Usage: /subs ${e} ${o.join("|")}`)}const $m={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"])},NS={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 PS(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($m[o].has(n))return o;return null}function Nm(e){return e==="audio"||e==="image"||e==="video"?e:null}function OS(e,t,n){return Nm(e)!==null&&t===void 0&&n===0}function LS(e){return e.types.includes("Files")}const FS=["Media","Text & analysis","Generation","Edit"],Jn=[{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"}],Pm=new Set(Jn.map(e=>e.type));function Ar(e){return e.trim().toLocaleLowerCase().replaceAll("_"," ")}function DS(e){const t=Ar(e);return t?Jn.filter(n=>Ar(`${n.label} ${n.type} ${n.group}`).includes(t)):Jn}function VS(e){return Pm.has(e)}const Om=new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}),Lm=new Intl.NumberFormat("en-US"),jS={images:"Images",video:"Video",audio:"Audio",chat:"Chat",voice:"Voice",analysis:"Analysis & transcription"};function GS(e,t=!1){return(t?Lm:Om).format(e)}function Fm(e){return e>0&&e<.01?"<$0.01":`$${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function qS(e){const t=e.reportedUsd+e.estimatedUsd;return t===0&&e.unpriced>0?"— cost":`${e.estimatedUsd>0?"~":""}${Fm(t)}`}function Dm(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 US({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=Dm(await n("get_book_usage",{book_id:e},{background:!0}));if(!u())return;r(f=>f?.bookId===e&&JSON.stringify(f.data)===JSON.stringify(m)?f:{bookId:e,data:m}),s(null)}catch{u()&&s(e)}});return _.useEffect(()=>{if(!t||!e)return;let u=!0,m=!1,f=0;const d=async()=>{if(window.clearTimeout(f),!(!u||m||document.visibilityState==="hidden")){m=!0;try{await l(()=>u)}finally{m=!1,u&&(f=window.setTimeout(d,2e3))}}},p=()=>{d()};return f=window.setTimeout(p,0),window.addEventListener("focus",p),document.addEventListener("visibilitychange",p),()=>{u=!1,window.clearTimeout(f),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",p)}},[e,t,a]),{snapshot:o?.bookId===e?o.data:null,stale:!t||i===e,retry:()=>c(u=>u+1)}}const Es=new Set(["video","generate_video","concat","splice"]);function Vm(e,t){const n=ke(t),o=e.cells.find(r=>r.outputArtifactId?.toLowerCase()===n);return o||(e.cells.find(r=>Es.has(r.type)&&ii(e,r)?.toLowerCase()===n)??null)}function Mo(e,t){let n;try{n=xo(e,t)}catch(o){const r=Vm(e,t);if(!r)throw o;n=r}if(!Es.has(n.type))throw new Error(`${Z(n)} is not a video-producing cell`);if(!ii(e,n))throw new Error(`${Z(n)} does not have a video output yet`);return n}const jm="[a-z0-9][a-z0-9-]*",Gm=new RegExp(`^(?:please\\s+)?(?:/split|split)\\s+@(${jm})(?:\\s+([\\s\\S]+?))?(?:\\s+please)?[.!]?$`,"iu"),oe=.02;function G(e){return Math.round(e*1e3)/1e3}function _e(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 BS(e){const t=e.pieces[e.selectedIndex]??e.pieces[0];return t?`Cutting ${_e(t.startSeconds)}–${_e(t.endSeconds)} (${t.durationSeconds.toFixed(3)}s)`:"Split video"}function HS(e){return typeof e!="number"||!Number.isFinite(e)||!(e>0)?null:1/e}function qm(e,t){return(e==="all"?Math.max(1,t):1)+1}function Zn(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 Um(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 Bm(e){const t=Um(e);return t?t.split(/\s*(?:,|;|\band\b|\bthen\b)\s*/iu).map(n=>n.trim()).filter(Boolean):[]}function Hm(e,t,n){const o=Xe(e),r=Vn(n,o),i=[];let s=r;for(let a=0;a<t;a+=1){const c=Vn(s,[...o,r,...i]);i.push(c),s=c}return{action:r,outputs:i}}function Wm(e){const t={id:Wt(),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 Km(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 zm(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=Zn(n[1]),r=Zn(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 WS(e){const t=e.trim().match(Gm);if(!t)return null;const n=t[2]?.trim()??"";if(n&&/^(keep|remove)\b/iu.test(n)){const i=zm(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?Bm(n):[]).map(Zn);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 Xt(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 hn(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 KS(e){const t=hn(e);return Xt(t),t.slice(0,-1).map(n=>n.endSeconds)}function Xm(e){const t=hn({cutPointsSeconds:e.cutPointsSeconds,sourceDurationSeconds:e.sourceDurationSeconds}),n=e.outputMode??"all";if(n==="all")return Xt(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 Xt(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 Xt([{startSeconds:r[0].startSeconds,endSeconds:r[0].startSeconds+i}]),[r]}function Ym(e){const t=e.outputMode??"all",n=hn({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=`${_e(r.startSeconds)}-${_e(r.endSeconds)}`;return t==="keep"?`Cut ${i} out of ${e.sourceAddress}`:`Remove ${i} from ${e.sourceAddress}`}function Jm(e,t,n){if(e==="all")return`Chunk ${String(n+1).padStart(2,"0")}`;if(e==="keep"){const a=t[0];return`Cut ${_e(a.startSeconds)}-${_e(a.endSeconds)}`}const o=t[0],r=t[t.length-1],i=o.endSeconds,s=r.startSeconds;return t.length>=2&&s>i?`Without ${_e(i)}-${_e(s)}`:`Without ${_e(o.startSeconds)}-${_e(r.endSeconds)}`}function zS(e){const t=Mo(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=Xm({cutPointsSeconds:e.command.cutPointsSeconds,outputMode:n,selectedChunkIndexes:o,sourceDurationSeconds:e.sourceDurationSeconds}),i=hn({cutPointsSeconds:e.command.cutPointsSeconds,sourceDurationSeconds:e.sourceDurationSeconds}).slice(0,-1).map(f=>f.endSeconds),s=Hm(e.document.cells,r.length,t.slot),a=r.map(f=>f.map(d=>({endSeconds:d.endSeconds,startSeconds:d.startSeconds}))),c={id:Wt(),type:"split_video",label:n==="all"?`Split into ${r.length} chunks`:Ym({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((f,d)=>{const p=f[0].startSeconds,g=f.reduce((v,S)=>v+(S.endSeconds-S.startSeconds),p),y=Wm({actionCell:c,chunkCount:r.length,chunkIndex:d,endSeconds:f.length===1?f[0].endSeconds:g,slot:s.outputs[d],source:t,startSeconds:p});return y.outputCell={...y.outputCell,label:Jm(n,f,d)},y}),u=[c,...l.map(f=>f.outputCell)],m=[{id:Wt(),source:t.id,target:c.id,targetInput:"video"},...l.map(f=>({id:Wt(),source:c.id,target:f.outputCell.id,targetInput:"media"}))];return{actionCell:c,createdCellIds:u.map(f=>f.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 XS(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:Km(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 Zm=1/60;function Qm(e,t){return e[t]}function YS(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??Zm,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=Qm(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 JS(e){return e>0&&e<.25}function Je(e){return[...new Set(e.map(G))].filter(t=>Number.isFinite(t)).sort((t,n)=>t-n)}function ep(e){return Je(e.slice(1,-1))}function tp(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function Ce(e){const t=G(e.sourceDurationSeconds),o=[0,...Je(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 ZS(e){let t=0;return e.map(n=>(t=G(t+n),t))}function QS(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 Cs(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 To(e){const t=G(e.sourceDurationSeconds),n=Ce(e),o=n[e.index];if(!o)return{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index};const r=Cs(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?Je(e.cutPointsSeconds.filter(g=>g<=a.startSeconds)):[],u=c?Je(e.cutPointsSeconds.filter(g=>g>=c.endSeconds)):[],m=[];i>0&&m.push(i),s<t&&m.push(s);const f=Je([...l,...m,...u]).filter(g=>g>0&&g<t),p=Ce({cutPointsSeconds:f,sourceDurationSeconds:t}).findIndex(g=>g.startSeconds===i&&g.endSeconds===s);return{cutPointsSeconds:f,selectedIndex:p>=0?p:e.index}}function e0(e){const n=Ce(e)[e.index];return n?To({...e,endSeconds:n.endSeconds,startSeconds:G(n.startSeconds+e.deltaSeconds)}):{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index}}function t0(e){const n=Ce(e)[e.index];return n?To({...e,endSeconds:G(n.endSeconds+e.deltaSeconds),startSeconds:n.startSeconds}):{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index}}function n0(e){const n=Ce(e)[e.index];if(!n)return{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index};const o=n.durationSeconds,r=Cs(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}:To({...e,endSeconds:s,startSeconds:i})}function o0(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=Je([...e.cutPointsSeconds,o]).filter(i=>i>0&&i<G(e.sourceDurationSeconds));return tp(r,e.cutPointsSeconds)?{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index}:{cutPointsSeconds:r,selectedIndex:e.index}}function r0(e){const t=Ce(e),n=t[e.index],o=t[e.index+1];return!n||!o?{cutPointsSeconds:[...e.cutPointsSeconds],selectedIndex:e.index}:{cutPointsSeconds:ep([0,...e.cutPointsSeconds.filter(i=>i!==n.endSeconds),G(e.sourceDurationSeconds)]),selectedIndex:e.index}}const np={steps:[],credits:[]};function i0(e=np,t=At){return{loading:!1,error:null,context:e,options:{enabled:kp(e)},promptOverrides:{},creditsOverride:null,maxCharacters:t}}function s0(e,t){return e.maxCharacters===t?e:{...e,maxCharacters:t}}function yt(e,t){return e.slot.row-t.slot.row||e.slot.column-t.slot.column||e.id.localeCompare(t.id)}function op(e,t){const n=e.cells.filter(o=>!Ge(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(yt)}return e.cells.filter(o=>Fe(e,o)===t).sort(yt)}const Er=new Set(["generate_audio","generate_image","generate_video"]),rp=["sourceArtifactId","source_asset_id","first_asset_id","second_asset_id","additional_asset_ids"];function Tn(e,t){const n=e.inputs?.[t];return typeof n=="string"&&n.trim()?n:null}function Gt(e){return e?.trim()?e:null}function Ms(e,t){const n=e.inputs?.[t];return(Array.isArray(n)?n:[n]).filter(r=>typeof r=="string"&&r.trim()!=="")}function ip(e){return rp.flatMap(t=>Ms(e,t))}function sp(e){const t=new Map(e.cells.map(o=>[o.id,o])),n=new Map;for(const o of[...e.cells].sort(yt)){if(Ge(o))continue;const r=Fe(e,o);if(!r)continue;const i=n.get(r);(!i||Er.has(i.type)&&!Er.has(o.type))&&n.set(r,o)}return{cellsById:t,cellsByArtifactId:n}}function Ts(e,t,n){const o=e.edges.filter(s=>s.target===n.id).map(s=>s.source),r=Ms(n,"sourceCellId"),i=ip(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 Cr(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 Ts(e,t,u))r.has(m)||a.push(m)}}return{visited:i,stopped:s}}function ap(e){return e.type==="generate_video"}function Rs(e,t){const n=t.flatMap(o=>{const r=Fe(e,o);return r?[r]:[]});return[...new Set(n)]}function cp(e,t,n){const o=sa(e,n.id)?.outputCell??null,r=Ts(e,t,n).map(i=>t.cellsById.get(i)).filter(i=>i!==void 0).sort(yt);return{id:n.id,producerCellId:n.id,outputCellId:o?.id??null,outputArtifactId:o?Fe(e,o)??null:Fe(e,n)??null,producerPrompt:Gt(n.prompt)??Tn(n,"prompt"),producerResolvedPrompt:Tn(n,"resolvedPrompt")??Tn(n,"resolved_prompt"),producerTool:Gt(n.tool),producerModel:Gt(n.model),producerProvider:Gt(n.provider),sourceArtifactIds:Rs(e,r)}}function a0(e,t){const n=sp(e),o=op(e,t),r=Cr(e,n,o,ap).stopped.sort(yt),i=Cr(e,n,o,()=>!1).visited;return{steps:r.map(s=>cp(e,n,s)),upstreamArtifactIds:Rs(e,i)}}function c0(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 l0(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 $s="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",lp=new RegExp(`^${$s}$`,"iu"),up=new RegExp(`@(${$s}|${aa})(?![\\w-])`,"giu");function dp(e){return e==="video"||e==="final"?"video":e==="image"||e==="audio"?e:"source"}function u0(e,t){const n=new Map(t.map(i=>[ke(i.reference),i.type])),o=new Map,r=new Map;return e.replace(up,(i,s)=>{const a=ke(s),c=o.get(a);if(c)return c;const l=n.get(a);if(!l&&!lp.test(a))return i;const u=dp(l),m=(r.get(u)??0)+1;r.set(u,m);const f=`[${u} ${m}]`;return o.set(a,f),f})}const fp=new Set(["youtube.com","m.youtube.com","music.youtube.com","youtu.be"]),mp=new Set(["x.com","mobile.x.com","twitter.com","mobile.twitter.com"]),pp=new Set(["explore","home","i","intent","messages","notifications","search","settings","share"]);function gp(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 hp(e,t){const n=gp(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 bp(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=pp.has(n.toLowerCase())?null:n;return{kind:"x",url:`https://x.com/${n}/status/${t[2]}`,handle:o,status:!0}}function yp(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 fp.has(n)?hp(t,n):mp.has(n)?bp(t):null}catch{return null}}function _p(e){return e.kind==="youtube"?e.videoId!==null:e.status}function vp(e,t){return typeof e.uploader!="string"?t:e.uploader.replaceAll("@","").replace(/\s+/g," ").trim()||t}function d0(e,t){const n=[t.webpage_url,t.webpageUrl,t.source_url,t.sourceUrl].map(yp).filter(r=>r!==null),o=n.find(_p)??n[0];return o?{id:`${e}:${o.url}`,label:vp(t,o.kind==="x"?"X":"YouTube"),url:o.url,xHandle:o.kind==="x"?o.handle:null}:null}function f0(e){const t=new Set;return e.filter(n=>t.has(n.url)?!1:(t.add(n.url),!0))}const m0="The thread has nothing to post. Add a prompt, or turn the thread off.";function kp(e){return e.credits.length>0||e.steps.some(t=>t.prompt.trim()!==""||t.images.length>0)}function wp(e){return e.slice(0,jn)}function Ns(e,t){return t>1?` (${e+1}/${t})`:""}function Ps(e,t,n){const o=Ns(t,n);if(!e.model)return`Prompt${o}:
|
|
16
|
+
`;const r=e.model.provider?` via ${e.model.provider}`:"";return`Made with ${e.model.label}${r}${o}. Prompt:
|
|
17
|
+
`}const Sp="…",Ip=2;function xp(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 Ap(e,t){if(e.length<=t)return e;const n=Math.max(0,t-Ip),o=xp(e,n),r=o>Math.floor(n/2)?o:n;return`${e.slice(0,r).trimEnd()}${Sp}`}function Ep(e,t,n,o){const r=Ps(e,t,n);return Ap(e.prompt.trim(),o-r.length)}function Cp(e,t){const n=e.context.steps.findIndex(o=>o.id===t.id);return n===-1?0:n}function Mp(e,t){return e.promptOverrides[t.id]??Ep(t,Cp(e,t),e.context.steps.length,e.maxCharacters)}function Tp(e){return e.xHandle?`@${e.xHandle}`:e.label}function Mr(e){return`${Tp(e)}: ${e.url}`}function Rp(e,t=At){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 ${Mr(o)}`;const r=`Special thanks to:
|
|
18
|
+
${n.map(Mr).join(`
|
|
19
|
+
`)}`;return r.length<=t?r:`Special thanks to:
|
|
20
|
+
${n.map(i=>i.url).join(`
|
|
21
|
+
`)}`}function $p(e){return e.creditsOverride??Rp(e.context.credits,e.maxCharacters)}function Os(e,t,n,o){return{id:e,stepId:t,text:n,imageAssetIds:o.map(r=>r.assetId),images:[...o]}}function Np(e,t,n,o){const r=Mp(e,t).trim(),i=wp(t.images);if(!r&&i.length===0)return null;const s=r?`${Ps(t,n,o)}${r}`:`Input images for this video${Ns(n,o)}:`;return Os(`step:${t.id}`,t.id,s,i)}function Pp(e){if(!e.options.enabled)return[];const t=e.context.steps.length,n=e.context.steps.flatMap((r,i)=>{const s=Np(e,r,i,t);return s?[s]:[]}),o=e.context.credits.length>0?$p(e).trim():"";return o&&n.push(Os("credits",null,o,[])),n}function p0(e){return Pp(e).map(t=>({text:t.text,imageAssetIds:t.imageAssetIds}))}const Op=2e3,Lp=6*6e4,g0={status:null,connecting:!1,authorizeUrl:null,error:null};function Fp(e){const t=h(e),n=W(t?.username),o=W(t?.subscription_type);return n&&o?{username:n,subscriptionType:o}:null}function Dp(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:At}function Vp(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:Fp(t?.account),postMaxCharacters:Dp(t?.post_max_characters)}}function jp(e){return e?.postMaxCharacters??At}function Gp(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 qp(e){if(!e.account)return null;const t=jp(e).toLocaleString("en-US");return`${Gp(e.account.subscriptionType)}: posts up to ${t} characters.`}async function Tr(e,t={}){return Vp(await e("service_status",{service:"x",...t.refreshAccount?{refresh_account:!0}:{}},{background:!0}))}async function h0(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 b0(e,t){const n=t.now??Date.now,o=t.pollMs??Op,r=t.timeoutMs??Lp,i=n();let s=await Tr(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 Tr(e)}return s}function y0(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 Up(e){return new Date(e).toLocaleString([],{hour:"2-digit",minute:"2-digit",month:"short",day:"numeric"})}function Bp(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 ${Up(n)}.`:"Tokens renew automatically."}function _0(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=qp(e);return{tone:"connected",label:e.account?`Connected as @${e.account.username}`:"Connected",detail:[n,Bp(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"}}function v0(e){const[t,n]=_.useState(null),[o,r]=_.useState(!1),[i,s]=_.useState(null);async function a(c){if(e){r(!0),s(null);try{n(await e("set_har_capture",c?{mode:c}:{}))}catch(l){s(l instanceof Error?l.message:String(l))}finally{r(!1)}}}return{settings:t,busy:o,error:i,update:a}}const Hp={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 Wp(e){return Hp[e.envKey]??e.label}function Qn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function k0(e){const t=Qn(e);if(!Array.isArray(t?.providers))throw new Error("Could not read provider settings");return t.providers.flatMap(n=>{const o=Qn(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 w0(e){const t=Qn(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 S0(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 f=a.current;fn(()=>f)()};return{draft:t,saving:o,message:i,edit:(f,d)=>{!f.editable||o||(c.current+=1,a.current=d,s(null),n({key:f.envKey,value:f.secret?"":f.maskedKey??""}))},close:l,save:async f=>{if(!t||t.key!==f.envKey||!t.value.trim()||o||!f.editable)return;const d=c.current;r(!0),s(null);try{if(await e(t.key,t.value),d!==c.current)return;s({key:t.key,text:`${Wp(f)} saved`,error:!1}),l()}catch(p){d===c.current&&s({key:t.key,text:p instanceof Error?p.message:String(p),error:!0})}finally{r(!1)}},change:f=>n(d=>d?{...d,value:f}:null)}}const Ro={label:"In place · previous version kept",tone:"warning"};function ze(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 je(e){const t=$e(e);return t!==null?me(t):xe(e)}function qe(e,t){const n=co(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 Kp(e,t){const n=$e(e),o=$e(t);return n===null||o===null||o<n?null:me(o-n)}function zp(e){const t=ze(e.params,"start_time")?je(e.params.start_time)??"Not provided":"0:00 (default)",n=je(e.params.end_time)??"Not provided",o=Kp(e.params.start_time??0,e.params.end_time)??"Calculated on apply";return{title:"Extract new video clip",settings:[L("Source",qe(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 Xp(e){const t=je(e.params.chunk_a_end)??"Not provided",n=ze(e.params,"chunk_b_start")?e.params.chunk_b_start:e.params.chunk_a_end,o=je(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",qe(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 Yp(e){const t=ze(e.params,"cut_start")||ze(e.params,"cut_end"),n=t?"cut_start":"trim_start",o=t?"cut_end":"trim_end",r=ze(e.params,n)?je(e.params[n])??"Not provided":t?"Not provided":"0:00 (default)",i=ze(e.params,o)?je(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",qe(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:Ro}}function _t(e){const t=e.replaceAll("_"," ").replaceAll("-"," ");return t.charAt(0).toUpperCase()+t.slice(1)}function Jp(e){return String(Number(e.toFixed(2)))}function Zp(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",qe(e.input,e.params))];return t!==null&&t>0&&s.push(L("Source duration",me(t))),s.push(L("Speed",r!==null?`${Jp(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:Ro}}function Qp(e){const t=xe(e.params.scheduled_for),n=xe(e.params.orientation);return{title:"Post to X",settings:[L("Destination","X"),L("Source",qe(e.input,e.params)),L("Publish",t?`Scheduled · ${t}`:"Now","default",t!==null),L("Orientation",n?_t(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 $o=/api.?key|secret|(?:^|[_-])token(?:$|[_-])|password|credential|authorization/iu;function eg(e,t){return e!=="value"?!1:Object.entries(t).some(([n,o])=>/^(?:env_?)?key$|^(?:variable_?)?name$/iu.test(n)&&typeof o=="string"&&$o.test(o))}function eo(e){return Array.isArray(e)?e.map(eo):typeof e!="object"||e===null?e:Object.fromEntries(Object.entries(e).map(([t,n])=>[t,$o.test(t)?"Hidden":eo(n)]))}function Ls(e,t,n){if($o.test(e)||eg(e,n))return"Hidden";if(/time|seconds|duration/iu.test(e)){const r=je(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(eo(t));return o?o.length>96?`${o.slice(0,93)}…`:o:"None"}function tg(e){const t=Array.isArray(e.params.steps)?e.params.steps:[],n=t.flatMap((r,i)=>{const s=Rn(r),a=xe(s?.tool)??`step ${i+1}`,c=Rn(s?.params)??{},l=xe(c.asset_id)??xe(c.audio_asset_id)??qe(e.input,c);return[L(`Step ${i+1}`,`${_t(a)} · ${l}`)]}),o=t.some(r=>{const i=xe(Rn(r)?.tool);return i==="replace_video_audio"||i==="trim_video"});return{title:"Chained actions",settings:n.length>0?n:[L("Tool","chain")],effect:o?Ro:null}}function Rr(e){return e===null?"Unknown":e<.01?`${Math.round(e*100)}¢`:`$${e.toFixed(2)}`}function I0(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(_t(o),Ls(o,r,e.params))),L("Estimated cost",Rr(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 ${Rr(e.estimateUsd)}`,tone:"warning"},postText:typeof e.params.prompt=="string"?e.params.prompt:void 0}}function Rn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ng(e){const t=Object.entries(e.params).filter(([n])=>n!=="book_id").slice(0,8).map(([n,o])=>L(_t(n),n==="asset_id"?qe(e.input,e.params):Ls(n,o,e.params),"default",/url/iu.test(n)&&typeof o=="string"));return{title:_t(e.tool),settings:t.length>0?t:[L("Tool",e.tool)],effect:null}}function x0(e){return e.tool==="extract_video_clip"?zp(e):e.tool==="split_video"?Xp(e):e.tool==="trim_video"?Yp(e):e.tool==="change_video_speed"?Zp(e):e.tool==="post"?Qp(e):e.tool==="chain"?tg(e):ng(e)}const Rt={blocking:null,notice:null};function ee(e){return{blocking:e,notice:null}}function Fs(e){return{blocking:null,notice:e}}function $r(e,t,n){return t!==null?t>e:n<=0||e<n}function og(e){return e.trim().replace(/^@/,"").trim()}function A0(e){const t=og(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&&!$r(e.qrStartSeconds,e.qrEndSeconds,o)?ee("QR end time must be after its start time."):e.includeHandle&&!$r(e.handleStartSeconds,e.handleEndSeconds,o)?ee("Handle end time must be after its start time."):Rt}function E0(e){if(!e.prompt?.trim())return ee("Write a prompt before applying.");if(e.settingsError)return ee(e.settingsError);if(e.previewStale)return Rt;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 Fs(e.estimateUnknown?"No cost estimate is available for this model.":null)}function C0(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=qm(e.outputMode,t.length);return e.availableEmptyCells<n?ee(`This split needs ${n} empty notebook cells; ${e.availableEmptyCells} available.`):Rt}function M0(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 Rt;const i=r.length>0?` (+${r.length} more)`:"";return Fs(`${o.message}${i}`)}function T0(e,t,n){const o=uc(e,t,n);return o?ee(o):Rt}function R0(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 rg=1024,$0=`(min-width: ${rg}px)`;function N0(e){return e.state==="ready"&&!e.hasSecondaryActions&&e.wideEnough}function ig(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 sg(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 ag(e){return e==="generate_image"||e==="generate_video"||e==="generate_audio"}function P0(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||!ag(r.type))return n;const i=ig(o.type);return!i||i==="image"&&(n==="first_frame"||n==="last_frame")||i==="audio"&&(n==="replace_audio"||n==="scene_audio")?n:sg(e,r.id,i)}function cg(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 lg(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 ug(e){const t=new Map(e.cells.map(a=>[a.id,a])),n=Ki(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)??Bi,m=zi(u.sourceSide,u.sourcePortIndex),f=s.get(a.source)??[];f.includes(m)||f.push(m),s.set(a.source,f)}return e.cells.map(a=>{const c=lg(t,a),l=Dc(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:Qe(a.slot),data:{kind:a.type,...a.label===void 0?{}:{label:a.label},subtitle:Ge(a)?yu():`${a.type.toUpperCase()} · CELL`,slot:a.slot,status:"ready",targetInputs:o.get(a.id)??cg(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 O0(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 L0(e){const t=Ki(e),n=new Map(e.cells.map(o=>[o.id,pi(o.type)]));return e.edges.map(o=>{const r=t.get(o.id)??Bi,i=n.get(o.source)??"data";return{id:o.id,source:o.source,sourceHandle:zi(r.sourceSide,r.sourcePortIndex),target:o.target,targetHandle:o.targetInput,type:"busRiver",className:`workflow-edge edge-family-${i}`,data:r}})}function F0(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 dg(e){return e.operation!=="rewrite_prompt"&&Et(e.type)}function D0(e){return e.tool==="edit_image_subjects"&&e.provider==="local"?!1:e.operation==="rewrite_prompt"||dg(e)}function ut(e="text"){return{mode:e,reference:null,startSeconds:"0",durationSeconds:"",preparing:!1,error:null}}function Nr(e){return e instanceof Error?e.message:String(e)}function fg({initialMode:e="text",onStateChange:t,release:n}){let o=!0,r=0,i=ut(e);const s=g=>{i=g,o&&t(g)},a=g=>{g&&Promise.resolve(n(g)).catch(()=>{})},c=g=>{r+=1;const y=i.reference;s(ut(g)),a(y)};return{changeMode:g=>{o&&c(g)},clearError:()=>{o&&i.error&&s({...i,error:null})},clearReference:()=>{if(!o)return;r+=1;const g=i.reference;s({...i,reference:null,startSeconds:"0",durationSeconds:"",preparing:!1,error:null}),a(g)},close:()=>{o&&c("text")},getState:()=>i,prepare:async(g,y)=>{if(!o)return{status:"stale"};const v=r+1;if(r=v,i.mode===g)s({...i,preparing:!0,error:null});else{const S=i.reference;s({...ut(g),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:g,reference:S,startSeconds:"0",durationSeconds:"",preparing:!1,error:null}),w!==S&&a(w),{status:"ready",mode:g,reference:S}}catch(S){if(!o||v!==r)return{status:"stale"};const w=Nr(S);return s({...i,preparing:!1,error:w}),{status:"error",error:w}}},resetInvalidRange:g=>{const y=Nr(g);return o&&s({...i,startSeconds:"0",durationSeconds:"",error:y}),y},setDurationSeconds:g=>{o&&s({...i,durationSeconds:g,error:null})},setStartSeconds:g=>{o&&s({...i,startSeconds:g,error:null})},stop:()=>{if(!o)return;o=!1,r+=1;const g=i.reference;i=ut(),a(g)}}}function mg(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 V0(e){const t=Date.now()+(e.timeoutMs??6e5);try{for(;!e.isCancelled();){const n=await e.search();let o=mg(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 He(e){if(typeof e!="object"||e===null)throw new Error("Invalid search indexing response");return e}async function j0(e){const t=He(await e.start());if(!Array.isArray(t.jobs))throw new Error("Invalid search indexing jobs");let n=t.jobs.map(i=>{const s=He(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(He).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=He(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 f of m.failures){const d=He(f).message;typeof d=="string"&&o.failures.length<20&&o.failures.push({message:d})}}else if(u.state==="failed"||u.state==="aborted"){o.failed+=1;const m=u.error?He(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 G0(e){const t=ne.c(10),n="text";let o;t[0]!==n?(o=()=>ut(n),t[0]=n,t[1]=o):o=t[1];const[r,i]=_.useState(o);let s;t[2]!==n?(s=()=>fg({initialMode:n,onStateChange:i,release:Rf}),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 No={jobs:{path:"/jobs",name:"Jobs"},settings:{path:"/settings",name:"Settings"}},pg=Object.entries(No);function q0(e){const t=e.replace(/\/+$/,"")||"/";return pg.find(([,o])=>o.path===t)?.[0]??"notebook"}function U0(e){return e==="notebook"?"/":No[e].path}function B0(e){return e==="notebook"?"VIDEOBOOK":`${No[e].name} · VIDEOBOOK`}function gg(e,t){return!e||!t?null:`${e}:${t}`}function hg(e,t){return t?e[t]??null:null}function bg(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 H0(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=gg(e,t),a=hg(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=f=>{i(d=>bg(d,s,f))},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 W0(e,t=n=>window.requestAnimationFrame(n)){t(()=>{t(()=>{const n=e();n&&n.scrollTo({top:n.scrollHeight,behavior:"smooth"})})})}function yg(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"),f=m.length===1?m[0]:null;if(!f||f.getAttribute("data-id")!==t)return s();const d=u.getBoundingClientRect(),g=Math.min(d.top+u.clientHeight,o?.getBoundingClientRect().top??d.bottom)-d.top;if(g<=0)return;const y=f.getBoundingClientRect(),v=Math.max(16,(g-y.height)/2),S=Math.max(0,Math.min(u.scrollHeight-u.clientHeight,u.scrollTop+y.top-d.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 K0(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=hu(s.width,s.minimumZoom);let f;o[1]===Symbol.for("react.memo_cache_sentinel")?(f=()=>{const I=r.current;I&&(l.current=I.scrollTop/c.current)},o[1]=f):f=o[1];const d=f;let p;o[2]!==n?(p=()=>{const I=r.current;if(!n||!I)return;I.scrollLeft=0,I.scrollTop=0,l.current=0;const E=()=>{d();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",d,{passive:!0});const C=new ResizeObserver(E);return C.observe(I),()=>{u.current?.(),I.removeEventListener("scroll",d),C.disconnect()}},o[2]=n,o[3]=p):p=o[3];let g;o[4]!==n||o[5]!==e||o[6]!==t?(g=[n,e,t,d],o[4]=n,o[5]=e,o[6]=t,o[7]=g):g=o[7],_.useLayoutEffect(p,g);let y,v;o[8]!==n||o[9]!==m?(y=()=>{const I=r.current;!n||!I||(I.scrollTop=l.current*m,c.current=m,d())},v=[n,d,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=yg(()=>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 z0(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 X0=["source","cinematic","ig-influencer"],_g={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 on(e){return _g[e]}function to(e,t={}){const n=on(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 Y0(e,t){const n=on(e.id),o=to(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 vg(e,t){if(e.id!==t.id)return!1;const n=to(e.id,e.options),o=to(t.id,t.options);return Object.keys(n).every(r=>n[r]===o[r])}function vt(e){return!!(e&&"version"in e&&e.version===2)}function Pe(e){return!e||!("shots"in e)?[]:e.shots}function J0(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&&vg(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 Z0(e,t,n){return e.stages[t]?.outputs.find(o=>o.index===n)?.versions??[]}function Q0(e,t,n){return e.stages[t]?.outputs.find(o=>o.index===n)?.stale??null}function eI(e,t,n){const o=e.estimate[t].usd;if(o===null||t==="frame")return o;const r=Pe(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 Ds(e){return Object.values(e.stages).flatMap(t=>t.attempts??[]).find(t=>t.chainId===e.chainId&&t.feedback)}function bn(e){const t=Ds(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,Pe(e.plan).length);return`${t.index>=n?"ending frame":"storyboard"} ${t.index%n+1}`}function tI(e){return(e.planVersion===2||e.planVersion===3)&&(e.status==="failed"||e.status==="interrupted")}function nI(e){return e.status!=="running"||!e.resumeStage?"Stop goal":Ds(e)?"Stop revision":"Stop regeneration"}function kg(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=bn(e);return`${r?`${r[0].toUpperCase()}${r.slice(1)} revision`:t.stage==="frame"?"Frame generation":"Storyboard generation"} stopped`}function Vs(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 wg(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(Vs)}function Sg(e){return{planned:"Planned",waiting:"Waiting",submitting:"Submitting",generating:"Generating",done:"Ready",failed:"Failed",skipped:"Not started",stopped:"Stopped"}[e]}function kt(e){const t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function js(e){return e&&"version"in e&&e.version===3?e.video.durationSeconds:Pe(e).reduce((t,n)=>t+n.durationSeconds,0)}function Ig(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 xg(e){return Pe(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 Ag(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"&&vt(n)?[{index:0,number:"01",title:"Full frame",prompt:n.frame.prompt,seconds:0}]:Pe(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"&&vt(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(f=>f.index===c.index);return{...c,state:Ig(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 Eg(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 et(e){const t=e.stage==="assembly"?"videos":e.stage,n=Ag(e,t),o=Eg(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 Cg(e){return{frame:"Full frame",storyboards:"Storyboards",videos:"Videos"}[e]}function rn(e,t){const n=e.estimate[t];return n.usd===null?"":` · est. $${n.usd.toFixed(2)}`}function Mg(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 Le(e,t,n,o,r){return{text:e,short:t,announce:`Goal: ${e}`,action:n,tone:o,busy:r}}function Tg(e,t){if(e.planVersion!==3)return null;const n=et(e),o=e.finish;if(o?.status==="running")return Le("Finishing the cold open and watermark","Finishing",null,"live",!0);if(o?.status==="failed")return Le("Finishing failed","Finishing failed","Finish","attention",!1);if(n.phase==="review"){if(o){const r=e.coldOpen?` · analysis $${e.coldOpen.analysisUsd.toFixed(2)}`:"";return Le(`Review finish${r}`,"Review","Review","review",!1)}return e.stage==="videos"?Le(`Review video${rn(e,"videos")}`,"Review","Review","review",!1):Le(`Review scene${rn(e,"frame")}`,"Review","Review","review",!1)}if(n.phase==="frame"||n.phase==="videos"){const r=n.active?.state==="generating"?`Generating${t===null?"":` ${kt(t)}`}`:"Submitting",i=bn(e),s=n.phase==="frame"?"Scene":"Video";return Le(`${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 Le(i,n.phase==="failed"?"Failed":"Interrupted","Retry","attention",!1)}return null}function wt(e,t=null){const n=Tg(e,t);if(n)return n;const o=et(e),r=vt(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"}${rn(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?"":` ${kt(t)}`}`:"Submitting",f=bn(e);i=`${f?`Revising ${f}`: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 · ${kt(js(e.plan))}`,s="Done",a="Preview",c="done"):(o.phase==="failed"||o.phase==="interrupted")&&(i=Mg(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 Pr(e){const t=et(e);return`${e.goalId}:${e.chainId??""}:${t.phase}:${t.stage}:${t.done}:${t.active?.index??-1}`}function Rg(e,t){const n=Pr(t);if(e.goalId!==t.goalId||Pr(e)===n||t.status==="cancelled")return null;const o=et(e),r=et(t);let i=wt(e).text;const s=bn(t),a=kg(e,o,r,t);return r.phase==="failed"||r.phase==="interrupted"?i=wt(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 ${Cg(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 oI(e){return e.find(t=>t.status!=="cancelled"&&!t.dismissedAt&&t.cellId)??null}function rI(e){const t=new Map;for(const n of e){n.combined&&t.set(n.combined.cellId,`Combined${n.address?` · ${n.address}`:""}`);const o=Pe(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(f=>f.index===(l==="frame"?0:a-1))??[],m=u.findIndex(f=>f.chainId===i.chainId&&f.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 f of[i.cellId,i.outputCellId])f&&t.set(f,`${c}${n.address?` · ${n.address}`:""}`)}}return t}const Or=5,Lr={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 iI(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 $g(e,t){return!e||!t?null:t.phase==="failed"||t.phase==="interrupted"?`${wt(e).text}${e.planVersion===1?" · start a new goal":" · open to retry"}`:t.phase==="planning"?e.brief||null:t.phase==="review"?`${wt(e).text}${t.stage==="frame"?"":rn(e,t.stage)}`:t.phase==="complete"?`${e.assembly?"Added to the timeline":"Clip ready"} · ${kt(js(e.plan))}`:null}function Ng(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+(vt(e.plan)&&e.plan.frameContinuity?3:2)*Pe(e.plan).length,o=Object.values(e.stages).reduce((r,i)=>r+i.outputs.length,0);return Math.round(o/n*100)}function sI(e,t,n){const o=e?.plan??t,r=e?et(e):null,i=r?.phase??null,s=r&&r.shots.length>0?r.shots:xg(o),a=s.length>Or?s.slice(0,Or-1):s,c=Pe(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(d=>d.durationSeconds===u)?u:null,f=e?[...(e.stages.frame?.outputs??[]).map(d=>({...d,label:l?"Scene":"Full frame"})),...(e.stages.storyboards?.outputs??[]).map(d=>({...d,label:d.index>=c.length?`Ending ${d.index+1-c.length}`:`Storyboard ${d.index+1}`}))]:[];return{title:o?.title??(i==="planning"?"Building your shot plan":n??"Video goal"),planning:i==="planning",rows:a.map(d=>({key:`${d.index}`,number:d.number,title:d.title,state:d.state,detail:d.state==="generating"?"":d.state==="submitting"?"Queued":d.seconds>0&&(d.state==="done"||d.state==="planned")?d.state==="done"?kt(d.seconds):`${d.seconds}s`:Sg(d.state),startedAt:d.state==="generating"?d.startedAt:null})),hiddenRows:s.length-a.length,note:$g(e,r),noteTone:i?Lr[i].tone:"quiet",chip:e?.finish?.status==="running"?{label:"Finishing",tone:"live"}:i?Lr[i]:{label:"Goal",tone:"quiet"},progressPercent:e&&r?Ng(e,r):0,shotsLabel:o?m===null?`${c.length} clips`:l?`1 × ${m}s`:`${c.length} × ${m}s`:null,aspectRatio:o?.aspectRatio??null,thumbnails:f,styleLabel:vt(o)?on(o.style?.id??"cinematic").label:e?.requestedStyle?on(e.requestedStyle.id).label:null}}function Fr(e){const t=e?.startedAt??e?.enqueuedAt;return typeof t=="number"&&Number.isFinite(t)&&t>0?new Date(t).toISOString():void 0}function Pg(e,t,n,o){if(!vc(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:Fr(i)??Fr(r[0])??t.createdAt}}function Og(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 Lg(e,t){return t?e.get(t):void 0}function Fg(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 Dg(e,t){const n=h(e.execution),o=n&&h(n[t]);return b(o?.startedAt)??b(o?.updatedAt)??void 0}function Vg(e,t){const n=h(e.execution),o=n&&h(n[t]);return b(o?.error)??void 0}function Dr(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 jg(e,t,n){const o=e.cells.find(f=>f.id===t),r=b(o?.inputs?.producerCellId)??e.edges.find(f=>f.target===t&&f.targetInput==="media")?.source??null,i=r?e.cells.find(f=>f.id===r):void 0,s=i?.type==="generate_video"?h(i.inputs?.generationSettings):null,a=us(i?.model??"",i?.inputs?.generationMode),c=a?"adaptive":ds(i?.model??"",i?.inputs??{})??b(o?.inputs?.aspectRatio??o?.inputs?.aspect_ratio)??b(s?.aspect_ratio),l=c&&c!=="adaptive"&&c!=="auto"?c:un(n?.width??null,n?.height??null),u=Dr(n?.duration),m=Dr(o?.inputs?.durationSeconds??o?.inputs?.duration_seconds??s?.duration??s?.duration_seconds);return{aspectRatio:l,durationSeconds:u??(a?null:m)}}function aI(e,t,n){const o=new Map(t.map(r=>[r.artifactId,r]));return ug(e).map(r=>{const i=e.posts?.find(d=>d.id===r.id),s=i?Og(i,e.cells,o):null,a=$c(r.data.inputs),c=Lg(o,r.data.outputArtifactId),l=r.data.kind==="video"?jg(e,r.id,c):null,u=Dg(e,r.id),m=Vg(e,r.id),f=Pg(r.data.kind,c,n,{status:Fg(e,r.id),...u?{startedAt:u}:{},...m?{error:m}:{}});return{...r,data:{...r.data,status:i?.runtime.status??f.status,...i?{post:i}:{},...s?{postSource:s}:{},...f.startedAt?{statusStartedAt:f.startedAt}:{},...f.error?{statusError:f.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 Po(e,t){return Object.is(e,t)?!0:JSON.stringify(e)===JSON.stringify(t)}function cI(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 Po(a,s)?s:a});return o.length===e.length&&o.every((i,s)=>i===e[s])?e:o}function lI(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 Po(a,s)?s:a});return o.length===e.length&&o.every((i,s)=>i===e[s])?e:o}const qt=[],$n=[];function Nn(e){return e?`${e.bookId}:${e.notebookId}`:""}function Gg(e,t){return e.some(n=>n.goalId===t.goalId)?e.map(n=>n.goalId===t.goalId?t:n):[t,...e]}function uI(e,t){const n=ne.c(12);let o;n[0]===Symbol.for("react.memo_cache_sentinel")?(o={key:"",goals:qt,events:$n},n[0]=o):o=n[0];const[r,i]=_.useState(o),s=_.useRef(r),a=Nn(t),c=r.key===a?r.goals:qt,l=r.key===a?r.events:$n;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:qt,$=k.map(R=>{const D=A.find(z=>z.goalId===R.goalId);return D&&D.updatedAt>R.updatedAt?D:R});if(C.key===w&&Po(C.goals,$))return;const T=$.flatMap(R=>{const D=A.find(q=>q.goalId===R.goalId),z=D?Rg(D,R):E&&R.status==="review"?{from:"Plan ready"}:null;return z?[{kind:"status",sequence:Jt(),goalId:R.goalId,text:`Goal woke up · ${z.from} · ${wt(R).text}${R.address?` · ${R.address}`:""}`}]:[]}),N=[...C.key===w?C.events:$n,...T].slice(-256),M={key:w,goals:$,events:N};s.current=M,i(M)},n[1]=u):u=n[1];const m=u;let f;n[2]===Symbol.for("react.memo_cache_sentinel")?(f=(w,k)=>{const I=wg(k),E=Nn(w);m(E,I)},n[2]=f):f=n[2];const d=f;let p;n[3]!==e?(p=async w=>{d(w,await e("video_goal",{book_id:w.bookId,notebook_id:w.notebookId,action:"list"},{background:!0}))},n[3]=e,n[4]=p):p=n[4];const g=p;let y;n[5]!==e?(y=async(w,k,I)=>{const E=Vs(await e("video_goal",{...k,book_id:w.bookId,notebook_id:w.notebookId},I?{chat:I}:{background:!0})),C=Nn(w),A=s.current;return(A.key===C||A.key==="")&&m(C,Gg(A.key===C?A.goals:qt,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]!==g?(S={goals:c,events:l,accept:d,refresh:g,act:v},n[7]=v,n[8]=l,n[9]=c,n[10]=g,n[11]=S):S=n[11],S}const qg="Usage: /clip-audio @clip-id gain|mute|fade-in|fade-out <value>",Ug=["gain","mute","fade-in","fade-out"];function Bg(e){const[t,n,o,r]=e,i=n?.toLowerCase();if(!t||!i||o===void 0||r!==void 0||!Kg(i))return{ok:!1,message:qg};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=zg(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 Hg(e,t){if(!e)return{ok:!1,message:"Load the primary sequence first."};const n=ke(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 Wg(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 Kg(e){return Ug.includes(e)}function zg(e){const t=e.toLowerCase();return t==="on"||t==="true"||t==="yes"?!0:t==="off"||t==="false"||t==="no"?!1:null}const Xg=new Set(["/caption","/move","/split-clip","/clip-delete","/gap","/fit","/reframe","/clip-reverse","/clip-audio","/duck","/insert","/overwrite","/clip-trim","/volume"]);function dI(e,t,n){if(e==="/delete"||e==="/trim"||e==="/reverse"){if(!he(n.sequence,t[0]))return{handled:!1}}else if(!Xg.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),f=c?.toLowerCase(),d=f==="clean"||f==="bold"||f==="high-contrast"?f:null,p=l.join(" ").trim();return!Number.isSafeInteger(u)||u<0||!Number.isSafeInteger(m)||m<1||!d||!p?o("Usage: /caption <start-frame> <duration-frames> clean|bold|high-contrast <text>"):r({kind:"caption",timeline_start_frame:u,duration_frames:m,text:p,style_id:d})}if(e==="/move"){const[s,a,c]=t,l=he(i,s),u=Vr(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=Vr(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"):Ut(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?Ut(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=Bg(t);if(!s.ok)return o(s.message);const a=Hg(i,s.clipRef);return a.ok?r(Wg(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]"):Ut(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,f,d]=s,g=n.mentionAssets.find(S=>S.cellAddress.toLowerCase()===m?.toLowerCase())??n.assets.find(S=>S.id===m||S.artifactId===m),y=Number(f),v=d===void 0?void 0:Number(d);return!g||!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:g.artifactId,timeline_start_frame:y,...v===void 0?{}:{duration_frames:v}})}if(e==="/clip-trim"||e==="/trim"){const[m,f,d]=s,p=he(i,m),g=Number(f),y=Number(d);return!p||!Number.isSafeInteger(g)||g<0||!Number.isSafeInteger(y)||y<1?o("Usage: /clip-trim @clip-id <start-frame> <duration-frames>"):r({kind:"trim",clip_id:p.clipId,timeline_start_frame:g,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>"):Ut(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=ke(t),o=e.clips.filter(r=>r.clipId.toLowerCase().startsWith(n));return o.length===1?o[0]:void 0}function Vr(e,t){if(!e||!t)return;const n=ke(t),o=e.tracks.filter(r=>r.trackId.toLowerCase().startsWith(n)||r.name.toLowerCase()===n);return o.length===1?o[0]:void 0}function Ut(e,t){return e?.tracks.find(n=>n.trackId===t.trackId)}const Yg="Usage: /export-sequence --aspect 16:9|9:16|1:1 --captions burned|sidecar|omit";function fI(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:Yg}:{ok:!0,orientation:s,captions:a}}const Jg="Usage: /track-add video|audio|caption [name]";function mI(e){const[t,...n]=e,o=t?.toLowerCase();return o!=="video"&&o!=="audio"&&o!=="caption"?{ok:!1,message:Jg}:{ok:!0,kind:o,name:n.join(" ")}}function pI(e,t){if(!t)return{ok:!1,message:"Open a project with a sequence first."};const n=Zg(t),o=e?.trim()??"";if(!o)return{ok:!0,initialFrame:n[0]?.timelineStartFrame??0};const r=Qg(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 Zg(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 Qg(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 jr="Choose a timeline audio clip or the audio asset on the timeline";function gI(e,t,n,o){if(!t)return{ok:!1,message:"Load the primary sequence first."};const r=ke(e);if(!r)return{ok:!1,message:jr};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(!ni(r)){const m=s.filter(f=>f.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:jr};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 eh=["stack","punch","karaoke"],th=["pop","slam","rise"],nh=1,Gr=j().regex(/^#[0-9a-fA-F]{6}$/),oh=te({style:Ze(eh),motion:Ze(th),energySizing:Te(),snapToOnsets:Te(),avoidFaces:Te(),avoidText:Te(),textColor:Gr,hitColor:Gr}).strict(),rh=te({kind:Ze(["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(),ih=te({text:j().min(1),transcriptStart:V().nonnegative(),transcriptEnd:V().nonnegative(),onsetStart:V().nonnegative(),energy:V().min(0).max(1)}).strict(),sh=te({id:j().min(1),frameTime:V().nonnegative(),regions:ae(rh),lines:ae(ae(ih).min(1)).min(1)}).strict(),ah=te({version:ai(nh),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(sh)}).strict(),ch=.8,lh=.5,sn=.92,no=.06,qr=.06,uh=.5,dh=.18,fh=.05,Bt=.02,mh=.3;function Oo(e,t){const n=t?e.onsetStart-e.transcriptStart:0,o=e.transcriptStart+n,r=Math.max(o+fh,e.transcriptEnd+n);return{text:e.text,start:o,end:r,energy:e.energy}}function ph(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 gh(e,t){const n=ph(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 hh(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 bh(e){return{y0:.08,y1:e.targetHeight>e.targetWidth?.86:.92}}function yh(e,t){return t.filter(n=>n.x-Bt<e.x1&&n.x+n.width+Bt>e.x0).map(n=>({y0:n.y-Bt,y1:n.y+n.height+Bt})).sort((n,o)=>n.y0-o.y0)}function _h(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 vh(e){return e.reduce((t,n)=>t===null||n.y1-n.y0>t.y1-t.y0?n:t,null)}function kh(e){return e.reduce((t,n)=>t+(n.y1-n.y0),0)}function wh(e,t,n){const o=yh(e,n);return{candidate:e,span:vh(_h(t,o)),blocked:kh(o)}}function Pn(e){return e.span?e.span.y1-e.span.y0:0}function Ur(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 Sh(e,t){const n=bh(t),o=hh(t).map(s=>wh(s,n,e)),r=o.reduce((s,a)=>Pn(a)>Pn(s)+.02?a:s);if(r.span&&Pn(r)>=mh)return Ur(r.candidate,r.span,t);const i=o.reduce((s,a)=>a.blocked<s.blocked?a:s);return Ur(i.candidate,n,t)}function Ih(e,t){return e.filter(n=>n.kind==="face"?t.avoidFaces:t.avoidText)}function xh(e){return e.map(t=>t.text).join(" ")}function Ah(e){return Math.max(...e.map(t=>t.energy))}function Gs(e,t,n){return Math.min(n,t/(Math.max(e.length,2)*lh))}function qs(e){return e.reduce((n,o)=>n+o*(sn+no),0)-(e.length>0?e[e.length-1]*no:0)}function Eh(e){return e*no}function Ch(e,t,n){const o=t.height*.36,r=e.map(a=>Gs(xh(a),t.width,o)),i=n?r.map((a,c)=>a*(.7+.3*Ah(e[c]))):r.map(()=>Math.min(...r)),s=Math.min(1,t.height/qs(i));return e.map((a,c)=>({words:a,fontSize:Math.round(i[c]*s*10)/10}))}function Mh(e,t,n){const o=n?.7+.3*e.energy:.85;return Math.min(Gs(e.text,t.width,t.height*.6),t.height*.6)*o}function Th(e,t){const n=e.flat(),o=n[0].start-qr,r=n[n.length-1].end+uh,i=t===null?r:Math.min(r,t-qr);return{start:o,end:Math.max(i,o+.1)}}function Rh(e,t){return Oo(e.lines[0][0],t).start}function hI(e,t,n){return e.map((o,r)=>{const i=o.lines.map(f=>f.map(d=>Oo(d,t.snapToOnsets))),s=e[r+1],a=Th(i,s?Rh(s,t.snapToOnsets):null),c=Ih(o.regions,t).map(f=>gh(f,n)),l=Sh(c,n),u=Ch(i,l,t.energySizing),m=qs(u.map(f=>f.fontSize));return{id:o.id,start:a.start,end:a.end,column:l,lines:u,blockTop:l.y+(l.height-m)/2}})}function $h(e,t){return e.find(n=>t>=n.start&&t<n.end)??null}function Nh(e,t){return Lo((e.end-t)/dh)}function Ph(e,t){return e.lines.flatMap(n=>n.words).filter(n=>n.start<=t).pop()??null}const Oh={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:Lo(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 Lo(e){return e<0?0:e>1?1:e}function Lh(e,t,n){const o=t>=e.start;return o&&t<e.end||o&&e.energy>=ch?n.hitColor:n.textColor}function Fh(e,t,n,o,r){const i=t-e.start,s=Lh(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=Oh[n.motion],c=Lo(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 Br=[{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}],Dh=.03;function bI(e){const t=e&&typeof e=="object"?e:{};return{analysis:ah.parse(t.analysis),settings:oh.parse(t.settings),cached:t.cached===!0}}function yI(e,t){return!e||!t?"landscape":t>e?"portrait":e===t?"square":"landscape"}function _I(e,t){const n=Br.find(o=>o.id===t)??Br[0];return{sourceWidth:e.sourceWidth,sourceHeight:e.sourceHeight,targetWidth:n.width,targetHeight:n.height}}function vI(e,t){return e.phrases.flatMap((n,o)=>n.lines.flat().map((r,i)=>{const s=Oo(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)>=Dh}}))}function kI(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 wI(e,t){return e.findIndex(n=>t>=n.start&&t<n.end)}function SI(e){return e.column.side==="center"?"stack centered":`stack ${e.column.side}`}function II(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 xI(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 AI(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 EI(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 CI(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 oo=["image","gen","video","audio","work"],Vh={audio:"Audio",gen:"Gen",image:"Images",video:"Videos",work:"Work"},jh=["image","gen","video"];function Us(e){const t=pi(e);return t==="data"||t==="goal"?"work":t}function ro(e){return Vh[e]}function Gh(e){return e.map(ro).join(" · ")}function qh(e,t){const n=new Set;for(const o of e)o.slot.row===t&&n.add(Us(o.type));return oo.filter(o=>n.has(o))}function Uh(e,t,n,o){if(t.length===0){const r=o?jh[e]:void 0;return r?{caption:ro(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:ro(r),continuation:i,families:t,family:r,kind:"homogeneous",row:e}}return{caption:Gh(t),continuation:!1,families:t,family:null,kind:"mixed",row:e}}function MI(e,t){const n=e.length===0,o=[];let r=[];for(let i=0;i<t;i+=1){const s=qh(e,i),a=Uh(i,s,r,n);o.push(a),r=s}return o}function TI(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 On(e,t){return e.slot.row-t.slot.row||e.slot.column-t.slot.column||e.id.localeCompare(t.id)}function Bh(e,t={}){const n=e.cells.filter(g=>g.type==="goal").sort(On);if(n.length===0)return e;const o=new Set(n.flatMap(g=>Array.isArray(g.inputs?.characters)?g.inputs.characters.flatMap(y=>y&&typeof y=="object"&&"cellId"in y&&typeof y.cellId=="string"?[y.cellId]:[]):[])),r=new Set(e.edges.filter(g=>e.cells.some(y=>y.id===g.source&&y.type==="generate_image")).map(g=>g.target)),i=[...e.cells].sort((g,y)=>g.id.localeCompare(y.id)),s=e.cells.filter(g=>g.type==="image"&&(o.has(g.id)||!r.has(g.id)&&!g.inputs?.producerCellId&&!g.inputs?.mediaRole)).sort(On),a=new Set(s.map(g=>g.id)),c=i.filter(g=>g.type.startsWith("generate_")||g.type==="prompt"),l=i.filter(g=>g.type==="image"&&!a.has(g.id)),u=i.filter(g=>g.type==="video"),m=e.cells.filter(g=>g.type==="timeline").sort(On),f=new Map;let d=0;const p=(g,y=0,v=1)=>{g.forEach((S,w)=>f.set(S.id,{row:d+Math.floor(w/X),column:w%X})),d+=Math.max(v,Math.ceil((g.length+y)/X))};p(s,0,0),p([...n,...c],t.generators),p(l,t.images),p(u,t.videos);for(const g of m)f.set(g.id,{row:d,column:0}),d+=1;if(d+=t.timelines??0,p(i.filter(g=>!f.has(g.id)),0,0),d>de)throw new Error(`The goal layout needs ${d} rows, but the grid supports ${de}. Remove unused cells before continuing.`);return{...e,cells:e.cells.map(g=>({...g,slot:f.get(g.id)}))}}function Ln(e,t){return{ok:!1,code:e,message:t}}function Hh(e){return[...e].sort((t,n)=>t.slot.row-n.slot.row||t.slot.column-n.slot.column||t.id.localeCompare(n.id))}function Wh(e){return e<=0?0:Math.ceil(e/X)}function RI(e){if(new Map(e.cells.map(c=>[c.id,c])).size!==e.cells.length)return Ln("invalid-edge","Cannot auto-arrange a notebook with duplicate cell IDs.");if(e.cells.some(c=>c.type==="goal"))try{const c=Bh(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 Ln("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 Hh(e.cells))c.type!=="timeline"&&n[Us(c.type)].push(c.id);const i=oo.reduce((c,l)=>c+Wh(n[l].length),0);if(i+r.size>de)return Ln("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 oo){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,f]of l.slice(u,u+X).entries())s.push({id:f,row:a,column:m});a+=1}}return{ok:!0,rowCount:Math.max(a,...o.map(c=>c.slot.row+1)),slots:s}}function $I(e,t=n=>window.requestAnimationFrame(n)){t(()=>{t(()=>{e()?.scrollTo({left:0,top:0,behavior:"smooth"})})})}function Fn(e){return`${e.row}:${e.column}`}function Hr(e){return[...e].sort((t,n)=>t.slot.row-n.slot.row||t.slot.column-n.slot.column)}function Kh(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=Hr(e.cells.filter(g=>t.has(g.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((g,y)=>Kh(n,o,y)),a=new Set(s.map(Fn));if(e.cells.some(g=>g.type==="timeline"&&Ee(g).some(y=>a.has(Fn(y)))))return{ok:!1,code:"capacity",message:"Choose an arrangement that leaves the timeline row free."};const c=Hr(e.cells.filter(g=>!t.has(g.id)&&a.has(Fn(g.slot)))),l=new Set([...r.map(g=>g.id),...c.map(g=>g.id)]),u=[...e.cells.filter(g=>!l.has(g.id)).flatMap(Ee),...s],m=si(u,c.length),f=[...r.map((g,y)=>({id:g.id,...s[y]})),...c.map((g,y)=>({id:g.id,...m[y]}))],d=new Map(e.cells.map(g=>[g.id,g.slot])),p=f.filter(g=>{const y=d.get(g.id);return y?.row!==g.row||y?.column!==g.column}).length;return{ok:!0,slots:f,movedCount:p,displacedCount:c.length}}function Wr(e){return[...e].sort((t,n)=>t.slot.row-n.slot.row||t.slot.column-n.slot.column)}function zh(e,t){const n=(e.row*X+e.column+t)%Yt;return{row:Math.floor(n/X),column:n%X}}function Xh(e){return Yt-new Set(e.map(ve)).size}function PI(e,t,n){const o=Wr(e.cells.filter(d=>t.has(d.id)));if(o.length===0)return{ok:!1,code:"no-images",message:"No image cells in this notebook to group."};if(o.length>Yt)return{ok:!1,code:"capacity",message:`Cannot group ${o.length} images: the grid fits ${Yt}.`};const r=o.map((d,p)=>zh(n,p)),i=new Set(r.map(ve));if(e.cells.some(d=>d.type==="timeline"&&Ee(d).some(p=>i.has(ve(p)))))return{ok:!1,code:"capacity",message:"Choose an arrangement that leaves the timeline row free."};const s=Wr(e.cells.filter(d=>!t.has(d.id)&&i.has(ve(d.slot)))),a=new Set([...o.map(d=>d.id),...s.map(d=>d.id)]),c=[...e.cells.filter(d=>!a.has(d.id)).flatMap(Ee),...r];if(s.length>Xh(c))return{ok:!1,code:"grid-full",message:ca};const l=si(c,s.length),u=[...o.map((d,p)=>({id:d.id,...r[p]})),...s.map((d,p)=>({id:d.id,...l[p]}))],m=new Map(e.cells.map(d=>[d.id,d.slot])),f=u.filter(d=>{const p=m.get(d.id);return p?.row!==d.row||p?.column!==d.column}).length;return{ok:!0,slots:u,movedCount:f,displacedCount:s.length}}function Yh(e,t){return`Generation was interrupted (${e?.trim()||`Notebook run ${t}`}). Clear the slot to reset the cell, then generate again.`}function OI(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 LI(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:Yh(e.job.errorMessage,e.job.state)}:{kind:"continue",sawRun:e.sawRun||e.observation.state==="active"}}function FI(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 DI(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 Jh=new Set(["download_video","process_image","process_video","process_audio","process_upload","complete_kie_task","generate_media"]);function VI(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")&&Jh.has(c.type));if(t?.status==="error"||a){const c=t?.status==="error"?n.find(l=>l.artifactId===e&&l.type==="render_project"&&(l.state==="failed"||l.state==="aborted")):void 0;return{kind:"failed",message:a?.error?.message??c?.error?.message??x(o)??"Media processing failed"}}return{kind:"continue"}}function yn(e,t){return Object.fromEntries(t.flatMap(n=>e[n]===void 0?[]:[[n,e[n]]]))}function St(e,t,n){const o=x(e[t]);if(!o)throw new Error(n);return o}function Zh(e){return{type:"video",artifactId:St(e,"output_artifact_id","The extracted clip did not return an artifact for the notebook"),inputs:{sourceOperation:"extract_video_clip",...yn(e,["source_asset_id","start_time","end_time","duration","job_id"])}}}function Qh(e){const t=yn(e,["source_asset_id","chunk_a_end","chunk_b_start","overlap_sec","job_id"]);return[{type:"video",artifactId:St(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:St(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 eb(e){return{type:"audio",artifactId:St(e,"audio_asset_id","The cover song did not return an audio artifact for the notebook"),inputs:{sourceOperation:"make_cover_song",...yn(e,["source_asset_id","source_kind","duration_seconds","job_id"])}}}function Bs(e){const t=e.additional_asset_ids??e.additional;return Array.isArray(t)?t.flatMap(n=>{const o=x(n);return o?[o]:[]}):[]}function tb(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=Bs(t);return{type:"video",artifactId:St(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}:{},...yn(t,["overlap","transition_seconds","alignment_mode","job_id"])}}}function nb(e,t,n){const o=x(e.source_asset_id),r=o?t.find(i=>!Ge(i)&&i.outputArtifactId===o):void 0;return mn(t,r?[r.slot]:[],n)}function ob(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),...Bs(e)].filter(c=>c!==null)),i=t.filter(c=>c.outputArtifactId&&r.has(c.outputArtifactId)&&!Ge(c)).map(c=>c.slot),s=[...t],a=[];for(let c=0;c<n;c+=1){const l=yo(s,i,o);a.push(l),s.push({type:"video",slot:l})}return a}function jI(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"?[Zh(r)]:e==="split_video"?Qh(r):e==="make_cover_song"?[eb(r)]:[tb(e,r)]).filter(c=>!n.some(l=>!Ge(l)&&l.outputArtifactId===c.artifactId));if(s.length===0)return[];const a=e==="make_cover_song"?[nb(r,n,o)]:ob(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 rb(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 ib(e,t){const n=h(e.execution),o=n?h(n[t]):null,r=x(o?.status),i=x(o?.runId);return r&&i&&ln(r)?i:null}function Kr(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 GI(e){const t=Mo(e.document,e.command.sourceReference),n=t.id,o=Z(t),r=e.expectedRevision?{expected_revision:e.expectedRevision}:{},i=rb(e.document,t.id);if(i){const l={actionCellId:i.id,actionAddress:Z(i),outputCellId:i.id,reusedAction:!0,sourceCellId:n,sourceAddress:o},u=ib(e.document,i.id);if(u)return{...l,jobId:"",runId:u};const m=Kr(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,...Kr(s),reusedAction:!1,sourceCellId:n,sourceAddress:o}}function sb(e){const t=Number(e);return Number.isFinite(t)&&t>=0?Math.round(t*1e3)/1e3:null}async function qI(e){const t=e.command.frameMode==="time"?sb(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=Mo(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 zr="2026-07-28",ab=21*6e4;function cb(e){return e==="apply_watermark"?ab:void 0}async function Hs(e,t){const n=new la({name:t,version:"0.1.0"},{capabilities:{},supportedProtocolVersions:[zr],versionNegotiation:{mode:{pin:zr}}});try{return await n.connect(new ua(new URL(e))),n}catch(o){throw await n.close(),o}}function lb(e,t,n){const o=cb(t);return e.callTool({name:t,arguments:n},o===void 0?void 0:{timeout:o})}function ub(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 db(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 Ie(e,t,n){return db(await e.callTool({name:t,arguments:n}))}function Xr(e){try{return window.localStorage.getItem(e)??""}catch{return""}}async function fb(e){const[t,n,o]=await Promise.all([Ie(e,"list_books",{sort:"newest"}),Ie(e,"slash_commands",{detail:"full"}),Ie(e,"list_chat_models",{})]),r=Array.isArray(t)?t:[],i=ub(r.map(h).filter(v=>v!==null),Xr("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,f]=await Promise.all([Ie(e,"list_notebooks",{book_id:s}),Ie(e,"list_assets",{book_id:s,sort:"newest",limit:200,include_referenced:!0}),Ie(e,"get_primary_sequence",{book_id:s}),Ie(e,"list_jobs",{book_id:s,limit:200}),Ie(e,"list_ingest_status",{book_id:s,limit:200}),Ie(e,"list_notebook_actions",{book_id:s})]),d=Array.isArray(a)?a.map(h).filter(v=>v!==null):[],p=Xr(`videobook.active-notebook:${s}`),g=d.find(v=>v.id===p)??d[0],y=typeof g?.id=="string"?g.id:"";return{bookValue:t,commandValue:n,chatModelValue:o,bookId:s,notebookValue:a,notebookId:y,assetValue:c,sequenceValue:l,jobValue:u,ingestStatusValue:m,actionValue:f}}async function UI(){const e=new URL("/mcp",window.location.origin).toString(),t=await Hs(e,"videobook-bootstrap");try{return await fb(t)}finally{await t.close()}}const io="gpt-6-astra",mb={defaultModel:"gpt-6-astra",models:[{id:io,label:"Astra",description:"Routes every composer request and configures its tools"}]};function pb(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===io?[{id:s.id,label:s.label,description:s.description}]:[]}):[],o=io,r=n.some(i=>i.id===o)?o:n[0]?.id;return r?{defaultModel:r,models:n}:mb}function BI(e,t){return e.models.some(n=>n.id===t)?t:e.defaultModel}function Yr(e){return e instanceof Error?e:new Error(String(e))}function gb({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)},f=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")}),d())},o({state:"ready",error:null})}catch(S){if(!s||v!==c)return;o({state:"failed",error:Yr(S)}),d()}},d=()=>{!s||l!==null||(l=i(()=>{l=null,f()},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=Yr(k);throw s&&a===w&&(a=null,u(w),o({state:"failed",error:I}),d()),I}},start:()=>{s||(s=!0,f())},stop:()=>{if(!s)return;s=!1,c+=1,m();const v=a;a=null,v&&u(v)}}}function HI(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 g=gb({connect:()=>Hs(n,o),callTool:lb,reconnectDelayMs:r,scheduleTimer:bb,cancelTimer:hb,onStateChange:y=>{a(y.state),l(y.error)}});return i.current=g,g.start(),()=>{i.current===g&&(i.current=null),g.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 f;t[5]===Symbol.for("react.memo_cache_sentinel")?(f=async(g,y)=>{const v=i.current;if(!v)throw new Error("MCP server is not ready");return v.callTool(g,y)},t[5]=f):f=t[5];const d=f;let p;return t[6]!==c||t[7]!==s?(p={state:s,error:c,callTool:d},t[6]=c,t[7]=s,t[8]=p):p=t[8],p}function hb(e){return window.clearTimeout(e)}function bb(e,t){return window.setTimeout(e,t)}function WI({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])}const yb=/^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/iu;function Fo(e){return yb.test(e.trim())}function KI(e){const t=e.trim();return Fo(t)?{ok:!0,languageCode:t}:{ok:!1,message:"A quick prompt can only set a language code on a pending transcription, for example /apply en."}}function zI(e){return e.assetId?e.languageCode.trim()&&!Fo(e.languageCode)?{blocking:"Language must be a code such as en or pt-br, or left blank to auto-detect.",notice:null}:{blocking:null,notice:null}:{blocking:"Choose a video or audio clip.",notice:null}}function XI(e){const t=e.languageCode.trim();return{book_id:e.bookId,asset_id:e.assetId,diarize:e.diarize,tag_audio_events:e.tagAudioEvents,wait:!1,...t?{language_code:t}:{}}}function YI(e){const t=Array.isArray(e?.warnings)?e.warnings.filter(i=>typeof i=="string"):[],n=typeof e?.usd=="number"?e.usd:null,o=t.length>0&&t.every(i=>i.includes("historical average per call")),r=n===null||t.length>0&&!o;return{usd:r?null:n,unavailable:r}}function Ws(e,t){const n=t.get(e.artifactId);return n?`@${n}`:e.label||e.artifactId}function _b(e,t,n){const o=t.find(i=>i.artifactId===e);if(o)return o;const r=e.toLowerCase();for(const[i,s]of n)if(s.toLowerCase()===r)return t.find(a=>a.artifactId===i);return t.find(i=>i.label.toLowerCase()===r)}function JI(e){const t=e.assetRef?.trim()??"",n=t.replace(/^@/,"");if(n){const r=_b(n,e.assets,e.addressByArtifactId);return r?We(r.type)?{ok:!0,assetId:r.artifactId}:{ok:!1,message:`Transcribe applies to video or audio; ${Ws(r,e.addressByArtifactId)} is ${r.type}`}:{ok:!1,message:`No asset found for ${t}`}}const o=e.selectedCell?.outputArtifactId??null;if(o&&We(e.selectedCell?.type??"")){const r=e.assets.find(i=>i.artifactId===o);if(r&&We(r.type))return{ok:!0,assetId:r.artifactId}}if(e.preview&&We(e.preview.type)){const r=e.assets.find(i=>i.artifactId===e.preview?.assetId);if(r&&We(r.type))return{ok:!0,assetId:r.artifactId}}return{ok:!0,assetId:null}}function ZI(e,t){return e.filter(n=>We(n.type)).map(n=>({artifactId:n.artifactId,label:Ws(n,t),type:n.type,mediaUrl:n.mediaUrl,thumbnailUrl:n.thumbnailUrl,duration:n.duration})).sort((n,o)=>n.label.localeCompare(o.label))}function be(e,t){return{kind:"refused",outcome:{status:e,message:t}}}function se(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu," ").trim()}function vb(e){return e.map(t=>t.title).join(", ")}function Ks(e){return e.length>0?e.map(t=>t.label).join(", "):"no settings"}function so(e){return e.options.map(String).join(", ")}function kb(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 wb(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 Sb(e){return typeof e=="string"&&["default","auto","automatic"].includes(se(e))}function Ib(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 ${so(e)}.`}:{kind:"setting",name:e.name,value:n}}function xb(e,t,n){const o=kb(e,n);if(!o)return{error:`This review has no "${e}" setting. It has ${Ks(n)}.`};if(Sb(t))return o.required?{error:`${o.label} has no default. It takes ${so(o)}.`}:{kind:"setting",name:o.name,value:void 0};if(o.valueType==="boolean"){const s=wb(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 Ib(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 ${so(o)}.`}:{kind:"setting",name:o.name,value:i??r}}function Ab(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 ${vb(t)}.`}}function QI(e,t){if(t.kind==="none")return be("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?be("review","Revise the model and settings first, then apply. Apply only takes a new prompt."):n&&t.kind==="chain-step"?be("review","A chain step can't be rewritten. Apply it as it stands, or cancel the chain."):n&&t.kind==="transcribe"?Fo(n)?{kind:"command",input:`/apply ${n.trim()}`}:be("review","A transcription review only takes a language code, for example en. Apply it as it stands, or cancel it."):n&&t.kind!=="generation"?be("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 be("review","A chain step can't be revised. Apply it, or cancel to stop the whole chain.");if(t.kind!=="generation")return be("review","Only a generation review has a prompt, a model and settings to revise.");if(!n&&!r&&o.length===0)return be("review",`Say what to change: the prompt, the model, or one of ${Ks(t.action.controls)}.`);const i=[];if(r){const c=Ab(r,t.models);if("error"in c)return be("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=xb(c,l,a);if("error"in u)return be("review",u.error);i.push(u)}return{kind:"revise",edits:i}}const ex={target:null,sources:[]};function tx(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 Eb(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 Cb=2;function nx(e,t,n={}){(n.scheduleFrame??(r=>window.requestAnimationFrame(r)))(()=>{const r=e();if(!r)return;const i=Eb({...t,clientHeight:r.clientHeight,scrollHeight:r.scrollHeight});Math.abs(i-r.scrollTop)<=Cb||r.scrollTo({top:i,behavior:n.reducedMotion?"auto":"smooth"})})}function ox(e,t){return t.some(n=>{const o=ri(n.address);return o?(fs(e,o)?.id??null)!==n.cellId:!0})}const Jr=["#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 Zr(e,t){return typeof e=="boolean"?e:t}function ye(e){const t=e>1?e/1e3:e;return Math.min(1,Math.max(0,t))}function Mb(e){if(Array.isArray(e)&&e.length>=4){const f=re(e[0]),d=re(e[1]),p=re(e[2]),g=re(e[3]);if(f===null||d===null||p===null||g===null)return null;const y=ye(f),v=ye(d);return{x:y,y:v,width:Math.max(0,ye(p)-y),height:Math.max(0,ye(g)-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=ye(n),l=ye(o),u=r===null?s===null?null:ye(s)-c:ye(r),m=i===null?a===null?null:ye(a)-l:ye(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 Tb(e,t){let n=t;for(const o of e)n=(n<<5)-n+o.charCodeAt(0)|0;return Jr[Math.abs(n)%Jr.length]}function Rb(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)??Tb(o,t),box:Mb(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:Zr(r?.remove??n.removable,!0),exactEdit:Zr(r?.exact_edit??r?.exactEdit??n.exact_edit,!1)}}function $b(e,t){return e==="idle"||e==="analyzing"||e==="ready"||e==="failed"?e:t}function rx(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=Rb(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:$b(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 Nb(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 Pb=3e3,Ob=27*6e4;function Lb(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 ix({initialMap:e,read:t,publish:n,isCurrent:o,now:r=Date.now,wait:i=Lb,intervalMs:s=Pb,timeoutMs:a=Ob}){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 Nb(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 Db={transcript:["transcribe","transcribe_video_audio"],analysis:["analyze_video"]};function Vb(e){return e==="transcript"?"Transcription failed":"Video analysis failed"}function sx(e){const t=e.jobs.filter(o=>o.artifactId===e.artifactId&&Db[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??Vb(e.insight)}:t.some(o=>o.state==="done")?{kind:"ready"}:e.hasInsight&&!e.hadInsight?{kind:"ready"}:{kind:"continue"}}const jb=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 ax(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 Gb(e){return e.content?.find(n=>n.type==="text")?.text??null}function cx(e){const t=e,n=Gb(e);if(t.isError)throw new Error(n??"MCP tool failed");if(!n)return null;try{return JSON.parse(n)}catch{return n}}function lx(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 qb(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 ux(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:qb(s?.review)}]}):[];return{chainId:n,status:o,error:b(t?.error),awaitingStepId:b(t?.awaiting_step_id),steps:r}}function dx(e){const t=h(e);return b(t?.artifact_id)!==null&&b(t?.assetId)!==null&&b(t?.job_id)?.startsWith("download-")===!0}function fx(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),f=b(t?.effect),d=b(o?.reason),p=o?.required;if(r!=="chat-action-plan"||!i||!s||!a||!c||!l||!n||!m||f!=="mutation"&&f!=="generation"&&f!=="view"||typeof p!="boolean"||!d)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:f,confirmation:{required:p,reason:d}}}function zs(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 mx(e){return zs([e])[0]??null}function Ub(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||!jb.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 Bb(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=Ub(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),f=c&&b(c.targetInput??c.target_input);return l&&u&&m&&f?[{id:l,source:u,target:m,targetInput:f}]:[]}):[];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}:{},...h(t.generation_settings_memory)?{generationSettingsMemory:kd(h(t.generation_settings_memory))}:{},cells:i,edges:s}}function Hb(e){return Array.isArray(e)?e.flatMap(t=>{const n=Bb(t);return n?[n]:[]}):[]}function Xs(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,f=h(t.analysis_info??t.analysisInfo),d=f&&F(f.source_duration_seconds??f.sourceDurationSeconds),p=Array.isArray(f?.shots)?f.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:$}]:[]}):[],g=f?.llm_exchanges??f?.llmExchanges,y=Array.isArray(g)?g.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=d!==null?{sourceDurationSeconds:d,llmExchanges:y,outputJson:f?.output_json??f?.outputJson??null,outputUrl:b(f?.output_url??f?.outputUrl),shots:p}: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:ff(t.transcript),visionAnalysis:mf(t.vision_analysis??t.visionAnalysis),tags:Ei(t.tags)}}function Wb(e){const t=h(e);return(Array.isArray(e)?e:Array.isArray(t?.assets)?t.assets:[]).flatMap(o=>{const r=Xs(o);return r?[r]:[]})}function Kb(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 px(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=Xs(u);if(!m)return[];const f=(u&&b(u.owning_book_id))??t?.owningBookId,d=(u&&b(u.owning_book_name))??t?.owningBookName,p=h(u?.assetWork),g=h(p?.meta),y=b(h(g?.error)?.message),v=(u&&b(u.last_used_at))??null;return f&&d?[{...m,owningBookId:f,owningBookName:d,errorMessage:y,lastUsedAt:v}]:[]}),page:{offset:i,limit:s,total:a,hasMore:r?.hasMore===!0},statusCounts:Kb(n?.status_counts??n?.statusCounts),booksWithErrors:c.flatMap(l=>{const u=h(l),m=u&&b(u.book_id),f=u&&b(u.message);return m&&f?[{bookId:m,message:f}]:[]})}}function gx(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 zb(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 Xb(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 Yb(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 Ii(n),n}function Jb(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:_i(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 hx(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:Yb(n.plan),outputArtifactId:b(n.outputArtifactId),error:b(n.error),createdAt:s,updatedAt:a}]}catch{return[]}}):[]}function Zb(e){return Array.isArray(e)?e.filter(t=>{const n=h(t);return n!==null&&typeof n.command=="string"&&typeof n.description=="string"}):[]}function bx(e){if(!e)return null;const t=zs(e.bookValue),n=Hb(e.notebookValue);return{books:t,bookId:e.bookId,notebook:n.find(o=>o.id===e.notebookId)??null,assets:Wb(e.assetValue),ingestStatuses:zb(e.ingestStatusValue),sequence:Xb(e.sequenceValue),jobs:Jb(e.jobValue),commands:Zb(e.commandValue),chatModelCatalog:pb(e.chatModelValue),generationActions:Pd(e.actionValue)}}function ao(e){return e!==null&&Number.isFinite(e)&&e>0}function Qb(e,t){return ao(e)&&ao(t)?`${e}×${t}`:null}function Ys(e,t){const n=e??t;if(!n)return null;const o=jd(n);return{key:"generator",label:o,title:o,announce:`Generator ${o}`,emphasis:"generator"}}function Js(e){return e?{key:"provenance",label:e,title:`Extracted from ${e}`,announce:`Extracted from ${e}`,emphasis:"generator"}:null}function yx(e){const t=Qb(e.width,e.height),n=un(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,Ys(e.tool,e.model),Js(e.provenance)].filter(o=>o!==null)}function _x(e){const t=e.aspectRatio??un(e.width,e.height);return[t?{key:"aspect",label:t,title:"Aspect ratio",announce:`Aspect ratio ${t}`,emphasis:"plain"}:null,Ys(e.tool,e.model),Js(e.provenance)].filter(n=>n!==null)}function vx(e){const t=mo(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 ey(e){return ao(e)?{label:me(Math.floor(e)),seconds:e}:null}function kx(e){return ey(mo(e).durationSeconds)}function wx(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 Sx={title:6,continuity:30,frame:20,storyboard:32,ending:12,video:12};function Ix(e){return e.trim().split(/\s+/u).filter(Boolean).length}function xx(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 Ax(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:ty}=da();function ny(e){return e==="left"?"flex-start":e==="right"?"flex-end":"center"}function oy(e){return e==="left"?"left bottom":e==="right"?"right bottom":"center bottom"}function ry(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 Qr=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=ny(a),t[0]=a,t[1]=m):m=t[1];let f;t[2]!==o?(f=Math.round(o*.2),t[2]=o,t[3]=f):f=t[3];const d=o*sn;let p;t[4]!==o||t[5]!==l?(p=l?0:Eh(o),t[4]=o,t[5]=l,t[6]=p):p=t[6];let g;t[7]!==o||t[8]!==m||t[9]!==f||t[10]!==d||t[11]!==p?(g={display:"flex",justifyContent:m,gap:f,fontSize:o,lineHeight:sn,height:d,marginBottom:p,whiteSpace:"nowrap"},t[7]=o,t[8]=m,t[9]=f,t[10]=d,t[11]=p,t[12]=g):g=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=Fh(w,r,s,o,i);return Ke.jsx("span",{style:{display:"inline-block",opacity:I.opacity,color:I.color,transform:`translateY(${I.translateY}px) scale(${I.scale})`,transformOrigin:oy(a),WebkitTextStroke:u>0?`${u}px ${c.strokeColor}`:void 0,paintOrder:u>0?"stroke fill":void 0,textShadow:ry(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]!==g||t[31]!==y?(v=Ke.jsx("div",{style:g,children:y}),t[30]=g,t[31]=y,t[32]=v):v=t[32],v};function ei(e,t){return{position:"absolute",left:e.x,top:t,width:e.width,display:"flex",flexDirection:"column",fontFamily:ty,fontWeight:400,userSelect:"none",pointerEvents:"none"}}const Ex=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=fa(),{fps:s}=ma(),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 f=$h(n,a);if(!f){u=null;break e}const d=Nh(f,a);if(r.style==="punch"){const p=Ph(f,a);if(!p){u=null;break e}const g=Mh(p,f.column,r.energySizing),y=f.column.y+(f.column.height-g*sn)/2;u=Ke.jsx("div",{style:ei(f.column,y),children:Ke.jsx(Qr,{words:[p],fontSize:g,time:a,fade:d,settings:r,side:f.column.side,finish:o,last:!0})});break e}c=ei(f.column,f.blockTop),l=f.lines.map((p,g)=>Ke.jsx(Qr,{words:p.words,fontSize:p.fontSize,time:a,fade:d,settings:r,side:f.column.side,finish:o,last:g===f.lines.length-1},`${f.id}-${g}`))}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=Ke.jsx("div",{style:c,children:l}),t[11]=c,t[12]=l,t[13]=m):m=t[13],m};export{Fv as $,Qv as A,qv as B,zl as C,$v as D,Zv as E,D_ as F,V_ as G,j_ as H,Jv as I,pv as J,G_ as K,Uv as L,q_ as M,Rv as N,lk as O,uy as P,Dv as Q,yv as R,Ev as S,fn as T,rk as U,ak as V,ck as W,dk as X,Nv as Y,_v as Z,Pv as _,zy as a,vv as a$,Ov as a0,jv as a1,Tv as a2,Yv as a3,Xv as a4,T_ as a5,ju as a6,Ck as a7,O as a8,Qe as a9,kf as aA,Vw as aB,Lw as aC,Gw as aD,wn as aE,Q_ as aF,tv as aG,Mf as aH,Tf as aI,Zw as aJ,Qw as aK,ms as aL,Nf as aM,rS as aN,iS as aO,zw as aP,oS as aQ,Yw as aR,Jw as aS,Xw as aT,xS as aU,AS as aV,ES as aW,Ti as aX,Ul as aY,Gl as aZ,Bn as a_,ve as aa,$k as ab,Nk as ac,me as ad,Pk as ae,Ok as af,$_ as ag,P_ as ah,N_ as ai,Lk as aj,ss as ak,mc as al,n_ as am,rw as an,mw as ao,fw as ap,pw as aq,gw as ar,Mw as as,Sk as at,Nw as au,Pw as av,Ow as aw,jw as ax,Fw as ay,Dw as az,qy as b,W_ as b$,Hv as b0,xv as b1,ds as b2,us as b3,ew as b4,uw as b5,dw as b6,kv as b7,NS as b8,DS as b9,zi as bA,Nm as bB,OS as bC,u_ as bD,Dy as bE,f_ as bF,Et as bG,gi as bH,b as bI,jd as bJ,h as bK,h_ as bL,vx as bM,kx as bN,yx as bO,_x as bP,ey as bQ,ln as bR,m_ as bS,Go as bT,F as bU,wx as bV,Us as bW,pi as bX,g_ as bY,LS as bZ,Xo as b_,FS as ba,GS as bb,qS as bc,Fm as bd,jS as be,v0 as bf,_0 as bg,S0 as bh,Wp as bi,$0 as bj,R0 as bk,N0 as bl,ec as bm,Vy as bn,Gy as bo,jy as bp,s_ as bq,c_ as br,a_ as bs,__ as bt,fo as bu,z_ as bv,Rk as bw,K_ as bx,Kv as by,aS as bz,ly as c,Zf as c$,xx as c0,Ax as c1,fi as c2,ga as c3,Ya as c4,Ry as c5,xt as c6,Ua as c7,tt as c8,Na as c9,To as cA,o0 as cB,r0 as cC,YS as cD,jp as cE,qp as cF,Pp as cG,kp as cH,e_ as cI,Mp as cJ,$p as cK,m0 as cL,wp as cM,t_ as cN,Jp as cO,og as cP,o_ as cQ,i_ as cR,_S as cS,om as cT,nm as cU,cm as cV,am as cW,tm as cX,em as cY,Xf as cZ,lm as c_,lo as ca,ui as cb,Iy as cc,gy as cd,Vo as ce,py as cf,my as cg,vy as ch,by as ci,yy as cj,Id as ck,xd as cl,Eo as cm,dc as cn,Qk as co,wd as cp,lw as cq,Sd as cr,Ce as cs,QS as ct,JS as cu,_e as cv,e0 as cw,t0 as cx,n0 as cy,HS as cz,uv as d,Pe as d$,Jf as d0,r_ as d1,mS as d2,rm as d3,hS as d4,$r as d5,gc as d6,pc as d7,gm as d8,pm as d9,d_ as dA,Tk as dB,Uw as dC,Bw as dD,es as dE,p_ as dF,jk as dG,Vd as dH,ow as dI,qk as dJ,Jk as dK,Yk as dL,Io as dM,ot as dN,qw as dO,sS as dP,Bv as dQ,jf as dR,sI as dS,iI as dT,kt as dU,et as dV,wt as dW,Pr as dX,Rg as dY,Ix as dZ,Sx as d_,xk as da,Ik as db,Ak as dc,Ek as dd,E_ as de,Fk as df,Dc as dg,Tw as dh,Dk as di,We as dj,Vk as dk,iw as dl,Xk as dm,gd as dn,Dd as dp,cs as dq,gn as dr,Tt as ds,cw as dt,aw as du,wo as dv,sw as dw,nw as dx,zk as dy,Kk as dz,gv as e,oI as e$,Z0 as e0,Q0 as e1,eI as e2,J0 as e3,on as e4,Y0 as e5,X0 as e6,to as e7,js as e8,dy as e9,mb as eA,BI as eB,g0 as eC,H0 as eD,G0 as eE,K0 as eF,F_ as eG,rv as eH,Uk as eI,hv as eJ,x0 as eK,Yy as eL,p0 as eM,T0 as eN,uc as eO,ww as eP,ex as eQ,tx as eR,_w as eS,hx as eT,sv as eU,cx as eV,dv as eW,cv as eX,lv as eY,uI as eZ,rI as e_,fy as ea,tI as eb,vg as ec,vt as ed,nI as ee,Cg as ef,Sg as eg,uk as eh,$h as ei,ph as ej,Ex as ek,Ih as el,gh as em,II as en,xI as eo,SI as ep,yI as eq,_I as er,hI as es,vI as et,kI as eu,wI as ev,Br as ew,bx as ex,HI as ey,q0 as ez,gt as f,bi as f$,uS as f0,US as f1,H_ as f2,X_ as f3,Mk as f4,mv as f5,Po as f6,x_ as f7,A_ as f8,I_ as f9,MI as fA,bk as fB,_k as fC,W0 as fD,Jy as fE,Zy as fF,s0 as fG,Ym as fH,af as fI,Sw as fJ,Iw as fK,xw as fL,Aw as fM,Ew as fN,nx as fO,Lg as fP,l_ as fQ,Mo as fR,R_ as fS,L_ as fT,O_ as fU,sx as fV,Nb as fW,Hb as fX,Xb as fY,Pd as fZ,ix as f_,zv as fa,Yb as fb,w_ as fc,k_ as fd,aI as fe,L0 as ff,cI as fg,lI as fh,WI as fi,Bb as fj,Jb as fk,FI as fl,OI as fm,Mc as fn,LI as fo,Wb as fp,VI as fq,Vg as fr,D0 as fs,dg as ft,Gk as fu,O0 as fv,F0 as fw,wk as fx,yk as fy,TI as fz,S_ as g,RI as g$,zs as g0,J_ as g1,gx as g2,Z_ as g3,Y_ as g4,wv as g5,Sv as g6,Zb as g7,pb as g8,ub as g9,gk as gA,ik as gB,mk as gC,Jt as gD,iv as gE,fv as gF,Ic as gG,rx as gH,k0 as gI,w0 as gJ,vw as gK,fx as gL,XI as gM,YI as gN,qo as gO,Wy as gP,Ky as gQ,ky as gR,h0 as gS,b0 as gT,y0 as gU,ev as gV,ov as gW,j0 as gX,Hw as gY,Kw as gZ,xy as g_,U0 as ga,B0 as gb,mx as gc,lS as gd,wS as ge,B_ as gf,Wv as gg,_m as gh,vS as gi,A0 as gj,M0 as gk,ZI as gl,zI as gm,E0 as gn,Oy as go,$y as gp,C0 as gq,BS as gr,Rt as gs,I0 as gt,Iv as gu,PS as gv,hk as gw,tw as gx,pk as gy,du as gz,U_ as h,pI as h$,$I as h0,vk as h1,CS as h2,v_ as h3,M_ as h4,C_ as h5,VS as h6,P0 as h7,kk as h8,al as h9,hy as hA,My as hB,Cy as hC,JI as hD,dx as hE,lx as hF,Bk as hG,WS as hH,mI as hI,fI as hJ,dI as hK,z0 as hL,CI as hM,Lv as hN,DI as hO,wf as hP,Cw as hQ,KS as hR,hn as hS,qm as hT,PI as hU,sk as hV,MS as hW,TS as hX,gI as hY,RS as hZ,$S as h_,bI as ha,AI as hb,EI as hc,nS as hd,tS as he,eS as hf,Vv as hg,fk as hh,Tr as hi,QI as hj,Gv as hk,dS as hl,fS as hm,ZS as hn,yw as ho,Hk as hp,bw as hq,hw as hr,Sy as hs,wy as ht,_y as hu,Ww as hv,V0 as hw,nv as hx,px as hy,ax as hz,By as i,jI as i0,Ay as i1,Ey as i2,kS as i3,ym as i4,mm as i5,Qf as i6,sm as i7,Is as i8,Yf as i9,Uy as iA,KI as iB,ox as iC,fs as iD,NI as iE,cS as iF,GI as iG,qI as iH,Rw as iI,$w as iJ,Zk as iK,zS as iL,XS as iM,dm as iN,fm as iO,UI as iP,yS as ia,gS as ib,bS as ic,um as id,pS as ie,Wk as ig,kw as ih,ux as ii,a0 as ij,u0 as ik,c0 as il,l0 as im,d0 as io,f0 as ip,i0 as iq,Hy as ir,Ty as is,IS as it,SS as iu,b_ as iv,y_ as iw,Py as ix,Ly as iy,Ny as iz,or as j,Pt as k,Bl as l,av as m,Cv as n,bv as o,Fy as p,Av as q,Mv as r,Hl as s,ou as t,Xy as u,ek as v,tk as w,Qy as x,nk as y,ok as z};
|