@conceptcraft/mindframes 0.3.17 → 0.3.19
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/dist/index.js +343 -162
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
3
|
-
var h={id:"mindframes",name:"mindframes",displayName:"Mindframes",description:"CLI tool for Mindframes presentation generation",commands:["mf","mindframes"],apiUrl:"https://www.mindframes.app",docsUrl:"https://docs.mindframes.ai",packageName:"@conceptcraft/mindframes",configDir:".mindframes",apiKeyEnvVar:"MINDFRAMES_API_KEY",apiUrlEnvVar:"MINDFRAMES_API_URL",codexSelfConnectorAppId:"asdk_app_6a2b9629c1608191970dcb3ab374ac55"};import
|
|
4
|
-
`)}function Ar(e){let t=[...e].sort((o,i)=>{if(o.isDefault&&!i.isDefault)return-1;if(!o.isDefault&&i.isDefault)return 1;let a=o.createdAt?new Date(o.createdAt).getTime():0;return(i.createdAt?new Date(i.createdAt).getTime():0)-a}),n=o=>{if(!o)return"-";try{return new URL(o).href}catch{return o.startsWith("http")?o:`https://${o}`}},r=new mn({head:[N.cyan("Name"),N.cyan("Source"),N.cyan("Color"),N.cyan("Logo"),N.cyan("Default"),N.cyan("ID")]});for(let o of t){let i=o.primaryColor?`${N.bgHex(o.primaryColor)(" ")} ${o.primaryColor}`:"-";r.push([o.name,n(o.sourceUrl),i,o.logoUrl?N.green("\u2713"):N.gray("\u2717"),o.isDefault?N.green("\u2605"):"",o.id])}return r.toString()}function pn(e){try{return new Date(e).toLocaleString()}catch{return e}}function re(e){console.log(),console.log(N.bold(e)),console.log(N.gray("\u2500".repeat(e.length)))}function S(e,t){console.log(` ${N.gray(`${e}:`)} ${t??"-"}`)}function ls(e){return JSON.stringify(e,null,2)}function p(e){console.log(ls(e))}import{createHash as As,randomUUID as et}from"crypto";import{readFileSync as Os,statSync as Ps}from"fs";import{basename as Fr}from"path";import{spawnSync as us}from"child_process";import{existsSync as ms,mkdtempSync as ps,rmSync as gs,writeFileSync as fs}from"fs";import{tmpdir as hs}from"os";import{join as Or}from"path";import gn from"ffmpeg-static";var ys=/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/;function bs(e){let t=ys.exec(e);if(!t)return;let n=Number(t[1])*3600+Number(t[2])*60+Number(t[3]);return Number.isFinite(n)&&n>0?n:void 0}function Pr(e,t="audio"){if(e.length===0)return;let n=gn&&ms(gn)?gn:"ffmpeg",r=/^[a-z0-9]+$/i.test(t)?t:"audio",o=ps(Or(hs(),"mf-tts-duration-")),i=Or(o,`speech.${r}`);try{fs(i,e);let a=us(n,["-hide_banner","-i",i],{encoding:"utf8"});return a.error?void 0:bs(a.stderr??"")}finally{gs(o,{force:!0,recursive:!0})}}import xt from"chalk";var c={SUCCESS:0,GENERAL_ERROR:1,AUTH_ERROR:2,NOT_FOUND:3,RATE_LIMIT:4,NETWORK_ERROR:5,INVALID_INPUT:6};async function ws(){let e=Cr(),t=Rr(),n=V();if(!e||!t)return null;try{let r=await fetch(`${n}/.well-known/oauth-authorization-server`);if(!r.ok)return null;let o=await r.json(),i=new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t}),a=Sr();a&&i.set("client_secret",a);let s=await fetch(o.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});if(!s.ok)return vt(),null;let l=await s.json();return wt(l.access_token,l.refresh_token,l.expires_in),l.access_token}catch{return null}}async function _r(){return xe()?Ir()?ws():kr()||null:null}function oe(){return xe()||Oe()}async function A(){if(!oe()){let e=u.commands[0],t=u.apiKeyEnvVar;console.error(xt.red("\u2717 Not authenticated.")),console.error(),console.error(xt.bold("To authenticate, run:")),console.error(xt.cyan(` ${e} login`)),console.error(),console.error(xt.gray(`Or set ${t} environment variable.`)),process.exit(c.AUTH_ERROR)}}function vs(e){return e.length<=14?"****":`${e.slice(0,10)}...${e.slice(-4)}`}function Lr(){let e=le();if(e)return vs(e)}function fn(e){return["cc_slides_","mcp_","cc_sk_","sk_"].some(n=>e.startsWith(n))}import{mkdirSync as xs,readFileSync as ks,writeFileSync as Cs}from"fs";import{homedir as Is}from"os";import{join as Dr}from"path";import Rs from"ajv/dist/2020.js";var hn=new Map;function Nr(){return Dr(Is(),".conceptcraft","schemas")}function Ur(e){return Dr(Nr(),`${e}.json`)}function Ss(e){try{let t=JSON.parse(ks(Ur(e),"utf8"));return typeof t?.catalogVersion=="number"&&t.schema?t:null}catch{return null}}function $s(e,t){try{xs(Nr(),{recursive:!0}),Cs(Ur(e),JSON.stringify(t))}catch{}}async function Ts(e){let t=hn.get(e);if(t!==void 0)return t;try{let n=await qr(e),r={catalogVersion:n.catalogVersion,schema:n.schema};return $s(e,r),hn.set(e,r),r}catch{let n=Ss(e);return hn.set(e,n),n}}function Es(e){let t=e.instancePath.replace(/^\//,"").replace(/\//g,"."),n=t.length>0?t:"(root)",r=e.keyword==="additionalProperties"?`: unknown field "${e.params.additionalProperty}"`:`: ${e.message??"invalid value"}`;return`${n}${r}`}async function kt(e,t){let n=await Ts(e);if(!n)return;let r;try{r=new Rs({allErrors:!0,strict:!1}).compile(n.schema)}catch{return}if(r(t))return;let o=(r.errors??[]).slice(0,10).map(Es);throw new Error(`Request does not match the ${e} contract \u2014 ${o.join("; ")}`)}async function ae(){let e=await _r();if(e)return{Authorization:`Bearer ${e}`};let t=le();return t?{"x-api-key":t}:{}}var O=class extends Error{constructor(n,r,o=1,i="operation_failed",a=!1){super(n);this.statusCode=r;this.exitCode=o;this.errorCode=i;this.retryable=a;this.name="ApiError"}statusCode;exitCode;errorCode;retryable},Vr="Idempotency-Key";function _s(e){return e&&e!=="GET"?{[Vr]:et()}:{}}async function B(e,t={}){let n=V();if(!oe()&&!t.allowUnauthenticated)throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2,"authentication_required");let r=await ae(),o=`${n}${e}`,i={...r,..._s(t.method),...t.headers};t.body&&!t.stream&&(i["Content-Type"]="application/json");let a={method:t.method??"GET",headers:i};t.body&&(a.body=JSON.stringify(t.body));let s;try{s=await fetch(o,a)}catch(g){throw new O(`Network error: ${g instanceof Error?g.message:"Unknown error"}`,0,5,"service_unavailable",!0)}if(!s.ok){let g=await s.text().catch(()=>""),m=Ds(g,s.status),w=1;switch(s.status){case 401:w=2;break;case 403:w=2;break;case 404:w=3;break;case 429:w=4;break;case 500:w=1;break}let v=`[${m.code}] ${m.message}`;throw new O(v,s.status,w,m.code,m.retryable)}return t.stream?s:s.headers.get("content-type")?.includes("application/json")?s.json():s.text()}function Ls(e){switch(e){case 400:return"invalid_input";case 401:return"authentication_required";case 402:return"insufficient_credits";case 403:return"access_denied";case 404:return"not_found";case 429:return"rate_limited";case 503:return"service_unavailable";default:return"operation_failed"}}function Ds(e,t){let n=Ls(t),r=e.trim()||`HTTP ${t}: The request could not be completed.`;try{let o=JSON.parse(e),i=typeof o.error=="object"&&o.error!==null?o.error:void 0;if(o.ok===!1&&typeof i?.code=="string"&&typeof i.message=="string")return{code:i.code,message:i.message,retryable:i.retryable===!0};if(typeof o.error=="string")return{code:/^[a-z][a-z0-9_]+$/.test(o.error)?o.error:n,message:typeof o.message=="string"?o.message:o.error,retryable:t===429||t>=500}}catch{}return{code:n,message:r,retryable:t===429||t>=500}}async function qr(e){return B(`/api/cli/tools/${encodeURIComponent(e)}/schema`)}async function jr(){return B("/api/cli/capabilities",{allowUnauthenticated:!0})}async function T(e,t,n){let r=n?`?teamId=${encodeURIComponent(n)}`:"";return B(`/api/cli/tool-runs/${encodeURIComponent(e)}/${encodeURIComponent(t)}${r}`)}async function y(e,t,n){return B(`/api/cli/tools/${encodeURIComponent(e)}`,{body:t,headers:n?{[Vr]:n}:void 0,method:"POST"})}async function Gr(e,t,n,r=120){let o=0;for(let i=0;i<r;i++){let a;try{a=await T(e,t,n),o=0}catch(s){if(s instanceof O&&s.retryable&&o<2){o+=1,await new Promise(l=>setTimeout(l,2e3));continue}throw s instanceof O?new O(`${s.message} Request ID: ${t}.`,s.statusCode,s.exitCode,s.errorCode,s.retryable):new O(`${s instanceof Error?s.message:"Unknown error"} Request ID: ${t}.`,0,5,"poll_failed",!0)}if(a.done){if(a.error)throw new O(`[${a.error.code??"operation_failed"}] ${a.error.message} Request ID: ${t}.`,500,1,a.error.code??"operation_failed",a.error.retryable);return a}await new Promise(s=>setTimeout(s,(a.nextPollAfterSeconds??2)*1e3))}throw new O(`[operation_timed_out] The background operation timed out. Request ID: ${t}.`,408,1,"operation_timed_out",!0)}function Ct(e){return e.error||e.status==="failed"||e.status==="errored"||e.status==="cancelled"?"failed":e.done||e.status==="completed"?"completed":e.status==="in_progress"?"processing":"pending"}function Ns(e){try{let n=new URL(e).pathname.split("/").pop()?.split(".").pop()?.toLowerCase();return n&&/^[a-z0-9]+$/.test(n)?n:void 0}catch{return}}function Us(e){let t=e.toLowerCase().split(".").pop();return{pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",mp4:"video/mp4",mov:"video/quicktime",mpeg:"video/mpeg",mpg:"video/mpeg",webm:"video/webm",aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",oga:"audio/ogg",ogg:"audio/ogg",wav:"audio/wav",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",html:"text/html",css:"text/css",js:"application/javascript",ts:"text/x-typescript",py:"text/x-python"}[t||""]||"application/octet-stream"}async function se(e,t={}){let n=V();if(!oe())throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2);let r=await ae(),o=Ps(e),i=Fr(e),a=Us(e),s=Os(e),l=As("sha256").update(s).digest("hex"),g=await fetch(`${n}/api/cli/files/upload`,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify({fileMetadata:{lastModified:o.mtimeMs,name:i,type:a,size:o.size},...t.idempotencyKey?{uploadIdentity:{contentSha256:l,idempotencyKey:t.idempotencyKey}}:{}})});if(!g.ok){let $=await g.text();throw new O($||"Failed to get upload URL",g.status,1)}let m=await g.json(),w=new FormData;for(let[$,x]of Object.entries(m.fields||{}))w.append($,x);let v=new Blob([s],{type:a});w.append("file",v,i);let b=await fetch(m.url,{method:"POST",body:w});if(!b.ok)throw new O("Failed to upload file to storage",b.status,1);return{id:et(),name:i,url:m.fileUrl,size:o.size,type:a,selected:!0}}async function Br(e,t){let n=[];for(let r=0;r<e.length;r++){let o=e[r],i=Fr(o);t?.(r,e.length,i);let a=await se(o);n.push(a)}return t?.(e.length,e.length,""),n}async function Wr(e){let t={};for(let[r,o]of Object.entries(e))o!==void 0&&(t[r]=o);let n=t.designBrandReference??t.brandId??t.brandingId;return n!==void 0&&(t.designBrandReference=n,delete t.brandId,delete t.brandingId),y("createSlides",{...t,approvalReceipt:"cli:create"})}async function Kr(e,t=20){let n=new URLSearchParams;return n.set("limit",String(t)),e&&n.set("teamId",e),(await B(`/api/cli/presentations?${n}`)).presentations}async function ge(e){return B(`/api/cli/presentation/${encodeURIComponent(e)}`)}async function Jr(e,t){return B(`/api/cli/presentation/${encodeURIComponent(e)}/speaker-notes`,{body:t,method:"POST"})}async function zr(e,t){return B(`/api/cli/presentation-video/${encodeURIComponent(e)}/narration`,{body:t,method:"POST"})}async function yn(e){let t=V(),n=await fetch(`${t}/api/durable-runs/${encodeURIComponent(e)}/events`,{headers:await ae()});if(!n.ok)throw new O(await n.text(),n.status);return n}async function Xr(e){await B(`/api/cli/presentation/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Hr(e,t={}){let n=V();if(!oe())throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2);let r=await ae(),o=await fetch(`${n}/api/presentations/export`,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify({presentationId:e,options:{includeImages:t.includeImages??!0,includeBranding:t.includeBranding??!0,downloadExternalImages:t.includeExternal??!0}})});if(!o.ok)throw new O(await o.text(),o.status,o.status===404?3:1);return o.arrayBuffer()}async function Yr(e,t,n={}){let r=V();if(!oe())throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2);let o=await ae(),i=new FormData,a=new Blob([e],{type:"application/zip"});i.append("file",a,t),i.append("options",JSON.stringify({dryRun:n.dryRun??!1,remapIds:!0}));let s=await fetch(`${r}/api/presentations/import`,{method:"POST",headers:o,body:i}),l=await s.json();if(!s.ok)throw new O(l.errors?.[0]?.message??"Import failed",s.status,1);return l}async function bn(){return B("/api/cli/branding")}async function Qr(e,t=25){let n=new URLSearchParams;return n.set("limit",String(t)),e&&n.set("search",e),B(`/api/cli/templates?${n}`)}async function Zr(e){return B(`/api/branding/${e}`)}async function eo(e,t,n){return y("extractBranding",{approvalReceipt:n,teamId:t,url:e})}async function ue(){return B("/api/cli/whoami")}async function to(){return B("/api/cli/features")}async function no(e,t,n={}){let r=V();if(!oe())throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2);let o=await ae(),i=await fetch(`${r}/api/presentations/${e}/generate-blog`,{method:"POST",headers:{"Content-Type":"application/json",...o},body:JSON.stringify({documentCreatedAt:t,targetWordCount:n.targetWordCount??300,tone:n.tone??"professional",language:n.language??"en",targetAudience:n.targetAudience??"General Audience",blogFormat:n.blogFormat??"narrative",customInstructions:n.customInstructions??"",includeImages:n.includeImages??!0,includeTableOfContents:n.includeTableOfContents??!1})});if(!i.ok)throw new O(await i.text(),i.status,i.status===404?3:1);return i}async function qs(e){let t=new URLSearchParams;e&&t.set("teamId",e);let n=t.toString();return B(`/api/cli/limits${n?`?${n}`:""}`)}async function ro(e,t,n){let r=await qs(n);if(!r.canGenerate[e]){let o=r.remaining[e]??0,i=r.limits[e]??0;throw i===0?new O(`The "${e}" mode is not available on your ${r.planName} plan. Available modes: ${r.availableModes.join(", ")||"none"}`,403,2):new O(`You have reached your ${e} generation limit for this billing cycle (${r.usage[e]??0}/${i} used). Try a different mode: ${r.availableModes.join(", ")||"none available"}`,403,4)}if(r.maxSlidesPerPresentation!==-1&&t>r.maxSlidesPerPresentation)throw new O(`Maximum ${r.maxSlidesPerPresentation} slides allowed on your ${r.planName} plan (requested: ${t}). Try a different mode: ${r.availableModes.join(", ")||"none available"}`,403,6);return r}function Ms(e){return e.replace(/[\u2014\u2013]/g,"-").replace(/[\u201C\u201D]/g,'"').replace(/[\u2018\u2019]/g,"'").replace(/\u2026/g,"...").replace(/\u00A0/g," ").replace(/[\u2010-\u2015]/g,"-").replace(/[\u2032\u2033]/g,"'")}async function oo(e){let t={...e,text:Ms(e.text)};await kt("generateSpeech",t);let n=await y("generateSpeech",{approvalReceipt:"cli:tts-generate",...t}),r=await Gr("generateSpeech",n.runId),o=r.entity?.url;if(!o)throw new O(`Speech completed without an audio URL. Request ID: ${n.runId}.`,500);let i;try{i=await fetch(o)}catch(w){throw new O(`${w instanceof Error?w.message:"Failed to download speech audio"} Request ID: ${n.runId}.`,0,5,"download_failed",!0)}if(!i.ok)throw new O(`Failed to download speech audio. Request ID: ${n.runId}.`,i.status,5,"download_failed",i.status===429||i.status>=500);let a=r.output??{},s=e.options??{},l=ie(a.format)??Ns(o)??"mp3",g=Buffer.from(await i.arrayBuffer()),m=io(a.durationSec,a.duration,a.duration_s)??Pr(g,l);if(m===void 0)throw new O(`Speech completed without a measurable duration. Request ID: ${n.runId}.`,500,1,"invalid_audio_metadata");return{audioData:g,audioUrl:o,duration:m,cost:ke(a.costUsd)??ke(a.cost)??0,provider:ie(a.provider)??s.provider??"gemini",format:l,requestId:n.runId,voiceId:ie(a.voice_id)??ie(a.voiceId),voice:ie(a.voice),model:ie(a.model),speed:ke(a.speed)??s.speed,language:ie(a.lang)??ie(a.language)??s.language,langApplied:Mr(a.langApplied)??Mr(a.lang_applied),timestamps:Fs(a.timestamps),wordTimings:Vs(a.timestamps??a.timings)}}function io(...e){for(let t of e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()?Number(t):Number.NaN;if(Number.isFinite(n)&&n>0)return n}}function Fs(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n=t.characters,r=t.characterStartTimesSeconds??t.character_start_times_seconds,o=t.characterEndTimesSeconds??t.character_end_times_seconds;if(!(!Array.isArray(n)||!Array.isArray(r)||!Array.isArray(o))&&!(n.length===0||n.length!==r.length||n.length!==o.length||!n.every(i=>typeof i=="string")||!r.every(i=>typeof i=="number"&&Number.isFinite(i))||!o.every(i=>typeof i=="number"&&Number.isFinite(i))))return{characters:n,characterStartTimesSeconds:r,characterEndTimesSeconds:o}}function Vs(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let r=n,o=ie(r.text)??ie(r.word),i=ke(r.start),a=ke(r.end);return o&&i!==void 0&&a!==void 0&&a>=i?[{text:o,start:i,end:a}]:[]});return t.length>0?t:void 0}function ie(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ke(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Mr(e){return typeof e=="boolean"?e:void 0}async function ao(e){let t=e?`/api/cli/tts?provider=${e}`:"/api/cli/tts";return B(t)}async function so(e){let t={...e},n=typeof t.idempotency_key=="string"?t.idempotency_key:void 0;return delete t.idempotency_key,await kt("generateMusic",t),{requestId:(await y("generateMusic",{...t,approvalReceipt:"cli:music-generate"},n)).runId,status:"pending"}}async function wn(e){let t=await T("generateMusic",e);return{requestId:e,status:Ct(t),audioUrl:t.entity?.url,duration:io(t.output?.durationSec,t.output?.duration,t.output?.duration_s),cost:ke(t.output?.costUsd)??ke(t.output?.cost),error:t.error?.message}}async function co(e){return{requestId:(await y("mixAudio",{...e,approvalReceipt:"cli:mix-create"})).runId,status:"pending"}}async function vn(e){let t=await T("mixAudio",e);return{requestId:e,status:Ct(t),outputUrl:t.entity?.url,error:t.error?.message}}async function lo(e){return B("/api/cli/images/search",{method:"POST",body:e})}async function uo(e){return B("/api/cli/videos/search",{method:"POST",body:e})}async function Y(e,t=60,n=2e3){let r=0;for(let o=0;o<t;o++){let i;try{i=await e(),r=0}catch(a){if(a instanceof O&&a.retryable&&r<2){r+=1,await new Promise(s=>setTimeout(s,n));continue}throw a}if(i.status==="completed"||i.status==="failed")return i;await new Promise(a=>setTimeout(a,n))}throw new O("Operation timed out",408,1)}async function mo(e,t,n){return y("getYoutubeTranscript",{...n?{language:n}:{},teamId:t,url:e})}async function po(e,t){let n=await y("scrape",{teamId:t,url:e});return{data:{content:n.content,cost:n.totalCost??0,metadata:{description:"",format:"markdown",tokenUsage:Math.ceil(n.content.length/4)},title:n.title??"",url:n.url},success:!0}}async function go(e){let t={...e},n=typeof t.idempotency_key=="string"?t.idempotency_key:void 0;delete t.idempotency_key,await kt("generateSfx",t);let r=await y("generateSfx",{...t,approvalReceipt:"cli:sfx-generate"},n);return{id:r.runId,requestId:r.runId,status:"pending"}}async function xn(e){let t=await T("generateSfx",e);return{id:t.entity?.id??e,requestId:e,status:Ct(t),audioUrl:t.entity?.url,error:t.error?.message}}async function fo(e){return y("listPresenterOptions",{...e?{voiceLanguage:e}:{}})}async function ho(e){return{requestId:(await y("generateAvatarVideo",{...e,approvalReceipt:"cli:avatar-generate"})).runId,status:"pending"}}async function kn(e){let t=await T("generateAvatarVideo",e);return{durationSec:typeof t.output?.durationSec=="number"?t.output.durationSec:null,error:t.error?.message,requestId:e,status:Ct(t),videoUrl:t.entity?.url}}async function yo(e){return y("lipsyncVideo",{...e,approvalReceipt:"cli:video-lipsync"})}async function bo(){return(await y("listTranslationLanguages",{})).languages}async function wo(e){return y("translateVideo",{...e,approvalReceipt:"cli:video-translate"})}async function vo(e,t,n){return y("createVideo",{...e,approvalReceipt:t},n)}async function xo(e){let{idempotencyKey:t,...n}=e;return y("analyzeVideoReference",n,t)}async function ko(e,t){return Gr("analyzeVideoReference",e,t)}async function Co(e){return y("listCastPresets",e)}async function Io(e){return y("createCastPreset",e,et())}async function Ro(e){return y("updateCastPreset",e,et())}async function So(e){return y("deleteCastPreset",{presetId:e},et())}var $o=[{billing:"free",category:"branding",description:"Attach a social handle to an accessible brand profile.",id:"addBrandSocialHandle",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding social add",operation:"mutation",scopes:["brands:write"],state:"available"},{billing:"free",category:"branding",description:"Add a competitor to an accessible brand profile.",id:"addCompetitor",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding competitor add",operation:"mutation",scopes:["brands:write"],state:"available"},{billing:"delegated",category:"media",description:"Transcribe an uploaded recording and publish the transcript for generation.",id:"analyzeMediaAsset",lifecycle:{mode:"background",status:{cliCommand:"media analyze status",pollAfterSeconds:10}},milestone:"M8",name:"media analyze",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"media",description:"Analyze an uploaded video before using it as a source, motion, blocking, or pacing reference in a video storyboard. The completed status output includes the analysisId required by the storyboard's source-video binding.",id:"analyzeVideoReference",lifecycle:{mode:"background",status:{cliCommand:"video reference status",pollAfterSeconds:10}},milestone:"M8",name:"video reference analyze",operation:"generation",scopes:["media:write"],state:"available"},{billing:"delegated",category:"artifacts",description:"Generate and persist an ad variation set.",id:"createAdSet",lifecycle:{mode:"background",status:{cliCommand:"ad-set status",pollAfterSeconds:10}},milestone:"M6",name:"ad-set create",operation:"generation",scopes:["ad-sets:write"],state:"available"},{billing:"free",category:"agents",description:"Create a scheduled agent from a validated configuration.",id:"createAgent",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent create",operation:"mutation",scopes:["agents:write"],state:"available"},{billing:"free",category:"media",description:"Save one way a cast member appears: a personal presenter (pp_* id), a backdrop, and optionally a voice, under a name unique to that person.",id:"createCastPreset",lifecycle:{mode:"bounded"},milestone:"M8",name:"cast preset create",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Save a markdown, CSV or plain-text document into the Library.",id:"createDocument",lifecycle:{mode:"bounded"},milestone:"M8",name:"document create",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"fixed",category:"media",description:"Generate and persist an image.",id:"createImage",lifecycle:{mode:"background",status:{cliCommand:"image status",pollAfterSeconds:10}},milestone:"M5",name:"image generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Create a Library folder, optionally inside another.",id:"createLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders create",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"dynamic",category:"artifacts",description:"Generate and persist a microsite.",id:"createMicrosite",lifecycle:{mode:"background",status:{cliCommand:"microsite status",pollAfterSeconds:10}},milestone:"M6",name:"microsite create",operation:"generation",scopes:["microsites:write"],state:"available"},{billing:"free",category:"artifacts",description:"Create a standalone poll.",id:"createPoll",lifecycle:{mode:"bounded"},milestone:"M3",name:"poll create",operation:"mutation",scopes:["polls:write"],state:"available"},{billing:"delegated",category:"presentations",description:"Create an MP4 video from a finished presentation, or render an existing presentation-video project.",id:"createPresentationVideo",lifecycle:{mode:"background",status:{cliCommand:"presentation video status",pollAfterSeconds:10}},milestone:"M4",name:"presentation video",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"fixed",category:"presentations",description:"Generate a presentation and persist the resulting deck.",id:"createSlides",lifecycle:{mode:"background",status:{cliCommand:"presentation status",pollAfterSeconds:20}},milestone:"M4",name:"create",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"delegated",category:"media",description:"Generate one video from the opaque text and explicit metadata stored in a pinned storyboard revision.",id:"createVideo",lifecycle:{mode:"background",status:{cliCommand:"video status",pollAfterSeconds:20}},milestone:"M8",name:"video create",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"media",description:"Create a versioned Markdown video storyboard.",id:"createVideoStoryboard",lifecycle:{mode:"bounded"},milestone:"M8",name:"video storyboard create",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"fixed",category:"artifacts",description:"Generate a persisted standalone visual abstract.",id:"createVisualAbstract",lifecycle:{mode:"background",status:{cliCommand:"visual-abstract status",pollAfterSeconds:10}},milestone:"M5",name:"visual-abstract create",operation:"generation",scopes:["visual-abstracts:write"],state:"available"},{billing:"free",category:"media",description:"Retire a saved cast preset. Existing videos keep working; the preset stops being offered.",id:"deleteCastPreset",lifecycle:{mode:"bounded"},milestone:"M8",name:"cast preset delete",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Remove a document from the Library.",id:"deleteDocument",lifecycle:{mode:"bounded"},milestone:"M8",name:"document delete",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"knowledge",description:"Delete a Library folder and its subfolders. Items inside are unfiled, never deleted.",id:"deleteLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders delete",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"artifacts",description:"Edit a standalone poll.",id:"editPoll",lifecycle:{mode:"bounded"},milestone:"M3",name:"poll edit",operation:"mutation",scopes:["polls:write"],state:"available"},{billing:"free",category:"presentations",description:"Apply one atomic edit to a presentation-video draft.",id:"editPresentationVideoDraft",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video edit",operation:"mutation",scopes:["presentations:write","media:read"],state:"available"},{billing:"quota",category:"branding",description:"Extract and persist a reusable brand profile from a URL.",id:"extractBranding",lifecycle:{mode:"background",status:{cliCommand:"branding status",pollAfterSeconds:10}},milestone:"M2",name:"branding extract",operation:"generation",scopes:["brands:write"],state:"available"},{billing:"dynamic",category:"research",description:"Extract normalized text from uploaded or remote content.",id:"extractContent",lifecycle:{mode:"bounded"},milestone:"M1",name:"content extract",operation:"query",scopes:["research:read"],state:"available"},{billing:"free",category:"knowledge",description:"File an artifact into a Library folder, or unfile it.",id:"fileArtifactIntoFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library file",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"agents",description:"Erase every stored version of a scheduled agent's memory. Irreversible.",id:"forgetAgentMemory",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent memory forget",operation:"mutation",scopes:["agents:write"],state:"available"},{billing:"delegated",category:"media",description:"Generate one reusable avatar/presenter clip for composition into a video. Accepts a stock avatar id or a personal presenter's pp_* id (from listPresenterOptions' `personal` group) as avatarId.",id:"generateAvatarVideo",lifecycle:{mode:"background",status:{cliCommand:"avatar status",pollAfterSeconds:10}},milestone:"M8",name:"avatar generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"dynamic",category:"media",description:"Generate music from final video facts or a trusted direct prompt.",id:"generateMusic",lifecycle:{mode:"background",status:{cliCommand:"music status",pollAfterSeconds:10}},milestone:"M7",name:"music generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"delegated",category:"media",description:"Generate an additional look for an existing personal presenter while preserving the same Cast identity.",id:"generatePresenterLook",lifecycle:{mode:"background",status:{cliCommand:"avatar look status",pollAfterSeconds:10}},milestone:"M8",name:"avatar look generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"dynamic",category:"media",description:"Generate SFX from final video facts or a trusted direct prompt.",id:"generateSfx",lifecycle:{mode:"background",status:{cliCommand:"sfx status",pollAfterSeconds:10}},milestone:"M7",name:"sfx generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"dynamic",category:"presentations",description:"Generate persisted speaker notes for a presentation version.",id:"generateSpeakerNotes",lifecycle:{mode:"background",status:{cliCommand:"presentation speaker-notes-status",pollAfterSeconds:5}},milestone:"M4",name:"presentation speaker-notes",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"dynamic",category:"media",description:"Generate speech audio from text.",id:"generateSpeech",lifecycle:{mode:"background",status:{cliCommand:"tts status",pollAfterSeconds:10}},milestone:"M7",name:"tts generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"agents",description:"Read what a scheduled agent has recorded about its own work: learned facts, standing instructions, things it never does, entities it tracks, and freeform notes.",id:"getAgentMemory",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent memory show",operation:"query",scopes:["agents:read"],state:"available"},{billing:"free",category:"branding",description:"List competitors saved for an accessible brand profile.",id:"getBrandCompetitors",lifecycle:{mode:"bounded"},milestone:"M1",name:"branding competitor list",operation:"query",scopes:["brands:read"],state:"available"},{billing:"free",category:"branding",description:"Read a brand's design tokens, the keys it is missing, or its design.md document.",id:"getBrandProfile",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding profile",operation:"query",scopes:["brands:read"],state:"available"},{billing:"free",category:"knowledge",description:"Read a bounded workspace Knowledge Hub bundle.",id:"getKnowledgeBundle",lifecycle:{mode:"bounded"},milestone:"M1",name:"knowledge bundle",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"dynamic",category:"research",description:"Search recent news sources.",id:"getNews",lifecycle:{mode:"bounded"},milestone:"M1",name:"search news",operation:"query",scopes:["research:read"],state:"available"},{billing:"free",category:"presentations",description:"Read a presentation and its slides.",id:"getPresentation",lifecycle:{mode:"bounded"},milestone:"M1",name:"get",operation:"query",scopes:["presentations:read"],state:"available"},{billing:"free",category:"presentations",description:"Read an owned presentation-video project and its ordered scene timeline.",id:"getPresentationVideoProject",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video inspect",operation:"query",scopes:["presentations:read"],state:"available"},{billing:"dynamic",category:"research",description:"Fetch a YouTube video's timestamped transcript with its title, channel, and duration.",id:"getYoutubeTranscript",lifecycle:{mode:"bounded"},milestone:"M1",name:"transcript",operation:"query",scopes:["research:read"],state:"available"},{billing:"free",category:"media",description:"Import a recording from a connected account into the media library.",id:"importConnectorRecording",lifecycle:{mode:"background",status:{cliCommand:"media import status",pollAfterSeconds:5}},milestone:"M8",name:"media import",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"presentations",description:"Import an attached PowerPoint as an auditable, review-gated Mindframes presentation.",id:"importPowerPoint",lifecycle:{mode:"background",status:{cliCommand:"presentation import status",pollAfterSeconds:5}},milestone:"M4",name:"presentation import",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"delegated",category:"media",description:"Re-voice a ready video with new audio via provider lip-sync (one sibling re-voiced video artifact).",id:"lipsyncVideo",lifecycle:{mode:"background",status:{cliCommand:"video lipsync status",pollAfterSeconds:20}},milestone:"M8",name:"video lipsync",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"media",description:"List saved ways a cast member appears \u2014 a trained presenter, a backdrop, and optionally a voice, under one name. Filtered to what the caller may actually use.",id:"listCastPresets",lifecycle:{mode:"bounded"},milestone:"M8",name:"cast preset list",operation:"query",scopes:["media:read"],state:"available"},{billing:"free",category:"knowledge",description:"List the workspace's documents, newest first.",id:"listDocuments",lifecycle:{mode:"bounded"},milestone:"M8",name:"document list",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"free",category:"knowledge",description:"List a document's append-only version history.",id:"listDocumentVersions",lifecycle:{mode:"bounded"},milestone:"M8",name:"document versions",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"free",category:"knowledge",description:"List the workspace Library folder tree.",id:"listLibraryFolders",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders list",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"free",category:"presentations",description:"List saved presentation-video draft versions.",id:"listPresentationVideoVersions",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video versions",operation:"query",scopes:["presentations:read"],state:"available"},{billing:"free",category:"media",description:"List provider-neutral presenter avatars, voices, and voice languages, plus the workspace's trained personal presenters (`personal` roster group, pp_* ids).",id:"listPresenterOptions",lifecycle:{mode:"bounded"},milestone:"M8",name:"avatar options",operation:"query",scopes:["media:read"],state:"available"},{billing:"free",category:"media",description:"List ready generated clips and uploaded MediaAssets while excluding final presentation-to-MP4 renders.",id:"listReusableVideoClips",lifecycle:{mode:"bounded"},milestone:"M8",name:"video library list",operation:"query",scopes:["media:read","presentations:read"],state:"available"},{billing:"free",category:"media",description:"List provider-neutral target languages for video translation.",id:"listTranslationLanguages",lifecycle:{mode:"bounded"},milestone:"M8",name:"video translate-languages",operation:"query",scopes:["media:read"],state:"available"},{billing:"dynamic",category:"media",description:"Mix voice, music, and sound-effect tracks.",id:"mixAudio",lifecycle:{mode:"background",status:{cliCommand:"mix status",pollAfterSeconds:10}},milestone:"M7",name:"mix create",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Move a Library folder under a new parent, or to the top level.",id:"moveLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders move",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"presentations",description:"Create or reuse a presentation-video project for a finished presentation.",id:"preparePresentationVideo",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video prepare",operation:"mutation",scopes:["presentations:write"],state:"available"},{billing:"free",category:"knowledge",description:"Read one document's full body and metadata.",id:"readDocument",lifecycle:{mode:"bounded"},milestone:"M8",name:"document read",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"free",category:"media",description:"Read a video storyboard and its immutable revision history.",id:"readVideoStoryboard",lifecycle:{mode:"bounded"},milestone:"M8",name:"video storyboard show",operation:"query",scopes:["media:read"],state:"available"},{billing:"free",category:"knowledge",description:"Set or clear the colour of a Library folder.",id:"recolorLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders recolor",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"agents",description:"Create a reviewable scheduled-agent recommendation.",id:"recommendAgent",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent recommend",operation:"generation",scopes:["agents:write"],state:"available"},{billing:"free",category:"presentations",description:"Refresh deck-backed video scenes from the latest presentation version.",id:"refreshPresentationVideoSlides",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video refresh",operation:"mutation",scopes:["presentations:write"],state:"available"},{billing:"dynamic",category:"presentations",description:"Regenerate one narration override in a presentation video draft.",id:"regeneratePresentationVideoNarration",lifecycle:{mode:"background",status:{cliCommand:"presentation video-narration-status",pollAfterSeconds:5}},milestone:"M4",name:"presentation video-narration",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"free",category:"knowledge",description:"Rename a Library folder.",id:"renameLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders rename",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"knowledge",description:"Restore an earlier version by appending it as the current one.",id:"restoreDocumentVersion",lifecycle:{mode:"bounded"},milestone:"M8",name:"document restore",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"presentations",description:"Restore a saved presentation-video draft version as a new version.",id:"restorePresentationVideoVersion",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video restore",operation:"mutation",scopes:["presentations:write"],state:"available"},{billing:"delegated",category:"media",description:"Create a new presenter Look by editing an existing Look without changing its source.",id:"revisePresenterLook",lifecycle:{mode:"background",status:{cliCommand:"avatar look revision-status",pollAfterSeconds:10}},milestone:"M8",name:"avatar look revise",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"media",description:"Create a new immutable revision of a Markdown video storyboard.",id:"reviseVideoStoryboard",lifecycle:{mode:"bounded"},milestone:"M8",name:"video storyboard revise",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"dynamic",category:"research",description:"Read and normalize content from a public URL.",id:"scrape",lifecycle:{mode:"bounded"},milestone:"M1",name:"scrape",operation:"query",scopes:["research:read"],state:"available"},{billing:"dynamic",category:"research",description:"Search licensed image providers.",id:"searchImages",lifecycle:{mode:"bounded"},milestone:"M1",name:"search images",operation:"query",scopes:["research:read"],state:"available"},{billing:"dynamic",category:"research",description:"Search the public web for current sources.",id:"searchInternet",lifecycle:{mode:"bounded"},milestone:"M1",name:"search web",operation:"query",scopes:["research:read"],state:"available"},{billing:"free",category:"knowledge",description:"Search workspace Knowledge Hub entries.",id:"searchKnowledge",lifecycle:{mode:"bounded"},milestone:"M1",name:"knowledge search",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"dynamic",category:"media",description:"Find videos: licensed stock clips to download, or web videos to embed.",id:"searchStockVideo",lifecycle:{mode:"bounded"},milestone:"M1",name:"search video",operation:"query",scopes:["media:read"],state:"available"},{billing:"free",category:"branding",description:"Point a brand at an already-uploaded logo, dark-background logo variant, or favicon.",id:"setBrandLogo",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding logo set",operation:"mutation",scopes:["brands:write"],state:"available"},{billing:"free",category:"presentations",description:"Set one presentation-video scene to a specific avatar/look or saved preset, including the preset voice by default, or restore inheritance from the project default.",id:"setPresentationVideoScenePresenter",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video presenter",operation:"mutation",scopes:["presentations:write"],state:"available"},{billing:"free",category:"presentations",description:"Transform an uploaded PowerPoint source into an auditable presentation review.",id:"transformPresentationImport",lifecycle:{mode:"background",status:{cliCommand:"presentation import status",pollAfterSeconds:5}},milestone:"M4",name:"presentation import transform",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"delegated",category:"media",description:"Translate a ready video into sibling language versions (one video per target language).",id:"translateVideo",lifecycle:{mode:"background",status:{cliCommand:"video translate status",pollAfterSeconds:20}},milestone:"M8",name:"video translate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"agents",description:"Add to or remove from what a scheduled agent remembers. Owner or workspace admin only.",id:"updateAgentMemory",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent memory set",operation:"mutation",scopes:["agents:write"],state:"available"},{billing:"free",category:"branding",description:"Write a brand's design tokens from a key patch or a whole design.md document.",id:"updateBrandTokens",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding set",operation:"mutation",scopes:["brands:write"],state:"available"},{billing:"free",category:"media",description:"Change a saved cast preset's name, presenter, backdrop, or voice. Sends the complete preset, not a patch.",id:"updateCastPreset",lifecycle:{mode:"bounded"},milestone:"M8",name:"cast preset update",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Edit a document's body, title or summary under an optimistic lock.",id:"updateDocument",lifecycle:{mode:"bounded"},milestone:"M8",name:"document update",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"presentations",description:"Update avatar, voice, music, captions, format, and renderer settings for a presentation-video project.",id:"updatePresentationVideoSettings",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video settings",operation:"mutation",scopes:["presentations:write"],state:"available"}];function It(e){return{capabilities:$o,catalogVersion:1,reason:e,source:"snapshot"}}async function tt(e=jr){try{let{capabilities:t,catalogVersion:n}=await e();return!Array.isArray(t)||t.length===0?It("the live catalog returned no capabilities"):{capabilities:t,catalogVersion:n,source:"live"}}catch(t){let n=t instanceof Error?t.message:String(t);return It(n)}}var To=["presentations","media","branding","knowledge","research","artifacts","agents"],Bs=80,Ws=30;function Ks(e){return e.billing!==void 0&&e.billing!=="free"&&e.billing!=="quota"}function Js(e){return e.lifecycle?.mode==="background"}function zs(e,t){if(t<=0)return[e];let n=[],r="";for(let o of e.split(/\s+/).filter(Boolean))r===""?r=o:r.length+1+o.length<=t?r=`${r} ${o}`:(n.push(r),r=o);return r!==""&&n.push(r),n.length>0?n:[""]}function Eo(e){let t=To.indexOf(e);return t===-1?To.length:t}function Xs(e,t){let n=t.search?.trim().toLowerCase(),r=t.category?.trim().toLowerCase();return e.filter(o=>r&&(o.category??"").toLowerCase()!==r?!1:n?`${o.name} ${o.description??""}`.toLowerCase().includes(n):!0)}function Hs(e){let t=new Map;for(let i of e){let a=i.category??"other",s=t.get(a);s?s.push(i):t.set(a,[i])}let n=[...t.entries()].sort(([i],[a])=>{let s=Eo(i)-Eo(a);return s!==0?s:i.localeCompare(a)}),r=Math.min(Ws,Math.max(...e.map(i=>i.name.length))),o=[];for(let[i,a]of n){a.sort((s,l)=>s.name.localeCompare(l.name)),o.length>0&&o.push(""),o.push(nt.bold(`${i} (${a.length})`));for(let s of a){let l=`${Ks(s)?"$":" "}${Js(s)?"*":" "}`,g=s.name.padEnd(r),m=2+r+1+l.length+1,w=Math.max(24,Bs-m),v=zs(s.description??"",w);o.push(` ${nt.cyan(g)} ${nt.yellow(l)} ${v[0]??""}`.trimEnd());for(let b of v.slice(1))o.push(`${" ".repeat(m)}${b}`)}}return o}function Ys(e){return e.map(t=>`${t.name} ${t.state} ${t.milestone}`)}function Qs(e,t={filtered:!1}){if(e.length===0)return[t.filtered?"No capabilities match that filter.":"No capabilities available."];if(!e.some(i=>i.description||i.category))return Ys(e);let r=u.commands[0],o=Hs(e);return o.push(""),o.push(nt.dim(`${e.length} capabilities \xB7 $ = paid \xB7 * = background (returns a run id)`)),o.push(nt.dim(`Filter with: ${r} capabilities --search <query>`)),o}var Ao=new Gs("capabilities").description("Index of everything this CLI can do \u2014 every command, grouped and described").option("-f, --format <format>","Output format: human, json, quiet","human").option("-s, --search <query>","Only show capabilities matching a query").option("--category <name>","Only show one category").action(async e=>{try{let t=await tt(),n=Xs(t.capabilities,e),r=!!(e.search||e.category);if(e.format==="json"){p({capabilities:n,catalogVersion:t.catalogVersion,source:t.source,...t.reason?{sourceReason:t.reason}:{}});return}if(e.format==="quiet"){for(let o of n)console.log(o.name);return}t.source==="snapshot"&&M(`Showing the capability list baked into this CLI build (${t.reason}); the deployed catalog may have moved on.`);for(let o of Qs(n,{filtered:r}))console.log(o)}catch(t){d(t instanceof Error?t.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}});import{mkdirSync as nd,writeFileSync as rd}from"fs";import{dirname as Lo,join as od}from"path";import{Command as fe}from"commander";import rt from"chalk";import{input as id,password as ad,confirm as Do,select as sd}from"@inquirer/prompts";import St from"ora";import Zs from"conf";var Rt=new Zs({projectName:"conceptcraft",configName:"feature-cache"}),ed=3600*1e3,td=1440*60*1e3;function Oo(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t=t&t}return t.toString(16)}function Po(){if(!Oe())return null;let e=Rt.get("featureFlags");if(!e)return null;let t=Oo(le());if(e.apiKeyHash&&e.apiKeyHash!==t)return Ie(),null;let n=Date.now()-e.fetchedAt;return n>td?null:(n>ed&&Cn(),e.flags)}function Cn(){Ce().catch(()=>{})}async function Ce(){let e=await to(),t=le();return Rt.set("featureFlags",{flags:e,fetchedAt:Date.now(),apiKeyHash:t?Oo(t):void 0}),e}function Ie(){Rt.delete("featureFlags")}function _o(){return Rt.path}var No=new fe("config").description("Manage CLI configuration: account settings, and the cached feature flags that decide which commands appear").addCommand(new fe("init").description("Initialize configuration interactively").action(async()=>{console.log(),console.log(rt.bold(`${u.displayName} CLI Configuration`)),console.log(rt.gray("\u2500".repeat(35))),console.log();try{let e=await ad({message:"Enter your API key:",mask:"*",validate:r=>!r||r.trim().length===0?"API key is required":fn(r.trim())?!0:"Invalid API key format. Keys should start with 'cc_slides_' or 'mcp_'"});if(ln(e.trim()),await Do({message:`Use a custom API URL? (default: ${u.apiUrl.replace("https://","")})`,default:!1})){let r=await id({message:"Enter API URL:",default:V(),validate:o=>{try{return new URL(o),!0}catch{return"Invalid URL format"}}});un(r)}console.log();let n=St("Verifying API key...").start();try{let r=await ue();if(n.succeed("API key verified!"),console.log(),f(`Logged in as: ${r.user.email}`),r.teams.length===0)M("No teams found for this user.");else if(r.teams.length===1){let o=r.teams[0];Ae(o.id),f(`Team: ${o.name} (${o.planName})`)}else{console.log(),f(`You have access to ${r.teams.length} teams.`);let o=await sd({message:"Select your default team:",choices:r.teams.map(a=>({name:`${a.name} (${a.planName}) - ${a.role}${a.isCurrent?" [current]":""}`,value:a.id})),default:r.currentTeam?.id});Ae(o);let i=r.teams.find(a=>a.id===o);C(`Selected team: ${i?.name}`)}try{await Ce()}catch{}}catch(r){n.fail("Failed to verify API key"),M(`Could not verify API key: ${r instanceof Error?r.message:String(r)}`),M(`You may need to set the team ID manually: ${u.commands[0]} config set team-id <id>`)}console.log(),C("Configuration saved!"),f(`Config file: ${Ze()}`),console.log()}catch(e){if(e.name==="ExitPromptError"){console.log(),f("Configuration cancelled.");return}throw e}})).addCommand(new fe("show").description("Show current configuration").option("--verify","Verify API key and show team details").action(async e=>{let t=xr();if(re("Current Configuration"),console.log(),S("API Key",Lr()??rt.red("Not set")),S("API URL",t.apiUrl),S("Default Team ID",t.defaultTeamId??rt.gray("Not set")),console.log(),S("Config file",Ze()),e.verify&&t.apiKey){console.log();let n=St("Verifying...").start();try{let r=await ue();n.succeed("Verified"),console.log(),S("User",r.user.email),r.currentTeam&&S("Current Team",`${r.currentTeam.name} (${r.currentTeam.planName})`),r.teams.length>1&&S("Total Teams",String(r.teams.length))}catch(r){n.fail("Verification failed"),M(r instanceof Error?r.message:String(r))}}console.log()})).addCommand(new fe("set").description("Set a configuration value").argument("<key>","Configuration key (api-key, api-url, team-id)").argument("<value>","Value to set").action(async(e,t)=>{switch(e){case"api-key":fn(t)||(d("Invalid API key format. Keys should start with 'cc_slides_' or 'mcp_'"),process.exit(6)),ln(t),Ie(),C("API key updated"),Ce().catch(()=>{});break;case"api-url":try{new URL(t),un(t),C(`API URL set to: ${t}`)}catch{d("Invalid URL format"),process.exit(6)}break;case"team-id":Ae(t),C(`Default team ID set to: ${t}`);break;default:d(`Unknown config key: ${e}`),console.log(rt.gray("Valid keys: api-key, api-url, team-id")),process.exit(6)}})).addCommand(new fe("clear").description("Clear all configuration").action(async()=>{try{await Do({message:"Are you sure you want to clear all configuration?",default:!1})?(bt(),Ie(),C("Configuration cleared")):f("Cancelled")}catch{f("Cancelled")}})).addCommand(new fe("refresh").description("Refresh cached feature flags").action(async()=>{let e=St("Refreshing feature flags...").start();try{await Ce(),e.succeed("Feature flags refreshed"),f(`Run '${u.commands[0]} --help' to see updated commands`)}catch(t){e.fail("Failed to refresh"),d(t instanceof Error?t.message:String(t)),process.exit(1)}})).addCommand(new fe("path").description("Show configuration file path").option("--cache","Show feature cache file path").action(e=>{e.cache?console.log(_o()):console.log(Ze())})).addCommand(new fe("pull").description("Pull your account settings (memory, brand, prefs) into a local config.toml").action(async()=>{let e=St("Pulling settings...").start();try{let t=await ae(),n=await fetch(`${V()}/api/cli/settings`,{headers:t});if(!n.ok)throw new Error(`Request failed (HTTP ${n.status})`);let r=await n.text(),o=od(Lo(Ze()),"settings.toml");nd(Lo(o),{recursive:!0}),rd(o,r,"utf8"),e.succeed("Settings pulled"),f(`Written to ${o}`)}catch(t){e.fail("Failed to pull settings"),d(t instanceof Error?t.message:String(t)),process.exit(1)}}));import{Command as dd}from"commander";import{confirm as cd}from"@inquirer/prompts";var Uo=new dd("delete").description("Delete a presentation").argument("<slug>","Presentation slug (e.g., my-presentation-v1-abc123)").option("-f, --force","Skip confirmation prompt").option("-q, --quiet","Suppress output").action(async(e,t)=>{if(await A(),!t.force)try{if(!await cd({message:`Are you sure you want to delete presentation "${e}"?`,default:!1})){t.quiet||M("Deletion cancelled");return}}catch{t.quiet||M("Deletion cancelled");return}try{await Xr(e),t.quiet||C(`Presentation "${e}" deleted`)}catch(n){d(n instanceof Error?n.message:String(n)),process.exit(n.exitCode??1)}});import{Command as _e}from"commander";import Mo from"chalk";import ld from"ora";import{createParser as wf}from"eventsource-parser";import xf from"chalk";import Cf from"ora";async function qo(e,t={}){let n=e.body?.getReader();if(!n)throw new Error("Response body is not readable");let r=new TextDecoder,o="",i=!1;for(;!i;){let a=await n.read();if(i=a.done,a.value){let s=r.decode(a.value,{stream:!0});o+=s,t.quiet||process.stdout.write(s)}}return t.quiet||console.log(),o}function ud(){return new _e("blog").description("Generate a blog post from a presentation").argument("<slug>","Presentation slug").option("--words <count>","Target word count (50-2000)","300").option("--tone <tone>","Writing tone (professional, casual, educational)","professional").option("--audience <text>","Target audience description").option("-f, --format <format>","Output format (human, json, markdown)","human").option("--instructions <text>","Custom instructions for the blog").option("--no-images","Exclude image references").option("--toc","Include table of contents").action(async(e,t)=>{await A();let n=parseInt(t.words,10);(Number.isNaN(n)||n<50||n>2e3)&&(d("Word count must be between 50 and 2000"),process.exit(6));let r=["professional","casual","educational"];r.includes(t.tone)||(d(`Invalid tone. Valid options: ${r.join(", ")}`),process.exit(6));let o=ld("Fetching presentation...").start();try{let i=await ge(e);o.text="Generating blog post...";let a=await no(i.id,i.documentCreatedAt||i.createdAt,{targetWordCount:n,tone:t.tone,targetAudience:t.audience??"General Audience",customInstructions:t.instructions??"",includeImages:!t.noImages,includeTableOfContents:t.toc??!1}),s=await qo(a,{quiet:!0});o.succeed("Blog generated"),t.format==="json"?console.log(JSON.stringify({presentationId:e,title:i.title,wordCount:n,tone:t.tone,content:s},null,2)):t.format==="markdown"?console.log(s):(console.log(),console.log(Mo.bold(`Blog: ${i.title}`)),console.log(Mo.gray("\u2500".repeat(40))),console.log(),console.log(s),console.log())}catch(i){o.fail("Generation failed"),d(i instanceof Error?i.message:String(i)),process.exit(i.exitCode??1)}})}function md(){return new _e("tweets").description("Generate tweets from a presentation").argument("<slug>","Presentation slug").option("--count <n>","Number of tweets to generate","5").option("-f, --format <format>","Output format (human, json)","human").action(async(e,t)=>{await A(),f("Tweet generation coming soon.")})}function pd(){return new _e("linkedin").description("Generate a LinkedIn carousel from a presentation").argument("<slug>","Presentation slug").option("-f, --format <format>","Output format (human, json)","human").action(async e=>{await A(),f("LinkedIn carousel generation coming soon.")})}function gd(){return new _e("questions").description("Generate questions for a presentation").argument("<slug>","Presentation slug").option("--count <n>","Number of questions","10").option("-f, --format <format>","Output format (human, json)","human").action(async(e,t)=>{await A(),f("Question generation coming soon.")})}function fd(){return new _e("cheatsheet").description("Generate a presenter cheat sheet").argument("<slug>","Presentation slug").option("--mode <mode>","Cheat sheet mode (qa-prep, talking-points)","qa-prep").option("-f, --format <format>","Output format (human, json, markdown)","human").action(async(e,t)=>{await A(),f("Cheat sheet generation coming soon.")})}function Fo(){let e=new _e("derive").description("Generate derivative content from a presentation"),t=Po();return t&&(t.deckToBlog&&e.addCommand(ud()),t.deckToTweets&&e.addCommand(md()),t.linkedInCarousel&&e.addCommand(pd()),t.redTeamQuestions&&e.addCommand(gd()),t.presenterCheatSheet&&e.addCommand(fd())),e}import $t from"chalk";import{Command as hd}from"commander";import{writeFile as yd}from"fs/promises";import{resolve as Vo}from"path";import bd from"ora";var In=new hd("export").description("Export a presentation to a ZIP of HTML and its assets").argument("<slug>","Presentation slug (e.g., my-presentation-v1-abc123)").option("-o, --output <path>","Output file path").option("--include-images","Include images (default: true)",!0).option("--include-branding","Include branding (default: true)",!0).option("--no-external","Skip external image downloads").action(async(e,t)=>{await A();let n=bd("Fetching presentation...").start();try{let r=await ge(e),o=r.title||e,i=r.id,a=e.replace(/[^a-z0-9-]/gi,"_").toLowerCase().substring(0,50),s=new Date().toISOString().split("T")[0],l=`${a}_${s}.zip`,g=t.output?Vo(t.output):Vo(process.cwd(),l);n.text=`Exporting "${o}"...`;let m=await Hr(i,{includeImages:t.includeImages,includeBranding:t.includeBranding,includeExternal:!t.noExternal});n.text="Saving file...",await yd(g,Buffer.from(m)),n.succeed("Export complete!"),console.log(),f(`File saved: ${g}`),f(`Size: ${wd(m.byteLength)}`),console.log()}catch(r){n.fail("Export failed"),d(r instanceof Error?r.message:String(r)),process.exit(r.exitCode??1)}});function wd(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}In.addHelpText("after",`
|
|
5
|
-
${$t.bold("Examples:")}
|
|
6
|
-
|
|
3
|
+
var h={id:"mindframes",name:"mindframes",displayName:"Mindframes",description:"CLI tool for Mindframes presentation generation",commands:["mf","mindframes"],apiUrl:"https://www.mindframes.app",docsUrl:"https://docs.mindframes.ai",packageName:"@conceptcraft/mindframes",configDir:".mindframes",apiKeyEnvVar:"MINDFRAMES_API_KEY",apiUrlEnvVar:"MINDFRAMES_API_URL",codexSelfConnectorAppId:"asdk_app_6a2b9629c1608191970dcb3ab374ac55"};import V from"chalk";import{Command as eg}from"commander";import st from"chalk";import{Command as td}from"commander";function $r(e={}){let t=(s,l)=>{let f=e[s];return f&&f.trim().length>0?f.trim():l},n=t("NEXT_PUBLIC_PRODUCT_SHORT_NAME","ConceptCraft"),r=t("NEXT_PUBLIC_CLI_COMMAND","ccr"),o=t("NEXT_PUBLIC_CLI_COMMAND_FULL","conceptcraft"),i=t("NEXT_PUBLIC_CLI_CONFIG_DIR",`.${o}`),a=n.toUpperCase().replace(/[^A-Z0-9]/g,"_");return{id:o,name:i.replace(/^\./,""),displayName:n,description:`CLI tool for ${n} presentation generation`,commands:[r,o],apiUrl:t("NEXT_PUBLIC_API_URL","http://localhost:3000"),docsUrl:t("NEXT_PUBLIC_DOCS_URL",`https://docs.${n.toLowerCase()}.ai`),packageName:t("NEXT_PUBLIC_CLI_PACKAGE_NAME","@conceptcraft/cli"),configDir:i,apiKeyEnvVar:`${a}_API_KEY`,apiUrlEnvVar:`${a}_API_URL`,codexSelfConnectorAppId:e.NEXT_PUBLIC_CODEX_SELF_CONNECTOR_APP_ID?.trim()||void 0}}var u=typeof h<"u"&&h?h:$r(process.env);import _ from"chalk";import wn from"cli-table3";import vs from"conf";var Tr=u.apiUrl,xs={apiKey:{type:"string"},apiUrl:{type:"string",default:Tr},defaultTeamId:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},tokenExpiresAt:{type:"number"},clientId:{type:"string"},clientSecret:{type:"string"}},P=new vs({projectName:u.name,schema:xs});function Er(){return{apiKey:fe(),apiUrl:G(),defaultTeamId:P.get("defaultTeamId"),accessToken:P.get("accessToken"),refreshToken:P.get("refreshToken"),tokenExpiresAt:P.get("tokenExpiresAt"),clientId:P.get("clientId"),clientSecret:P.get("clientSecret")}}function fe(){let e=process.env[u.apiKeyEnvVar]??process.env.CC_SLIDES_API_KEY;return e||P.get("apiKey")}function yn(e){P.set("apiKey",e)}function G(){let e=process.env[u.apiUrlEnvVar]??process.env.CC_SLIDES_API_URL;return e||(P.get("apiUrl")??Tr)}function bn(e){P.set("apiUrl",e)}function kt(){return P.get("defaultTeamId")}function De(e){P.set("defaultTeamId",e)}function Ct(){P.clear()}function ot(){return P.path}function Ne(){return!!fe()}function Ar(){return P.get("accessToken")}function Or(){return P.get("refreshToken")}function It(e,t,n){P.set("accessToken",e),P.set("refreshToken",t),P.set("tokenExpiresAt",Date.now()+(n-60)*1e3)}function Rt(){P.delete("accessToken"),P.delete("refreshToken"),P.delete("tokenExpiresAt")}function Pr(){let e=P.get("tokenExpiresAt");return e?Date.now()>=e:!0}function $e(){return!!P.get("accessToken")&&!!P.get("refreshToken")}function _r(){return P.get("clientId")}function Lr(){return P.get("clientSecret")}function Dr(e,t){P.set("clientId",e),P.set("clientSecret",t)}function C(e,t="human"){t!=="quiet"&&t!=="json"&&console.log(_.green("\u2713"),e)}function d(e,t="human"){if(t!=="quiet"){if(t==="json"){console.error(JSON.stringify({error:e}));return}console.error(_.red("\u2717"),e)}}function j(e,t="human"){t!=="quiet"&&t!=="json"&&console.warn(_.yellow("\u26A0"),e)}function Nr(e,t="human"){t==="quiet"||t==="json"||console.error(_.cyan("\u2192"),e)}function g(e,t="human"){t!=="quiet"&&t!=="json"&&console.log(_.blue("\u2139"),e)}function Ue(e,t="en"){return e?`${G()}/${t}/view/presentations/${e}`:"N/A"}function Ur(e,t={}){let{showLinks:n=!1,language:r="en"}=t,o=(s,l)=>s.length>l?`${s.slice(0,l-1)}\u2026`:s,i=s=>{try{return new Date(s).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0}).replace(" at ",", ")}catch{return"-"}};if(n){let s=new wn({head:[_.cyan("Slug"),_.cyan("Title"),_.cyan("Slides"),_.cyan("Created"),_.cyan("URL")]});for(let l of e)s.push([o(l.slug||l.id.slice(0,8),30),o(l.title||"Untitled",22),String(l.numberOfSlides||"-"),i(l.createdAt),Ue(l.slug,r)]);return s.toString()}let a=new wn({head:[_.cyan("Slug"),_.cyan("Title"),_.cyan("Slides"),_.cyan("Mode"),_.cyan("Created")],colWidths:[32,28,8,11,18]});for(let s of e)a.push([s.slug||s.id.slice(0,8),s.title||"Untitled",String(s.numberOfSlides||"-"),s.mode||"-",i(s.createdAt)]);return a.toString()}function qr(e){return e.map(t=>t.slug||t.id).join(`
|
|
4
|
+
`)}function jr(e){let t=[...e].sort((o,i)=>{if(o.isDefault&&!i.isDefault)return-1;if(!o.isDefault&&i.isDefault)return 1;let a=o.createdAt?new Date(o.createdAt).getTime():0;return(i.createdAt?new Date(i.createdAt).getTime():0)-a}),n=o=>{if(!o)return"-";try{return new URL(o).href}catch{return o.startsWith("http")?o:`https://${o}`}},r=new wn({head:[_.cyan("Name"),_.cyan("Source"),_.cyan("Color"),_.cyan("Logo"),_.cyan("Default"),_.cyan("ID")]});for(let o of t){let i=o.primaryColor?`${_.bgHex(o.primaryColor)(" ")} ${o.primaryColor}`:"-";r.push([o.name,n(o.sourceUrl),i,o.logoUrl?_.green("\u2713"):_.gray("\u2717"),o.isDefault?_.green("\u2605"):"",o.id])}return r.toString()}function vn(e){try{return new Date(e).toLocaleString()}catch{return e}}function se(e){console.log(),console.log(_.bold(e)),console.log(_.gray("\u2500".repeat(e.length)))}function S(e,t){console.log(` ${_.gray(`${e}:`)} ${t??"-"}`)}function ks(e){return JSON.stringify(e,null,2)}function m(e){console.log(ks(e))}import{createHash as Vs,randomUUID as it}from"crypto";import{readFileSync as Gs,statSync as Bs}from"fs";import{basename as Hr}from"path";import{spawnSync as Cs}from"child_process";import{existsSync as Is,mkdtempSync as Rs,rmSync as Ss,writeFileSync as $s}from"fs";import{tmpdir as Ts}from"os";import{join as Mr}from"path";import xn from"ffmpeg-static";var Es=/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/;function As(e){let t=Es.exec(e);if(!t)return;let n=Number(t[1])*3600+Number(t[2])*60+Number(t[3]);return Number.isFinite(n)&&n>0?n:void 0}function Fr(e,t="audio"){if(e.length===0)return;let n=xn&&Is(xn)?xn:"ffmpeg",r=/^[a-z0-9]+$/i.test(t)?t:"audio",o=Rs(Mr(Ts(),"mf-tts-duration-")),i=Mr(o,`speech.${r}`);try{$s(i,e);let a=Cs(n,["-hide_banner","-i",i],{encoding:"utf8"});return a.error?void 0:As(a.stderr??"")}finally{Ss(o,{force:!0,recursive:!0})}}import St from"chalk";var c={SUCCESS:0,GENERAL_ERROR:1,AUTH_ERROR:2,NOT_FOUND:3,RATE_LIMIT:4,NETWORK_ERROR:5,INVALID_INPUT:6};async function Os(){let e=Or(),t=_r(),n=G();if(!e||!t)return null;try{let r=await fetch(`${n}/.well-known/oauth-authorization-server`);if(!r.ok)return null;let o=await r.json(),i=new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t}),a=Lr();a&&i.set("client_secret",a);let s=await fetch(o.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});if(!s.ok)return Rt(),null;let l=await s.json();return It(l.access_token,l.refresh_token,l.expires_in),l.access_token}catch{return null}}async function Vr(){return $e()?Pr()?Os():Ar()||null:null}function de(){return $e()||Ne()}async function A(){if(!de()){let e=u.commands[0],t=u.apiKeyEnvVar;console.error(St.red("\u2717 Not authenticated.")),console.error(),console.error(St.bold("To authenticate, run:")),console.error(St.cyan(` ${e} login`)),console.error(),console.error(St.gray(`Or set ${t} environment variable.`)),process.exit(c.AUTH_ERROR)}}function Ps(e){return e.length<=14?"****":`${e.slice(0,10)}...${e.slice(-4)}`}function Gr(){let e=fe();if(e)return Ps(e)}function kn(e){return["cc_slides_","mcp_","cc_sk_","sk_"].some(n=>e.startsWith(n))}import{mkdirSync as _s,readFileSync as Ls,writeFileSync as Ds}from"fs";import{homedir as Ns}from"os";import{join as Br}from"path";import Us from"ajv/dist/2020.js";var Cn=new Map;function Wr(){return Br(Ns(),".conceptcraft","schemas")}function Kr(e){return Br(Wr(),`${e}.json`)}function qs(e){try{let t=JSON.parse(Ls(Kr(e),"utf8"));return typeof t?.catalogVersion=="number"&&t.schema?t:null}catch{return null}}function js(e,t){try{_s(Wr(),{recursive:!0}),Ds(Kr(e),JSON.stringify(t))}catch{}}async function Ms(e){let t=Cn.get(e);if(t!==void 0)return t;try{let n=await Jr(e),r={catalogVersion:n.catalogVersion,schema:n.schema};return js(e,r),Cn.set(e,r),r}catch{let n=qs(e);return Cn.set(e,n),n}}function Fs(e){let t=e.instancePath.replace(/^\//,"").replace(/\//g,"."),n=t.length>0?t:"(root)",r=e.keyword==="additionalProperties"?`: unknown field "${e.params.additionalProperty}"`:`: ${e.message??"invalid value"}`;return`${n}${r}`}async function $t(e,t){let n=await Ms(e);if(!n)return;let r;try{r=new Us({allErrors:!0,strict:!1}).compile(n.schema)}catch{return}if(r(t))return;let o=(r.errors??[]).slice(0,10).map(Fs);throw new Error(`Request does not match the ${e} contract \u2014 ${o.join("; ")}`)}function re(e,t){let n=e instanceof Error?e.message:"Unknown error";return!t||n.includes(t)?n:`${n} Request ID: ${t}. Resume with the matching status command; do not start a duplicate run.`}function oe(e,t={}){let n=e?.code?.trim()||t.defaultCode?.trim()||"",r=e?.message?.trim()||"The run failed without a reported reason.";return n?`[${n}] ${r}`:r}function zr(e){let t=e.projectId??"<project-id>";return/Narration is still missing for \d+ slides?\./.test(e.message)?["Narration is captured from speaker notes when the video project is prepared, so 'presentation video refresh' will not backfill it.",`Fill each empty scene with: ${e.binary} presentation video-narration ${t} --slide-id <slide-id> (scene ids: ${e.binary} presentation video inspect ${t})`].join(`
|
|
5
|
+
`):/Every scene is excluded from the video\./.test(e.message)?`Include a scene again with: ${e.binary} presentation video edit ${t} --edit '{"type":"patch_scene","scene":1,"excluded":false}'`:null}async function le(){let e=await Vr();if(e)return{Authorization:`Bearer ${e}`};let t=fe();return t?{"x-api-key":t}:{}}var O=class extends Error{constructor(n,r,o=1,i="operation_failed",a=!1){super(n);this.statusCode=r;this.exitCode=o;this.errorCode=i;this.retryable=a;this.name="ApiError"}statusCode;exitCode;errorCode;retryable},Yr="Idempotency-Key";function Ws(e){return e&&e!=="GET"?{[Yr]:it()}:{}}async function K(e,t={}){let n=G();if(!de()&&!t.allowUnauthenticated)throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2,"authentication_required");let r=await le(),o=`${n}${e}`,i={...r,...Ws(t.method),...t.headers};t.body&&!t.stream&&(i["Content-Type"]="application/json");let a={method:t.method??"GET",headers:i};t.body&&(a.body=JSON.stringify(t.body));let s;try{s=await fetch(o,a)}catch(f){throw new O(`Network error: ${f instanceof Error?f.message:"Unknown error"}`,0,5,"service_unavailable",!0)}if(!s.ok){let f=await s.text().catch(()=>""),p=Js(f,s.status),w=1;switch(s.status){case 401:w=2;break;case 403:w=2;break;case 404:w=3;break;case 429:w=4;break;case 500:w=1;break}let v=`[${p.code}] ${p.message}`;throw new O(v,s.status,w,p.code,p.retryable)}return t.stream?s:s.headers.get("content-type")?.includes("application/json")?s.json():s.text()}function Ks(e){switch(e){case 400:return"invalid_input";case 401:return"authentication_required";case 402:return"insufficient_credits";case 403:return"access_denied";case 404:return"not_found";case 429:return"rate_limited";case 503:return"service_unavailable";default:return"operation_failed"}}function Js(e,t){let n=Ks(t),r=e.trim()||`HTTP ${t}: The request could not be completed.`;try{let o=JSON.parse(e),i=typeof o.error=="object"&&o.error!==null?o.error:void 0;if(o.ok===!1&&typeof i?.code=="string"&&typeof i.message=="string")return{code:i.code,message:i.message,retryable:i.retryable===!0};if(typeof o.error=="string")return{code:/^[a-z][a-z0-9_]+$/.test(o.error)?o.error:n,message:typeof o.message=="string"?o.message:o.error,retryable:t===429||t>=500}}catch{}return{code:n,message:r,retryable:t===429||t>=500}}async function Jr(e){return K(`/api/cli/tools/${encodeURIComponent(e)}/schema`)}async function Qr(){return K("/api/cli/capabilities",{allowUnauthenticated:!0})}async function T(e,t,n){let r=n?`?teamId=${encodeURIComponent(n)}`:"";return K(`/api/cli/tool-runs/${encodeURIComponent(e)}/${encodeURIComponent(t)}${r}`)}async function y(e,t,n){return K(`/api/cli/tools/${encodeURIComponent(e)}`,{body:t,headers:n?{[Yr]:n}:void 0,method:"POST"})}async function Zr(e,t,n,r=120){let o=0;for(let i=0;i<r;i++){let a;try{a=await T(e,t,n),o=0}catch(s){if(s instanceof O&&s.retryable&&o<2){o+=1,await new Promise(l=>setTimeout(l,2e3));continue}throw s instanceof O?new O(`${s.message} Request ID: ${t}.`,s.statusCode,s.exitCode,s.errorCode,s.retryable):new O(`${s instanceof Error?s.message:"Unknown error"} Request ID: ${t}.`,0,5,"poll_failed",!0)}if(a.done){if(a.error)throw new O(`${oe(a.error,{defaultCode:"operation_failed"})} Request ID: ${t}.`,500,1,a.error.code??"operation_failed",a.error.retryable);return a}await new Promise(s=>setTimeout(s,(a.nextPollAfterSeconds??2)*1e3))}throw new O(`[operation_timed_out] The background operation timed out. Request ID: ${t}.`,408,1,"operation_timed_out",!0)}function Tt(e){return e.error||e.status==="failed"||e.status==="errored"||e.status==="cancelled"?"failed":e.done||e.status==="completed"?"completed":e.status==="in_progress"?"processing":"pending"}function zs(e){try{let n=new URL(e).pathname.split("/").pop()?.split(".").pop()?.toLowerCase();return n&&/^[a-z0-9]+$/.test(n)?n:void 0}catch{return}}function Xs(e){let t=e.toLowerCase().split(".").pop();return{pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",mp4:"video/mp4",mov:"video/quicktime",mpeg:"video/mpeg",mpg:"video/mpeg",webm:"video/webm",aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",oga:"audio/ogg",ogg:"audio/ogg",wav:"audio/wav",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",html:"text/html",css:"text/css",js:"application/javascript",ts:"text/x-typescript",py:"text/x-python"}[t||""]||"application/octet-stream"}async function ue(e,t={}){let n=G();if(!de())throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2);let r=await le(),o=Bs(e),i=Hr(e),a=Xs(e),s=Gs(e),l=Vs("sha256").update(s).digest("hex"),f=await fetch(`${n}/api/cli/files/upload`,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify({fileMetadata:{lastModified:o.mtimeMs,name:i,type:a,size:o.size},...t.idempotencyKey?{uploadIdentity:{contentSha256:l,idempotencyKey:t.idempotencyKey}}:{}})});if(!f.ok){let $=await f.text();throw new O($||"Failed to get upload URL",f.status,1)}let p=await f.json(),w=new FormData;for(let[$,x]of Object.entries(p.fields||{}))w.append($,x);let v=new Blob([s],{type:a});w.append("file",v,i);let b=await fetch(p.url,{method:"POST",body:w});if(!b.ok)throw new O("Failed to upload file to storage",b.status,1);return{id:it(),name:i,url:p.fileUrl,size:o.size,type:a,selected:!0}}async function eo(e,t){let n=[];for(let r=0;r<e.length;r++){let o=e[r],i=Hr(o);t?.(r,e.length,i);let a=await ue(o);n.push(a)}return t?.(e.length,e.length,""),n}async function to(e){let t={};for(let[r,o]of Object.entries(e))o!==void 0&&(t[r]=o);let n=t.designBrandReference??t.brandId??t.brandingId;return n!==void 0&&(t.designBrandReference=n,delete t.brandId,delete t.brandingId),y("createSlides",{...t,approvalReceipt:"cli:create"})}async function no(e,t=20){let n=new URLSearchParams;return n.set("limit",String(t)),e&&n.set("teamId",e),(await K(`/api/cli/presentations?${n}`)).presentations}async function we(e){return K(`/api/cli/presentation/${encodeURIComponent(e)}`)}async function ro(e,t){return K(`/api/cli/presentation/${encodeURIComponent(e)}/speaker-notes`,{body:t,method:"POST"})}async function oo(e,t){return K(`/api/cli/presentation-video/${encodeURIComponent(e)}/narration`,{body:t,method:"POST"})}async function Et(e){let t=G(),n=await fetch(`${t}/api/durable-runs/${encodeURIComponent(e)}/events`,{headers:await le()});if(!n.ok)throw new O(await n.text(),n.status);return n}async function io(e){await K(`/api/cli/presentation/${encodeURIComponent(e)}`,{method:"DELETE"})}async function ao(e,t={}){let n=G();if(!de())throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2);let r=await le(),o=await fetch(`${n}/api/presentations/export`,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify({presentationId:e,options:{includeImages:t.includeImages??!0,includeBranding:t.includeBranding??!0,downloadExternalImages:t.includeExternal??!0}})});if(!o.ok)throw new O(await o.text(),o.status,o.status===404?3:1);return o.arrayBuffer()}async function so(e,t,n={}){let r=G();if(!de())throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2);let o=await le(),i=new FormData,a=new Blob([e],{type:"application/zip"});i.append("file",a,t),i.append("options",JSON.stringify({dryRun:n.dryRun??!1,remapIds:!0}));let s=await fetch(`${r}/api/presentations/import`,{method:"POST",headers:o,body:i}),l=await s.json();if(!s.ok)throw new O(l.errors?.[0]?.message??"Import failed",s.status,1);return l}async function In(){return K("/api/cli/branding")}async function co(e,t=25){let n=new URLSearchParams;return n.set("limit",String(t)),e&&n.set("search",e),K(`/api/cli/templates?${n}`)}async function lo(e){return K(`/api/branding/${e}`)}async function uo(e,t,n){return y("extractBranding",{approvalReceipt:n,teamId:t,url:e})}async function he(){return K("/api/cli/whoami")}async function mo(){return K("/api/cli/features")}async function po(e,t,n={}){let r=G();if(!de())throw new O(`Not authenticated. Run '${u.commands[0]} login' or set ${u.apiKeyEnvVar} environment variable.`,401,2);let o=await le(),i=await fetch(`${r}/api/presentations/${e}/generate-blog`,{method:"POST",headers:{"Content-Type":"application/json",...o},body:JSON.stringify({documentCreatedAt:t,targetWordCount:n.targetWordCount??300,tone:n.tone??"professional",language:n.language??"en",targetAudience:n.targetAudience??"General Audience",blogFormat:n.blogFormat??"narrative",customInstructions:n.customInstructions??"",includeImages:n.includeImages??!0,includeTableOfContents:n.includeTableOfContents??!1})});if(!i.ok)throw new O(await i.text(),i.status,i.status===404?3:1);return i}async function Hs(e){let t=new URLSearchParams;e&&t.set("teamId",e);let n=t.toString();return K(`/api/cli/limits${n?`?${n}`:""}`)}async function go(e,t,n){let r=await Hs(n);if(!r.canGenerate[e]){let o=r.remaining[e]??0,i=r.limits[e]??0;throw i===0?new O(`The "${e}" mode is not available on your ${r.planName} plan. Available modes: ${r.availableModes.join(", ")||"none"}`,403,2):new O(`You have reached your ${e} generation limit for this billing cycle (${r.usage[e]??0}/${i} used). Try a different mode: ${r.availableModes.join(", ")||"none available"}`,403,4)}if(r.maxSlidesPerPresentation!==-1&&t>r.maxSlidesPerPresentation)throw new O(`Maximum ${r.maxSlidesPerPresentation} slides allowed on your ${r.planName} plan (requested: ${t}). Try a different mode: ${r.availableModes.join(", ")||"none available"}`,403,6);return r}function Ys(e){return e.replace(/[\u2014\u2013]/g,"-").replace(/[\u201C\u201D]/g,'"').replace(/[\u2018\u2019]/g,"'").replace(/\u2026/g,"...").replace(/\u00A0/g," ").replace(/[\u2010-\u2015]/g,"-").replace(/[\u2032\u2033]/g,"'")}async function fo(e){let t={...e,text:Ys(e.text)};await $t("generateSpeech",t);let n=await y("generateSpeech",{approvalReceipt:"cli:tts-generate",...t}),r=await Zr("generateSpeech",n.runId),o=r.entity?.url;if(!o)throw new O(`Speech completed without an audio URL. Request ID: ${n.runId}.`,500);let i;try{i=await fetch(o)}catch(w){throw new O(`${w instanceof Error?w.message:"Failed to download speech audio"} Request ID: ${n.runId}.`,0,5,"download_failed",!0)}if(!i.ok)throw new O(`Failed to download speech audio. Request ID: ${n.runId}.`,i.status,5,"download_failed",i.status===429||i.status>=500);let a=r.output??{},s=e.options??{},l=ce(a.format)??zs(o)??"mp3",f=Buffer.from(await i.arrayBuffer()),p=ho(a.durationSec,a.duration,a.duration_s)??Fr(f,l);if(p===void 0)throw new O(`Speech completed without a measurable duration. Request ID: ${n.runId}.`,500,1,"invalid_audio_metadata");return{audioData:f,audioUrl:o,duration:p,cost:Te(a.costUsd)??Te(a.cost)??0,provider:ce(a.provider)??s.provider??"gemini",format:l,requestId:n.runId,voiceId:ce(a.voice_id)??ce(a.voiceId),voice:ce(a.voice),model:ce(a.model),speed:Te(a.speed)??s.speed,language:ce(a.lang)??ce(a.language)??s.language,langApplied:Xr(a.langApplied)??Xr(a.lang_applied),timestamps:Qs(a.timestamps),wordTimings:Zs(a.timestamps??a.timings)}}function ho(...e){for(let t of e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()?Number(t):Number.NaN;if(Number.isFinite(n)&&n>0)return n}}function Qs(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n=t.characters,r=t.characterStartTimesSeconds??t.character_start_times_seconds,o=t.characterEndTimesSeconds??t.character_end_times_seconds;if(!(!Array.isArray(n)||!Array.isArray(r)||!Array.isArray(o))&&!(n.length===0||n.length!==r.length||n.length!==o.length||!n.every(i=>typeof i=="string")||!r.every(i=>typeof i=="number"&&Number.isFinite(i))||!o.every(i=>typeof i=="number"&&Number.isFinite(i))))return{characters:n,characterStartTimesSeconds:r,characterEndTimesSeconds:o}}function Zs(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let r=n,o=ce(r.text)??ce(r.word),i=Te(r.start),a=Te(r.end);return o&&i!==void 0&&a!==void 0&&a>=i?[{text:o,start:i,end:a}]:[]});return t.length>0?t:void 0}function ce(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Te(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Xr(e){return typeof e=="boolean"?e:void 0}async function yo(e){let t=e?`/api/cli/tts?provider=${e}`:"/api/cli/tts";return K(t)}async function bo(e){let t={...e},n=typeof t.idempotency_key=="string"?t.idempotency_key:void 0;return delete t.idempotency_key,await $t("generateMusic",t),{requestId:(await y("generateMusic",{...t,approvalReceipt:"cli:music-generate"},n)).runId,status:"pending"}}async function Rn(e){let t=await T("generateMusic",e);return{requestId:e,status:Tt(t),audioUrl:t.entity?.url,duration:ho(t.output?.durationSec,t.output?.duration,t.output?.duration_s),cost:Te(t.output?.costUsd)??Te(t.output?.cost),error:t.error?.message}}async function wo(e){return{requestId:(await y("mixAudio",{...e,approvalReceipt:"cli:mix-create"})).runId,status:"pending"}}async function Sn(e){let t=await T("mixAudio",e);return{requestId:e,status:Tt(t),outputUrl:t.entity?.url,error:t.error?.message}}async function vo(e){return K("/api/cli/images/search",{method:"POST",body:e})}async function xo(e){return K("/api/cli/videos/search",{method:"POST",body:e})}async function Z(e,t=60,n=2e3){let r=0;for(let o=0;o<t;o++){let i;try{i=await e(),r=0}catch(a){if(a instanceof O&&a.retryable&&r<2){r+=1,await new Promise(s=>setTimeout(s,n));continue}throw a}if(i.status==="completed"||i.status==="failed")return i;await new Promise(a=>setTimeout(a,n))}throw new O("Operation timed out",408,1)}async function ko(e,t,n){return y("getYoutubeTranscript",{...n?{language:n}:{},teamId:t,url:e})}async function Co(e,t){let n=await y("scrape",{teamId:t,url:e});return{data:{content:n.content,cost:n.totalCost??0,metadata:{description:"",format:"markdown",tokenUsage:Math.ceil(n.content.length/4)},title:n.title??"",url:n.url},success:!0}}async function Io(e){let t={...e},n=typeof t.idempotency_key=="string"?t.idempotency_key:void 0;delete t.idempotency_key,await $t("generateSfx",t);let r=await y("generateSfx",{...t,approvalReceipt:"cli:sfx-generate"},n);return{id:r.runId,requestId:r.runId,status:"pending"}}async function $n(e){let t=await T("generateSfx",e);return{id:t.entity?.id??e,requestId:e,status:Tt(t),audioUrl:t.entity?.url,error:t.error?.message}}async function Ro(e){return y("listPresenterOptions",{...e?{voiceLanguage:e}:{}})}async function So(e){return{requestId:(await y("generateAvatarVideo",{...e,approvalReceipt:"cli:avatar-generate"})).runId,status:"pending"}}async function Tn(e){let t=await T("generateAvatarVideo",e);return{durationSec:typeof t.output?.durationSec=="number"?t.output.durationSec:null,error:t.error?.message,requestId:e,status:Tt(t),videoUrl:t.entity?.url}}async function $o(e){return y("lipsyncVideo",{...e,approvalReceipt:"cli:video-lipsync"})}async function To(){return(await y("listTranslationLanguages",{})).languages}async function Eo(e){return y("translateVideo",{...e,approvalReceipt:"cli:video-translate"})}async function Ao(e,t,n){return y("createVideo",{...e,approvalReceipt:t},n)}async function Oo(e){let{idempotencyKey:t,...n}=e;return y("analyzeVideoReference",n,t)}async function Po(e,t){return Zr("analyzeVideoReference",e,t)}async function _o(e){return y("listCastPresets",e)}async function Lo(e){return y("createCastPreset",e,it())}async function Do(e){return y("updateCastPreset",e,it())}async function No(e){return y("deleteCastPreset",{presetId:e},it())}var Uo=[{billing:"free",category:"branding",description:"Attach a social handle to an accessible brand profile.",id:"addBrandSocialHandle",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding social add",operation:"mutation",scopes:["brands:write"],state:"available"},{billing:"free",category:"branding",description:"Add a competitor to an accessible brand profile.",id:"addCompetitor",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding competitor add",operation:"mutation",scopes:["brands:write"],state:"available"},{billing:"delegated",category:"media",description:"Transcribe an uploaded recording and publish the transcript for generation.",id:"analyzeMediaAsset",lifecycle:{mode:"background",status:{cliCommand:"media analyze status",pollAfterSeconds:10}},milestone:"M8",name:"media analyze",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"media",description:"Analyze an uploaded video before using it as a source, motion, blocking, or pacing reference in a video storyboard. The completed status output includes the analysisId required by the storyboard's source-video binding.",id:"analyzeVideoReference",lifecycle:{mode:"background",status:{cliCommand:"video reference status",pollAfterSeconds:10}},milestone:"M8",name:"video reference analyze",operation:"generation",scopes:["media:write"],state:"available"},{billing:"delegated",category:"artifacts",description:"Generate and persist an ad variation set.",id:"createAdSet",lifecycle:{mode:"background",status:{cliCommand:"ad-set status",pollAfterSeconds:10}},milestone:"M6",name:"ad-set create",operation:"generation",scopes:["ad-sets:write"],state:"available"},{billing:"free",category:"agents",description:"Create a scheduled agent from a validated configuration.",id:"createAgent",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent create",operation:"mutation",scopes:["agents:write"],state:"available"},{billing:"free",category:"media",description:"Save one way a cast member appears: a personal presenter (pp_* id), a backdrop, and optionally a voice, under a name unique to that person.",id:"createCastPreset",lifecycle:{mode:"bounded"},milestone:"M8",name:"cast preset create",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Save a markdown, CSV or plain-text document into the Library.",id:"createDocument",lifecycle:{mode:"bounded"},milestone:"M8",name:"document create",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"fixed",category:"media",description:"Generate and persist an image.",id:"createImage",lifecycle:{mode:"background",status:{cliCommand:"image status",pollAfterSeconds:10}},milestone:"M5",name:"image generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Create a Library folder, optionally inside another.",id:"createLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders create",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"dynamic",category:"artifacts",description:"Generate and persist a microsite.",id:"createMicrosite",lifecycle:{mode:"background",status:{cliCommand:"microsite status",pollAfterSeconds:10}},milestone:"M6",name:"microsite create",operation:"generation",scopes:["microsites:write"],state:"available"},{billing:"free",category:"artifacts",description:"Create a standalone poll.",id:"createPoll",lifecycle:{mode:"bounded"},milestone:"M3",name:"poll create",operation:"mutation",scopes:["polls:write"],state:"available"},{billing:"delegated",category:"presentations",description:"Create an MP4 video from a finished presentation, or render an existing presentation-video project.",id:"createPresentationVideo",lifecycle:{mode:"background",status:{cliCommand:"presentation video status",pollAfterSeconds:10}},milestone:"M4",name:"presentation video",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"fixed",category:"presentations",description:"Generate a presentation and persist the resulting deck.",id:"createSlides",lifecycle:{mode:"background",status:{cliCommand:"presentation status",pollAfterSeconds:20}},milestone:"M4",name:"create",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"delegated",category:"media",description:"Generate one video from the opaque text and explicit metadata stored in a pinned storyboard revision.",id:"createVideo",lifecycle:{mode:"background",status:{cliCommand:"video status",pollAfterSeconds:20}},milestone:"M8",name:"video create",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"media",description:"Create a versioned Markdown video storyboard.",id:"createVideoStoryboard",lifecycle:{mode:"bounded"},milestone:"M8",name:"video storyboard create",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"fixed",category:"artifacts",description:"Generate a persisted standalone visual abstract.",id:"createVisualAbstract",lifecycle:{mode:"background",status:{cliCommand:"visual-abstract status",pollAfterSeconds:10}},milestone:"M5",name:"visual-abstract create",operation:"generation",scopes:["visual-abstracts:write"],state:"available"},{billing:"free",category:"media",description:"Retire a saved cast preset. Existing videos keep working; the preset stops being offered.",id:"deleteCastPreset",lifecycle:{mode:"bounded"},milestone:"M8",name:"cast preset delete",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Remove a document from the Library.",id:"deleteDocument",lifecycle:{mode:"bounded"},milestone:"M8",name:"document delete",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"knowledge",description:"Delete a Library folder and its subfolders. Items inside are unfiled, never deleted.",id:"deleteLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders delete",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"artifacts",description:"Edit a standalone poll.",id:"editPoll",lifecycle:{mode:"bounded"},milestone:"M3",name:"poll edit",operation:"mutation",scopes:["polls:write"],state:"available"},{billing:"free",category:"presentations",description:"Apply one atomic edit to a presentation-video draft.",id:"editPresentationVideoDraft",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video edit",operation:"mutation",scopes:["presentations:write","media:read"],state:"available"},{billing:"dynamic",category:"presentations",description:"Generate the narration a presentation-video project is still missing.",id:"ensurePresentationVideoNarration",lifecycle:{mode:"background",status:{cliCommand:"presentation video narrate status",pollAfterSeconds:5}},milestone:"M4",name:"presentation video narrate",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"quota",category:"branding",description:"Extract and persist a reusable brand profile from a URL.",id:"extractBranding",lifecycle:{mode:"background",status:{cliCommand:"branding status",pollAfterSeconds:10}},milestone:"M2",name:"branding extract",operation:"generation",scopes:["brands:write"],state:"available"},{billing:"dynamic",category:"research",description:"Extract normalized text from uploaded or remote content.",id:"extractContent",lifecycle:{mode:"bounded"},milestone:"M1",name:"content extract",operation:"query",scopes:["research:read"],state:"available"},{billing:"free",category:"knowledge",description:"File an artifact into a Library folder, or unfile it.",id:"fileArtifactIntoFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library file",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"agents",description:"Erase every stored version of a scheduled agent's memory. Irreversible.",id:"forgetAgentMemory",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent memory forget",operation:"mutation",scopes:["agents:write"],state:"available"},{billing:"delegated",category:"media",description:"Generate one reusable avatar/presenter clip for composition into a video. Accepts a stock avatar id or a personal presenter's pp_* id (from listPresenterOptions' `personal` group) as avatarId.",id:"generateAvatarVideo",lifecycle:{mode:"background",status:{cliCommand:"avatar status",pollAfterSeconds:10}},milestone:"M8",name:"avatar generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"dynamic",category:"media",description:"Generate music from final video facts or a trusted direct prompt.",id:"generateMusic",lifecycle:{mode:"background",status:{cliCommand:"music status",pollAfterSeconds:10}},milestone:"M7",name:"music generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"delegated",category:"media",description:"Generate an additional look for an existing personal presenter while preserving the same Cast identity.",id:"generatePresenterLook",lifecycle:{mode:"background",status:{cliCommand:"avatar look status",pollAfterSeconds:10}},milestone:"M8",name:"avatar look generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"dynamic",category:"media",description:"Generate SFX from final video facts or a trusted direct prompt.",id:"generateSfx",lifecycle:{mode:"background",status:{cliCommand:"sfx status",pollAfterSeconds:10}},milestone:"M7",name:"sfx generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"dynamic",category:"presentations",description:"Generate persisted speaker notes for a presentation version.",id:"generateSpeakerNotes",lifecycle:{mode:"background",status:{cliCommand:"presentation speaker-notes-status",pollAfterSeconds:5}},milestone:"M4",name:"presentation speaker-notes",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"dynamic",category:"media",description:"Generate speech audio from text.",id:"generateSpeech",lifecycle:{mode:"background",status:{cliCommand:"tts status",pollAfterSeconds:10}},milestone:"M7",name:"tts generate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"agents",description:"Read what a scheduled agent has recorded about its own work: learned facts, standing instructions, things it never does, entities it tracks, and freeform notes.",id:"getAgentMemory",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent memory show",operation:"query",scopes:["agents:read"],state:"available"},{billing:"free",category:"branding",description:"List competitors saved for an accessible brand profile.",id:"getBrandCompetitors",lifecycle:{mode:"bounded"},milestone:"M1",name:"branding competitor list",operation:"query",scopes:["brands:read"],state:"available"},{billing:"free",category:"branding",description:"Read a brand's design tokens, the keys it is missing, or its design.md document.",id:"getBrandProfile",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding profile",operation:"query",scopes:["brands:read"],state:"available"},{billing:"free",category:"knowledge",description:"Read a bounded workspace Knowledge Hub bundle.",id:"getKnowledgeBundle",lifecycle:{mode:"bounded"},milestone:"M1",name:"knowledge bundle",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"dynamic",category:"research",description:"Search recent news sources.",id:"getNews",lifecycle:{mode:"bounded"},milestone:"M1",name:"search news",operation:"query",scopes:["research:read"],state:"available"},{billing:"free",category:"presentations",description:"Read a presentation and its slides.",id:"getPresentation",lifecycle:{mode:"bounded"},milestone:"M1",name:"get",operation:"query",scopes:["presentations:read"],state:"available"},{billing:"free",category:"presentations",description:"Read an owned presentation-video project and its ordered scene timeline.",id:"getPresentationVideoProject",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video inspect",operation:"query",scopes:["presentations:read"],state:"available"},{billing:"dynamic",category:"research",description:"Fetch a YouTube video's timestamped transcript with its title, channel, and duration.",id:"getYoutubeTranscript",lifecycle:{mode:"bounded"},milestone:"M1",name:"transcript",operation:"query",scopes:["research:read"],state:"available"},{billing:"free",category:"media",description:"Import a recording from a connected account into the media library.",id:"importConnectorRecording",lifecycle:{mode:"background",status:{cliCommand:"media import status",pollAfterSeconds:5}},milestone:"M8",name:"media import",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"presentations",description:"Import an attached PowerPoint as an auditable, review-gated Mindframes presentation.",id:"importPowerPoint",lifecycle:{mode:"background",status:{cliCommand:"presentation import status",pollAfterSeconds:5}},milestone:"M4",name:"presentation import",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"delegated",category:"media",description:"Re-voice a ready video with new audio via provider lip-sync (one sibling re-voiced video artifact).",id:"lipsyncVideo",lifecycle:{mode:"background",status:{cliCommand:"video lipsync status",pollAfterSeconds:20}},milestone:"M8",name:"video lipsync",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"media",description:"List saved ways a cast member appears \u2014 a trained presenter, a backdrop, and optionally a voice, under one name. Filtered to what the caller may actually use.",id:"listCastPresets",lifecycle:{mode:"bounded"},milestone:"M8",name:"cast preset list",operation:"query",scopes:["media:read"],state:"available"},{billing:"free",category:"knowledge",description:"List the workspace's documents, newest first.",id:"listDocuments",lifecycle:{mode:"bounded"},milestone:"M8",name:"document list",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"free",category:"knowledge",description:"List a document's append-only version history.",id:"listDocumentVersions",lifecycle:{mode:"bounded"},milestone:"M8",name:"document versions",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"free",category:"knowledge",description:"List the workspace Library folder tree.",id:"listLibraryFolders",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders list",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"free",category:"presentations",description:"List saved presentation-video draft versions.",id:"listPresentationVideoVersions",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video versions",operation:"query",scopes:["presentations:read"],state:"available"},{billing:"free",category:"media",description:"List provider-neutral presenter avatars, voices, and voice languages, plus the workspace's trained personal presenters (`personal` roster group, pp_* ids).",id:"listPresenterOptions",lifecycle:{mode:"bounded"},milestone:"M8",name:"avatar options",operation:"query",scopes:["media:read"],state:"available"},{billing:"free",category:"media",description:"List ready generated clips and uploaded MediaAssets while excluding final presentation-to-MP4 renders.",id:"listReusableVideoClips",lifecycle:{mode:"bounded"},milestone:"M8",name:"video library list",operation:"query",scopes:["media:read","presentations:read"],state:"available"},{billing:"free",category:"media",description:"List provider-neutral target languages for video translation.",id:"listTranslationLanguages",lifecycle:{mode:"bounded"},milestone:"M8",name:"video translate-languages",operation:"query",scopes:["media:read"],state:"available"},{billing:"dynamic",category:"media",description:"Mix voice, music, and sound-effect tracks.",id:"mixAudio",lifecycle:{mode:"background",status:{cliCommand:"mix status",pollAfterSeconds:10}},milestone:"M7",name:"mix create",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Move a Library folder under a new parent, or to the top level.",id:"moveLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders move",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"presentations",description:"Create or reuse a presentation-video project for a finished presentation.",id:"preparePresentationVideo",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video prepare",operation:"mutation",scopes:["presentations:write"],state:"available"},{billing:"free",category:"knowledge",description:"Read one document's full body and metadata.",id:"readDocument",lifecycle:{mode:"bounded"},milestone:"M8",name:"document read",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"free",category:"media",description:"Read a video storyboard and its immutable revision history.",id:"readVideoStoryboard",lifecycle:{mode:"bounded"},milestone:"M8",name:"video storyboard show",operation:"query",scopes:["media:read"],state:"available"},{billing:"free",category:"knowledge",description:"Set or clear the colour of a Library folder.",id:"recolorLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders recolor",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"agents",description:"Create a reviewable scheduled-agent recommendation.",id:"recommendAgent",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent recommend",operation:"generation",scopes:["agents:write"],state:"available"},{billing:"free",category:"presentations",description:"Refresh deck-backed video scenes from the latest presentation version.",id:"refreshPresentationVideoSlides",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video refresh",operation:"mutation",scopes:["presentations:write"],state:"available"},{billing:"dynamic",category:"presentations",description:"Regenerate one narration override in a presentation video draft.",id:"regeneratePresentationVideoNarration",lifecycle:{mode:"background",status:{cliCommand:"presentation video-narration-status",pollAfterSeconds:5}},milestone:"M4",name:"presentation video-narration",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"free",category:"knowledge",description:"Rename a Library folder.",id:"renameLibraryFolder",lifecycle:{mode:"bounded"},milestone:"M1",name:"library folders rename",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"knowledge",description:"Restore an earlier version by appending it as the current one.",id:"restoreDocumentVersion",lifecycle:{mode:"bounded"},milestone:"M8",name:"document restore",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"presentations",description:"Restore a saved presentation-video draft version as a new version.",id:"restorePresentationVideoVersion",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video restore",operation:"mutation",scopes:["presentations:write"],state:"available"},{billing:"delegated",category:"media",description:"Create a new presenter Look by editing an existing Look without changing its source.",id:"revisePresenterLook",lifecycle:{mode:"background",status:{cliCommand:"avatar look revision-status",pollAfterSeconds:10}},milestone:"M8",name:"avatar look revise",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"media",description:"Create a new immutable revision of a Markdown video storyboard.",id:"reviseVideoStoryboard",lifecycle:{mode:"bounded"},milestone:"M8",name:"video storyboard revise",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"dynamic",category:"research",description:"Read and normalize content from a public URL.",id:"scrape",lifecycle:{mode:"bounded"},milestone:"M1",name:"scrape",operation:"query",scopes:["research:read"],state:"available"},{billing:"dynamic",category:"research",description:"Search licensed image providers.",id:"searchImages",lifecycle:{mode:"bounded"},milestone:"M1",name:"search images",operation:"query",scopes:["research:read"],state:"available"},{billing:"dynamic",category:"research",description:"Search the public web for current sources.",id:"searchInternet",lifecycle:{mode:"bounded"},milestone:"M1",name:"search web",operation:"query",scopes:["research:read"],state:"available"},{billing:"free",category:"knowledge",description:"Search workspace Knowledge Hub entries.",id:"searchKnowledge",lifecycle:{mode:"bounded"},milestone:"M1",name:"knowledge search",operation:"query",scopes:["knowledge:read"],state:"available"},{billing:"dynamic",category:"media",description:"Find videos: licensed stock clips to download, or web videos to embed.",id:"searchStockVideo",lifecycle:{mode:"bounded"},milestone:"M1",name:"search video",operation:"query",scopes:["media:read"],state:"available"},{billing:"free",category:"branding",description:"Point a brand at an already-uploaded logo, dark-background logo variant, or favicon.",id:"setBrandLogo",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding logo set",operation:"mutation",scopes:["brands:write"],state:"available"},{billing:"free",category:"presentations",description:"Set one presentation-video scene to a specific avatar/look or saved preset, including the preset voice by default, or restore inheritance from the project default.",id:"setPresentationVideoScenePresenter",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video presenter",operation:"mutation",scopes:["presentations:write"],state:"available"},{billing:"free",category:"presentations",description:"Transform an uploaded PowerPoint source into an auditable presentation review.",id:"transformPresentationImport",lifecycle:{mode:"background",status:{cliCommand:"presentation import status",pollAfterSeconds:5}},milestone:"M4",name:"presentation import transform",operation:"generation",scopes:["presentations:write"],state:"available"},{billing:"delegated",category:"media",description:"Translate a ready video into sibling language versions (one video per target language).",id:"translateVideo",lifecycle:{mode:"background",status:{cliCommand:"video translate status",pollAfterSeconds:20}},milestone:"M8",name:"video translate",operation:"generation",scopes:["media:write"],state:"available"},{billing:"free",category:"agents",description:"Add to or remove from what a scheduled agent remembers. Owner or workspace admin only.",id:"updateAgentMemory",lifecycle:{mode:"bounded"},milestone:"M3",name:"agent memory set",operation:"mutation",scopes:["agents:write"],state:"available"},{billing:"free",category:"branding",description:"Write a brand's design tokens from a key patch or a whole design.md document.",id:"updateBrandTokens",lifecycle:{mode:"bounded"},milestone:"M2",name:"branding set",operation:"mutation",scopes:["brands:write"],state:"available"},{billing:"free",category:"media",description:"Change a saved cast preset's name, presenter, backdrop, or voice. Sends the complete preset, not a patch.",id:"updateCastPreset",lifecycle:{mode:"bounded"},milestone:"M8",name:"cast preset update",operation:"mutation",scopes:["media:write"],state:"available"},{billing:"free",category:"knowledge",description:"Edit a document's body, title or summary under an optimistic lock.",id:"updateDocument",lifecycle:{mode:"bounded"},milestone:"M8",name:"document update",operation:"mutation",scopes:["knowledge:write"],state:"available"},{billing:"free",category:"presentations",description:"Update avatar, voice, music, captions, format, and renderer settings for a presentation-video project.",id:"updatePresentationVideoSettings",lifecycle:{mode:"bounded"},milestone:"M4",name:"presentation video settings",operation:"mutation",scopes:["presentations:write"],state:"available"}];function At(e){return{capabilities:Uo,catalogVersion:1,reason:e,source:"snapshot"}}async function at(e=Qr){try{let{capabilities:t,catalogVersion:n}=await e();return!Array.isArray(t)||t.length===0?At("the live catalog returned no capabilities"):{capabilities:t,catalogVersion:n,source:"live"}}catch(t){let n=t instanceof Error?t.message:String(t);return At(n)}}var qo=["presentations","media","branding","knowledge","research","artifacts","agents"],nd=80,rd=30;function od(e){return e.billing!==void 0&&e.billing!=="free"&&e.billing!=="quota"}function id(e){return e.lifecycle?.mode==="background"}function ad(e,t){if(t<=0)return[e];let n=[],r="";for(let o of e.split(/\s+/).filter(Boolean))r===""?r=o:r.length+1+o.length<=t?r=`${r} ${o}`:(n.push(r),r=o);return r!==""&&n.push(r),n.length>0?n:[""]}function jo(e){let t=qo.indexOf(e);return t===-1?qo.length:t}function sd(e,t){let n=t.search?.trim().toLowerCase(),r=t.category?.trim().toLowerCase();return e.filter(o=>r&&(o.category??"").toLowerCase()!==r?!1:n?`${o.name} ${o.description??""}`.toLowerCase().includes(n):!0)}function dd(e){let t=new Map;for(let i of e){let a=i.category??"other",s=t.get(a);s?s.push(i):t.set(a,[i])}let n=[...t.entries()].sort(([i],[a])=>{let s=jo(i)-jo(a);return s!==0?s:i.localeCompare(a)}),r=Math.min(rd,Math.max(...e.map(i=>i.name.length))),o=[];for(let[i,a]of n){a.sort((s,l)=>s.name.localeCompare(l.name)),o.length>0&&o.push(""),o.push(st.bold(`${i} (${a.length})`));for(let s of a){let l=`${od(s)?"$":" "}${id(s)?"*":" "}`,f=s.name.padEnd(r),p=2+r+1+l.length+1,w=Math.max(24,nd-p),v=ad(s.description??"",w);o.push(` ${st.cyan(f)} ${st.yellow(l)} ${v[0]??""}`.trimEnd());for(let b of v.slice(1))o.push(`${" ".repeat(p)}${b}`)}}return o}function cd(e){return e.map(t=>`${t.name} ${t.state} ${t.milestone}`)}function ld(e,t={filtered:!1}){if(e.length===0)return[t.filtered?"No capabilities match that filter.":"No capabilities available."];if(!e.some(i=>i.description||i.category))return cd(e);let r=u.commands[0],o=dd(e);return o.push(""),o.push(st.dim(`${e.length} capabilities \xB7 $ = paid \xB7 * = background (returns a run id)`)),o.push(st.dim(`Filter with: ${r} capabilities --search <query>`)),o}var Mo=new td("capabilities").description("Index of everything this CLI can do \u2014 every command, grouped and described").option("-f, --format <format>","Output format: human, json, quiet","human").option("-s, --search <query>","Only show capabilities matching a query").option("--category <name>","Only show one category").action(async e=>{try{let t=await at(),n=sd(t.capabilities,e),r=!!(e.search||e.category);if(e.format==="json"){m({capabilities:n,catalogVersion:t.catalogVersion,source:t.source,...t.reason?{sourceReason:t.reason}:{}});return}if(e.format==="quiet"){for(let o of n)console.log(o.name);return}t.source==="snapshot"&&j(`Showing the capability list baked into this CLI build (${t.reason}); the deployed catalog may have moved on.`);for(let o of ld(n,{filtered:r}))console.log(o)}catch(t){d(t instanceof Error?t.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}});import{mkdirSync as gd,writeFileSync as fd}from"fs";import{dirname as Bo,join as hd}from"path";import{Command as ve}from"commander";import dt from"chalk";import{input as yd,password as bd,confirm as Wo,select as wd}from"@inquirer/prompts";import Pt from"ora";import ud from"conf";var Ot=new ud({projectName:"conceptcraft",configName:"feature-cache"}),md=3600*1e3,pd=1440*60*1e3;function Fo(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t=t&t}return t.toString(16)}function Vo(){if(!Ne())return null;let e=Ot.get("featureFlags");if(!e)return null;let t=Fo(fe());if(e.apiKeyHash&&e.apiKeyHash!==t)return Ae(),null;let n=Date.now()-e.fetchedAt;return n>pd?null:(n>md&&En(),e.flags)}function En(){Ee().catch(()=>{})}async function Ee(){let e=await mo(),t=fe();return Ot.set("featureFlags",{flags:e,fetchedAt:Date.now(),apiKeyHash:t?Fo(t):void 0}),e}function Ae(){Ot.delete("featureFlags")}function Go(){return Ot.path}var Ko=new ve("config").description("Manage CLI configuration: account settings, and the cached feature flags that decide which commands appear").addCommand(new ve("init").description("Initialize configuration interactively").action(async()=>{console.log(),console.log(dt.bold(`${u.displayName} CLI Configuration`)),console.log(dt.gray("\u2500".repeat(35))),console.log();try{let e=await bd({message:"Enter your API key:",mask:"*",validate:r=>!r||r.trim().length===0?"API key is required":kn(r.trim())?!0:"Invalid API key format. Keys should start with 'cc_slides_' or 'mcp_'"});if(yn(e.trim()),await Wo({message:`Use a custom API URL? (default: ${u.apiUrl.replace("https://","")})`,default:!1})){let r=await yd({message:"Enter API URL:",default:G(),validate:o=>{try{return new URL(o),!0}catch{return"Invalid URL format"}}});bn(r)}console.log();let n=Pt("Verifying API key...").start();try{let r=await he();if(n.succeed("API key verified!"),console.log(),g(`Logged in as: ${r.user.email}`),r.teams.length===0)j("No teams found for this user.");else if(r.teams.length===1){let o=r.teams[0];De(o.id),g(`Team: ${o.name} (${o.planName})`)}else{console.log(),g(`You have access to ${r.teams.length} teams.`);let o=await wd({message:"Select your default team:",choices:r.teams.map(a=>({name:`${a.name} (${a.planName}) - ${a.role}${a.isCurrent?" [current]":""}`,value:a.id})),default:r.currentTeam?.id});De(o);let i=r.teams.find(a=>a.id===o);C(`Selected team: ${i?.name}`)}try{await Ee()}catch{}}catch(r){n.fail("Failed to verify API key"),j(`Could not verify API key: ${r instanceof Error?r.message:String(r)}`),j(`You may need to set the team ID manually: ${u.commands[0]} config set team-id <id>`)}console.log(),C("Configuration saved!"),g(`Config file: ${ot()}`),console.log()}catch(e){if(e.name==="ExitPromptError"){console.log(),g("Configuration cancelled.");return}throw e}})).addCommand(new ve("show").description("Show current configuration").option("--verify","Verify API key and show team details").action(async e=>{let t=Er();if(se("Current Configuration"),console.log(),S("API Key",Gr()??dt.red("Not set")),S("API URL",t.apiUrl),S("Default Team ID",t.defaultTeamId??dt.gray("Not set")),console.log(),S("Config file",ot()),e.verify&&t.apiKey){console.log();let n=Pt("Verifying...").start();try{let r=await he();n.succeed("Verified"),console.log(),S("User",r.user.email),r.currentTeam&&S("Current Team",`${r.currentTeam.name} (${r.currentTeam.planName})`),r.teams.length>1&&S("Total Teams",String(r.teams.length))}catch(r){n.fail("Verification failed"),j(r instanceof Error?r.message:String(r))}}console.log()})).addCommand(new ve("set").description("Set a configuration value").argument("<key>","Configuration key (api-key, api-url, team-id)").argument("<value>","Value to set").action(async(e,t)=>{switch(e){case"api-key":kn(t)||(d("Invalid API key format. Keys should start with 'cc_slides_' or 'mcp_'"),process.exit(6)),yn(t),Ae(),C("API key updated"),Ee().catch(()=>{});break;case"api-url":try{new URL(t),bn(t),C(`API URL set to: ${t}`)}catch{d("Invalid URL format"),process.exit(6)}break;case"team-id":De(t),C(`Default team ID set to: ${t}`);break;default:d(`Unknown config key: ${e}`),console.log(dt.gray("Valid keys: api-key, api-url, team-id")),process.exit(6)}})).addCommand(new ve("clear").description("Clear all configuration").action(async()=>{try{await Wo({message:"Are you sure you want to clear all configuration?",default:!1})?(Ct(),Ae(),C("Configuration cleared")):g("Cancelled")}catch{g("Cancelled")}})).addCommand(new ve("refresh").description("Refresh cached feature flags").action(async()=>{let e=Pt("Refreshing feature flags...").start();try{await Ee(),e.succeed("Feature flags refreshed"),g(`Run '${u.commands[0]} --help' to see updated commands`)}catch(t){e.fail("Failed to refresh"),d(t instanceof Error?t.message:String(t)),process.exit(1)}})).addCommand(new ve("path").description("Show configuration file path").option("--cache","Show feature cache file path").action(e=>{e.cache?console.log(Go()):console.log(ot())})).addCommand(new ve("pull").description("Pull your account settings (memory, brand, prefs) into a local config.toml").action(async()=>{let e=Pt("Pulling settings...").start();try{let t=await le(),n=await fetch(`${G()}/api/cli/settings`,{headers:t});if(!n.ok)throw new Error(`Request failed (HTTP ${n.status})`);let r=await n.text(),o=hd(Bo(ot()),"settings.toml");gd(Bo(o),{recursive:!0}),fd(o,r,"utf8"),e.succeed("Settings pulled"),g(`Written to ${o}`)}catch(t){e.fail("Failed to pull settings"),d(t instanceof Error?t.message:String(t)),process.exit(1)}}));import{Command as vd}from"commander";import{confirm as xd}from"@inquirer/prompts";var Jo=new vd("delete").description("Delete a presentation").argument("<slug>","Presentation slug (e.g., my-presentation-v1-abc123)").option("-f, --force","Skip confirmation prompt").option("-q, --quiet","Suppress output").action(async(e,t)=>{if(await A(),!t.force)try{if(!await xd({message:`Are you sure you want to delete presentation "${e}"?`,default:!1})){t.quiet||j("Deletion cancelled");return}}catch{t.quiet||j("Deletion cancelled");return}try{await io(e),t.quiet||C(`Presentation "${e}" deleted`)}catch(n){d(n instanceof Error?n.message:String(n)),process.exit(n.exitCode??1)}});import{Command as qe}from"commander";import Xo from"chalk";import kd from"ora";import{createParser as Jf}from"eventsource-parser";import Xf from"chalk";import Yf from"ora";async function zo(e,t={}){let n=e.body?.getReader();if(!n)throw new Error("Response body is not readable");let r=new TextDecoder,o="",i=!1;for(;!i;){let a=await n.read();if(i=a.done,a.value){let s=r.decode(a.value,{stream:!0});o+=s,t.quiet||process.stdout.write(s)}}return t.quiet||console.log(),o}function Cd(){return new qe("blog").description("Generate a blog post from a presentation").argument("<slug>","Presentation slug").option("--words <count>","Target word count (50-2000)","300").option("--tone <tone>","Writing tone (professional, casual, educational)","professional").option("--audience <text>","Target audience description").option("-f, --format <format>","Output format (human, json, markdown)","human").option("--instructions <text>","Custom instructions for the blog").option("--no-images","Exclude image references").option("--toc","Include table of contents").action(async(e,t)=>{await A();let n=parseInt(t.words,10);(Number.isNaN(n)||n<50||n>2e3)&&(d("Word count must be between 50 and 2000"),process.exit(6));let r=["professional","casual","educational"];r.includes(t.tone)||(d(`Invalid tone. Valid options: ${r.join(", ")}`),process.exit(6));let o=kd("Fetching presentation...").start();try{let i=await we(e);o.text="Generating blog post...";let a=await po(i.id,i.documentCreatedAt||i.createdAt,{targetWordCount:n,tone:t.tone,targetAudience:t.audience??"General Audience",customInstructions:t.instructions??"",includeImages:!t.noImages,includeTableOfContents:t.toc??!1}),s=await zo(a,{quiet:!0});o.succeed("Blog generated"),t.format==="json"?console.log(JSON.stringify({presentationId:e,title:i.title,wordCount:n,tone:t.tone,content:s},null,2)):t.format==="markdown"?console.log(s):(console.log(),console.log(Xo.bold(`Blog: ${i.title}`)),console.log(Xo.gray("\u2500".repeat(40))),console.log(),console.log(s),console.log())}catch(i){o.fail("Generation failed"),d(i instanceof Error?i.message:String(i)),process.exit(i.exitCode??1)}})}function Id(){return new qe("tweets").description("Generate tweets from a presentation").argument("<slug>","Presentation slug").option("--count <n>","Number of tweets to generate","5").option("-f, --format <format>","Output format (human, json)","human").action(async(e,t)=>{await A(),g("Tweet generation coming soon.")})}function Rd(){return new qe("linkedin").description("Generate a LinkedIn carousel from a presentation").argument("<slug>","Presentation slug").option("-f, --format <format>","Output format (human, json)","human").action(async e=>{await A(),g("LinkedIn carousel generation coming soon.")})}function Sd(){return new qe("questions").description("Generate questions for a presentation").argument("<slug>","Presentation slug").option("--count <n>","Number of questions","10").option("-f, --format <format>","Output format (human, json)","human").action(async(e,t)=>{await A(),g("Question generation coming soon.")})}function $d(){return new qe("cheatsheet").description("Generate a presenter cheat sheet").argument("<slug>","Presentation slug").option("--mode <mode>","Cheat sheet mode (qa-prep, talking-points)","qa-prep").option("-f, --format <format>","Output format (human, json, markdown)","human").action(async(e,t)=>{await A(),g("Cheat sheet generation coming soon.")})}function Ho(){let e=new qe("derive").description("Generate derivative content from a presentation"),t=Vo();return t&&(t.deckToBlog&&e.addCommand(Cd()),t.deckToTweets&&e.addCommand(Id()),t.linkedInCarousel&&e.addCommand(Rd()),t.redTeamQuestions&&e.addCommand(Sd()),t.presenterCheatSheet&&e.addCommand($d())),e}import _t from"chalk";import{Command as Td}from"commander";import{writeFile as Ed}from"fs/promises";import{resolve as Yo}from"path";import Ad from"ora";var An=new Td("export").description("Export a presentation to a ZIP of HTML and its assets").argument("<slug>","Presentation slug (e.g., my-presentation-v1-abc123)").option("-o, --output <path>","Output file path").option("--include-images","Include images (default: true)",!0).option("--include-branding","Include branding (default: true)",!0).option("--no-external","Skip external image downloads").action(async(e,t)=>{await A();let n=Ad("Fetching presentation...").start();try{let r=await we(e),o=r.title||e,i=r.id,a=e.replace(/[^a-z0-9-]/gi,"_").toLowerCase().substring(0,50),s=new Date().toISOString().split("T")[0],l=`${a}_${s}.zip`,f=t.output?Yo(t.output):Yo(process.cwd(),l);n.text=`Exporting "${o}"...`;let p=await ao(i,{includeImages:t.includeImages,includeBranding:t.includeBranding,includeExternal:!t.noExternal});n.text="Saving file...",await Ed(f,Buffer.from(p)),n.succeed("Export complete!"),console.log(),g(`File saved: ${f}`),g(`Size: ${Od(p.byteLength)}`),console.log()}catch(r){n.fail("Export failed"),d(r instanceof Error?r.message:String(r)),process.exit(r.exitCode??1)}});function Od(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}An.addHelpText("after",`
|
|
6
|
+
${_t.bold("Examples:")}
|
|
7
|
+
${_t.gray("# HTML + assets ZIP of a deck")}
|
|
7
8
|
$ ${u.commands[0]} export <slug> -o deck.zip
|
|
8
9
|
|
|
9
|
-
${
|
|
10
|
-
${
|
|
10
|
+
${_t.bold("See also:")}
|
|
11
|
+
${_t.gray("# For an MP4 instead of a ZIP")}
|
|
11
12
|
$ ${u.commands[0]} presentation video <slug>
|
|
12
|
-
`);import{Command as
|
|
13
|
+
`);import{Command as Pd}from"commander";import On from"chalk";var Qo=new Pd("ideas").description("Generate presentation topic ideas").option("--context <text>","Custom context for idea generation").option("--count <n>","Number of ideas to generate","5").option("-f, --format <format>","Output format (human, json)","human").action(async e=>{await A(),g("Idea generation is available in the web dashboard."),console.log(),console.log(On.gray("The CLI will support idea generation in a future release.")),console.log(),console.log("For now, try these approaches:"),console.log(On.gray("` 1. Visit the ${brand.displayName} dashboard and use the idea generator`")),console.log(On.gray(" 2. Create a presentation with a broad topic and refine it")),console.log()});import{Command as _d}from"commander";import{readFile as Ld}from"fs/promises";import{resolve as Dd,basename as Nd}from"path";import Ud from"ora";var Zo=new _d("import").description("Import a presentation from ZIP (admin only)").argument("<file>","Path to ZIP file");Zo._hidden=!0;var ei=Zo.option("--dry-run","Validate without importing").option("--overwrite","Overwrite existing presentations").option("--remap-ids","Generate new IDs (default: true)",!0).action(async(e,t)=>{await A();try{(await he()).user.role!=="admin"&&(d("This command is only available to administrators"),process.exit(2))}catch{d("Failed to verify permissions"),process.exit(2)}let n=Dd(e),r=Nd(n);r.endsWith(".zip")||(d("File must be a ZIP archive"),process.exit(6));let o=Ud("Reading file...").start();try{let i=await Ld(n);t.dryRun?o.text="Validating...":o.text="Importing presentation...";let a=await so(i,r,{dryRun:t.dryRun});if(a.success){if(t.dryRun)o.succeed("Validation passed!"),console.log(),g("The file is valid and can be imported."),a.statistics&&(console.log(),S("Slides",String(a.statistics.slidesImported)),S("Images",String(a.statistics.imagesUploaded)));else if(o.succeed("Import complete!"),console.log(),S("Presentation ID",a.presentationId??"N/A"),S("Document ID",a.documentId??"N/A"),a.statistics&&(S("Slides imported",String(a.statistics.slidesImported)),S("Images uploaded",String(a.statistics.imagesUploaded)),S("Time",`${a.statistics.totalTimeMs}ms`)),a.presentationId){let s=G();S("View URL",`${s}/p/${a.presentationId}`)}if(a.warnings&&a.warnings.length>0){console.log();for(let s of a.warnings)j(s)}console.log()}else{if(o.fail("Import failed"),console.log(),a.errors)for(let s of a.errors)d(`${s.type}: ${s.message}`);process.exit(1)}}catch(i){o.fail("Import failed"),i.code==="ENOENT"&&(d(`File not found: ${n}`),process.exit(3)),d(i instanceof Error?i.message:String(i)),process.exit(i.exitCode??1)}});import{Command as qd}from"commander";var ti=new qd("list").description("List presentations").option("-n, --limit <count>","Number of results to return","20").option("-f, --format <format>","Output format (table, json, ids)","table").option("--sort <field>","Sort by field (created, updated, title)").option("--team-id <id>","Team ID (uses default if not specified)").option("-d, --detail","Show detailed output including URLs").option("-l, --language <lang>","Language for URLs","en").action(async e=>{await A();let t=parseInt(e.limit,10);(Number.isNaN(t)||t<1)&&(d("Invalid limit value"),process.exit(6));let n=e.teamId??kt();n||(d("`Team ID required. Set a default with '${brand.commands[0]} config set team-id <id>' or use --team-id`"),process.exit(6));try{let r=await no(n,t);if(r.length===0){e.format==="json"?console.log(JSON.stringify([])):e.format!=="ids"&&g("No presentations found");return}switch(e.sort&&r.sort((o,i)=>{switch(e.sort){case"created":return new Date(i.createdAt).getTime()-new Date(o.createdAt).getTime();case"title":return(o.title||"").localeCompare(i.title||"");default:return 0}}),e.format){case"json":console.log(JSON.stringify(r,null,2));break;case"ids":console.log(qr(r));break;default:console.log(Ur(r,{showLinks:e.detail,language:e.language}));break}}catch(r){d(r instanceof Error?r.message:String(r)),process.exit(r.exitCode??1)}});import{createHash as jd,randomBytes as oi}from"crypto";import ii from"http";import ni from"chalk";import{Command as Md}from"commander";import Fd from"open";import ri from"ora";var Vd=`${u.displayName} CLI`,Gd=8765,Bd=8775,Wd=["presentations:read","presentations:write","media:read","media:write"];function Kd(){return oi(32).toString("base64url")}function Jd(e){return jd("sha256").update(e).digest("base64url")}function zd(){return oi(16).toString("hex")}async function Xd(e,t){for(let n=e;n<=t;n++)try{return await new Promise((r,o)=>{let i=ii.createServer();i.listen(n,()=>{i.close(()=>r())}),i.on("error",o)}),n}catch{}throw new Error(`No available port found between ${e} and ${t}`)}async function Hd(e){let t=await fetch(`${e}/.well-known/oauth-authorization-server`);if(!t.ok)throw new Error(`Failed to fetch OAuth metadata: ${t.status}`);return t.json()}function Yd(e){let t=e.scopes_supported?.filter(n=>typeof n=="string"&&n.trim().length>0);return(t?.length?t:Wd).join(" ")}async function Qd(e,t,n){let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Vd,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",scope:n})});if(!r.ok){let o=await r.text();throw new Error(`Client registration failed: ${o}`)}return r.json()}async function Zd(e,t,n,r,o){let i=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:r,client_id:o,code_verifier:n}),a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});if(!a.ok){let s=await a.text();throw new Error(`Token exchange failed: ${s}`)}return a.json()}function ec(e,t){return new Promise((n,r)=>{let o,i=!1,a=()=>{i||(i=!0,clearTimeout(o),process.off("SIGINT",s),process.off("SIGTERM",s),l.close())},s=()=>{a(),r(new Error("Login cancelled"))},l=ii.createServer((f,p)=>{let w=new URL(f.url||"",`http://localhost:${e}`);if(w.pathname!=="/callback"){p.writeHead(404),p.end("Not found");return}let v=w.searchParams.get("code"),b=w.searchParams.get("state"),$=w.searchParams.get("error"),x=w.searchParams.get("error_description");if(p.writeHead(200,{"Content-Type":"text/html"}),$){p.end(`
|
|
13
14
|
<!DOCTYPE html>
|
|
14
15
|
<html>
|
|
15
16
|
<head><title>Login Failed</title></head>
|
|
@@ -19,7 +20,7 @@ ${$t.bold("See also:")}
|
|
|
19
20
|
<p>You can close this window.</p>
|
|
20
21
|
</body>
|
|
21
22
|
</html>
|
|
22
|
-
`),a(),r(new Error(x||$));return}if(!v||!b){
|
|
23
|
+
`),a(),r(new Error(x||$));return}if(!v||!b){p.end(`
|
|
23
24
|
<!DOCTYPE html>
|
|
24
25
|
<html>
|
|
25
26
|
<head><title>Login Failed</title></head>
|
|
@@ -29,7 +30,7 @@ ${$t.bold("See also:")}
|
|
|
29
30
|
<p>You can close this window.</p>
|
|
30
31
|
</body>
|
|
31
32
|
</html>
|
|
32
|
-
`),a(),r(new Error("Missing authorization code or state"));return}if(b!==t){
|
|
33
|
+
`),a(),r(new Error("Missing authorization code or state"));return}if(b!==t){p.end(`
|
|
33
34
|
<!DOCTYPE html>
|
|
34
35
|
<html>
|
|
35
36
|
<head><title>Login Failed</title></head>
|
|
@@ -39,7 +40,7 @@ ${$t.bold("See also:")}
|
|
|
39
40
|
<p>You can close this window.</p>
|
|
40
41
|
</body>
|
|
41
42
|
</html>
|
|
42
|
-
`),a(),r(new Error("State mismatch"));return}
|
|
43
|
+
`),a(),r(new Error("State mismatch"));return}p.end(`
|
|
43
44
|
<!DOCTYPE html>
|
|
44
45
|
<html>
|
|
45
46
|
<head><title>Login Successful</title></head>
|
|
@@ -48,120 +49,149 @@ ${$t.bold("See also:")}
|
|
|
48
49
|
<p>You can close this window and return to the terminal.</p>
|
|
49
50
|
</body>
|
|
50
51
|
</html>
|
|
51
|
-
`),a(),n({code:v,state:b})});l.listen(e),process.once("SIGINT",s),process.once("SIGTERM",s),o=setTimeout(()=>{a(),r(new Error("Login timed out - no callback received within 5 minutes"))},300*1e3)})}async function
|
|
52
|
-
`)[0]??"";n(a?{bin:t,version:a}:null)})})}var
|
|
52
|
+
`),a(),n({code:v,state:b})});l.listen(e),process.once("SIGINT",s),process.once("SIGTERM",s),o=setTimeout(()=>{a(),r(new Error("Login timed out - no callback received within 5 minutes"))},300*1e3)})}async function tc(e,t){let n=await fetch(`${e}/api/cli/whoami`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw new Error(`Failed to fetch user info: ${n.status}`);return n.json()}async function nc(e){let t=G(),n=ri("Discovering OAuth server...").start();try{let r=await Hd(t),o=Yd(r);n.succeed(`Connecting to ${t}`);let i=await Xd(Gd,Bd),a=`http://localhost:${i}/callback`;console.log(`Redirect URI: ${a}`),console.log(`Authorization endpoint: ${r.authorization_endpoint}`),console.log(`Token endpoint: ${r.token_endpoint}`),console.log(`Registration endpoint: ${r.registration_endpoint}`);let s=await Qd(r.registration_endpoint,a,o),l=s.client_id;Dr(l,s.client_secret);let f=Kd(),p=Jd(f),w=zd(),v=new URLSearchParams({client_id:l,redirect_uri:a,response_type:"code",scope:o,state:w,code_challenge:p,code_challenge_method:"S256"}),b=`${r.authorization_endpoint}?${v}`;console.log(`Authorization URL: ${b}`),e.browser?(g("Opening browser..."),await Fd(b)):(console.log(ni.bold("Open this URL in your browser:")),console.log(ni.cyan(b)));let $=ec(i,w),{code:x}=await $;n=ri("Completing login...").start();let k=await Zd(r.token_endpoint,x,f,a,l);It(k.access_token,k.refresh_token,k.expires_in);let R=await tc(t,k.access_token);n.succeed("Logged in!"),console.log(),S("Logged in as",R.user.email),R.currentTeam&&(De(R.currentTeam.id),S("Team",`${R.currentTeam.name} (${R.currentTeam.planName})`));try{await Ee()}catch{}console.log(),C("You're all set!"),console.log()}catch(r){throw n.fail("Login failed"),d(r instanceof Error?r.message:String(r)),r}}var ai=new Md("login").description(`Authenticate with ${u.displayName} (opens browser)`).option("--no-browser","Print URL instead of opening browser").action(async e=>{console.log(),$e()&&(j("You are already logged in."),g(`Run '${u.commands[0]} logout' to log out first, or continue to re-authenticate.`),console.log());try{await nc(e),process.exit(0)}catch{process.exit(1)}});import{Command as rc}from"commander";import{confirm as oc}from"@inquirer/prompts";var si=new rc("logout").description("Log out and clear authentication").option("--all","Clear all config including API key").action(async e=>{console.log();let t=$e(),n=Ne();if(!t&&!n){j("You are not logged in."),console.log();return}if(e.all)try{await oc({message:"Clear all configuration including API key?",default:!1})?(Ct(),Ae(),C("All configuration cleared.")):g("Cancelled.")}catch{g("Cancelled.")}else Rt(),Ae(),C("Logged out successfully."),n&&g("Note: Your API key is still configured. Use --all to clear everything.");console.log()});import{homedir as Gc}from"os";import{join as Bc}from"path";import ie from"chalk";import{Command as Wc}from"commander";import{spawn as ic}from"child_process";import{existsSync as ac,readdirSync as sc}from"fs";import{homedir as li}from"os";import{delimiter as di}from"path";import{query as dc}from"@anthropic-ai/claude-agent-sdk";function ee(e){if(e===void 0)return null;if(typeof e=="string")return e.length>12e3?`${e.slice(0,12e3)}\u2026`:e;try{let t=JSON.stringify(e);return t.length<=12e3?e:{preview:`${t.slice(0,12e3)}\u2026`,truncated:!0}}catch{return String(e).slice(0,12e3)}}function Lt(e){let t=typeof e=="string"?e:String(e??"");return t.length>12e3?`${t.slice(0,12e3)}\u2026`:t}function te(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function L(e){return typeof e=="string"?e:""}function ci(e,t){let n=e.replace(/[/.]/g,"-");return`${li()}/.claude/projects/${n}/${t}.jsonl`}function cc(e){try{return sc(`${e}/.nvm/versions/node`).map(t=>`${e}/.nvm/versions/node/${t}/bin`).sort().reverse()}catch{return[]}}function Dt(){let e=li(),t=[`${e}/.local/bin`,`${e}/.claude/local`,`${e}/.bun/bin`,`${e}/bin`,"/opt/homebrew/bin","/usr/local/bin",...cc(e)],r=(process.env.PATH??"").split(di);for(let o of t)r.includes(o)||r.push(o);return r.join(di)}async function Nt(e){let t=e??"claude";return new Promise(n=>{let r=ic(t,["--version"],{env:{...process.env,PATH:Dt()},stdio:["ignore","pipe","ignore"]}),o="";r.stdout.on("data",i=>{o+=i.toString("utf8")}),r.on("error",()=>n(null)),r.on("close",i=>{if(i!==0)return n(null);let a=o.trim().split(`
|
|
53
|
+
`)[0]??"";n(a?{bin:t,version:a}:null)})})}var lc=new Set(["","default","best"]);function Pn(e){let t=e.filter(i=>i.text.trim());if(t.length===0)return"";let n=t[t.length-1],r=t.slice(0,-1);return r.length===0?n.text:`<conversation-history>
|
|
53
54
|
${r.map(i=>`${i.role==="assistant"?"Assistant":"User"}: ${i.text}`).join(`
|
|
54
55
|
|
|
55
56
|
`)}
|
|
56
57
|
</conversation-history>
|
|
57
58
|
|
|
58
|
-
${n.text}`}function
|
|
59
|
-
`)[0]??"";t(i||null)})})}var
|
|
60
|
-
`)}catch{return[]}let n=new Set,r=new Map,o=null;for(let i of t){if(!i.trim())continue;let a;try{a=JSON.parse(i)}catch{continue}let s=
|
|
61
|
-
`);return a===-1?"":i.slice(a+1)}finally{
|
|
62
|
-
`):e&&typeof e=="object"?Object.values(e).map(
|
|
63
|
-
`):""}function
|
|
64
|
-
|
|
65
|
-
`),usage:a}}function
|
|
66
|
-
`,"utf8")}catch{}}function
|
|
67
|
-
`,"utf8")}catch{}}var
|
|
68
|
-
Stopping runner\u2026`)),t.abort()};process.on("SIGINT",n),process.on("SIGTERM",n);try{await fi({claudeBin:e.claudeBin,codexBin:e.codexBin,log:r=>console.log(te.gray(`[runner] ${r}`)),once:e.once,signal:t.signal,version:"0.3.17",workspaceRoot:e.workspace??Lc()})}catch(r){console.error(te.red(r instanceof Error?r.message:String(r))),process.exit(1)}});import q from"chalk";import{Command as Sp}from"commander";import{Command as Dn}from"commander";function Dc(e,t){return[...t,e]}var Nc=new Dn("create").description("Start durable ad-set generation").argument("<title>","Ad-set title").requiredOption("--brief <brief>","Campaign brief").option("--hook <text>","Opening hook (repeat)",Dc,[]).option("--style <style>","ugc, clean, cinematic, or testimonial","ugc").option("--branding-id <id>","Branding ID").option("--team-id <id>","Workspace ID").option("--yes","Approve generation").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to approve generation");try{p(await y("createAdSet",{approvalReceipt:"cli:--yes",brandingId:t.brandingId,brief:t.brief,hooks:t.hook.length?t.hook:[t.brief],style:t.style,teamId:t.teamId,title:e}))}catch(n){d(n instanceof Error?n.message:"Generation failed"),process.exit(c.GENERAL_ERROR)}}),Uc=new Dn("status").description("Read ad-set generation status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await T("createAdSet",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),hi=new Dn("ad-set").description("Generate a set of ad creatives (hooks, copy, visuals) from a campaign brief").addCommand(Nc).addCommand(Uc);import{randomUUID as qc}from"crypto";import{Command as Ne}from"commander";function yi(e){return new Ne(e).description(e==="create"?"Create and activate a scheduled agent":"Create a reviewable agent recommendation").argument("<name>","Agent name").requiredOption("--instructions <markdown>","Agent instructions").option("--description <text>","Agent description","").option("--schedule <frequency>","manual, daily, weekdays, weekly, or monthly","weekly").option("--time <hh:mm>","Local run time","09:00").option("--timezone <zone>","IANA timezone","UTC").option("--output <adapter>","Output adapter","digest").option("--team-id <id>","Workspace ID").option("--yes","Approve saving the agent").action(async(t,n)=>{if(!n.yes)return d("Pass --yes to approve this operation");try{p(await y(e==="create"?"createAgent":"recommendAgent",{approvalReceipt:"cli:--yes",description:n.description,instructionsMarkdown:n.instructions,name:t,output:n.output,schedule:n.schedule,scheduleTime:n.time,teamId:n.teamId,timezone:n.timezone}))}catch(r){d(r instanceof Error?r.message:"Agent operation failed"),process.exit(c.GENERAL_ERROR)}})}function Un(e,t){d(e instanceof Error?e.message:t),process.exit(c.GENERAL_ERROR)}function bi(e){return`cli:agent-memory:${e}:${qc()}`}function Mc(e,t){let n=e.indexOf("="),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);return[...t,{name:r.trim(),note:o.trim()}]}function Nn(e,t){return[...t,e]}var Fc=new Ne("show").description("Show what a scheduled agent remembers").argument("<agent-id>","Agent ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await y("getAgentMemory",{agentId:e,teamId:t.teamId}))}catch(n){Un(n,"Could not read the agent's memory")}}),Vc=new Ne("set").description("Add to or remove from what an agent remembers. Owner or workspace admin only.").argument("<agent-id>","Agent ID").option("--learned <text>","Durable fact to add (repeatable)",Nn,[]).option("--always <text>","Standing instruction to add (repeatable)",Nn,[]).option("--never <text>","Thing it must not do, to add (repeatable)",Nn,[]).option("--track <name=note>","Entity to track, as name=note (repeatable)",Mc,[]).option("--notes <text>","Replace the freeform notes").option("--remove <field>","Remove instead of add: learned, recurringInstructions, negativePreferences, entities, or notes").option("--value <text>","Item to remove; not needed when removing notes").option("--expected-version <n>","Refuse the write unless the stored memory is still at this version").option("--team-id <id>","Workspace ID").action(async(e,t)=>{let n=typeof t.remove=="string";try{p(await y("updateAgentMemory",{agentId:e,entities:t.track.length?t.track:void 0,expectedVersion:t.expectedVersion===void 0?void 0:Number.parseInt(t.expectedVersion,10),learned:t.learned.length?t.learned:void 0,negativePreferences:t.never.length?t.never:void 0,notes:t.notes,operation:n?"remove":"add",recurringInstructions:t.always.length?t.always:void 0,removeField:t.remove,removeValue:t.value,teamId:t.teamId},bi(n?"remove":"add")))}catch(r){Un(r,"Could not update the agent's memory")}}),jc=new Ne("forget").description("Erase every stored version of an agent's memory. This cannot be undone.").argument("<agent-id>","Agent ID").option("--team-id <id>","Workspace ID").option("--yes","Confirm the erase").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to erase this agent's memory");try{p(await y("forgetAgentMemory",{agentId:e,teamId:t.teamId},bi("forget")))}catch(n){Un(n,"Could not erase the agent's memory")}}),Gc=new Ne("memory").description("Read, edit, and erase what a scheduled agent remembers").addCommand(Fc).addCommand(Vc).addCommand(jc),wi=new Ne("agent").description("Create scheduled agents and read, edit, or erase what they remember").addCommand(yi("create")).addCommand(yi("recommend")).addCommand(Gc);import{randomUUID as ki}from"crypto";import{existsSync as Kc}from"fs";import{resolve as Jc}from"path";import ot from"chalk";import{Command as me}from"commander";import zc from"ora";import{mkdir as Bc,writeFile as vi}from"fs/promises";import{dirname as Wc}from"path";async function J(e,t){if(await Bc(Wc(t),{recursive:!0}),e.startsWith("data:")){let o=e.match(/^data:[^;]+;base64,(.+)$/);if(!o)throw new Error("Invalid data URL format");let i=Buffer.from(o[1],"base64");if(i.length===0)throw new Error("Downloaded media was empty");await vi(t,i);return}let n=await fetch(e);if(!n.ok)throw new Error(`Failed to download media: ${n.status}`);let r=Buffer.from(await n.arrayBuffer());if(r.length===0)throw new Error("Downloaded media was empty");await vi(t,r)}var Xc=15e3,Hc=40,xi=3;async function Ci(e,t){if(e?.length){if(e.length>xi)throw new Error(`A presenter Look accepts at most ${xi} reference images`);return Promise.all(e.map(async(n,r)=>{if(Kc(n))return{url:(await se(Jc(n),{idempotencyKey:`${t}:reference:${r+1}`})).url};let o;try{o=new URL(n)}catch(i){throw new Error(`Reference image ${r+1} must be an existing local file or an HTTP(S) URL.`,{cause:i})}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`Reference image ${r+1} must use an HTTP(S) URL.`);return{url:o.toString()}}))}}function qn(e,t){if(t==="json"){p(e);return}if(t==="quiet"){console.log(e.videoUrl??e.requestId);return}f(`Request ID: ${e.requestId}`),f(`Status: ${e.status}`),e.durationSec!=null&&f(`Duration: ${e.durationSec}s`),e.videoUrl&&C(`Video URL: ${e.videoUrl}`),e.error&&d(`Error: ${e.error}`)}var Yc=new me("options").description("List available presenter avatars and voices").option("--language <language>","Filter voices by language").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{try{let t=await fo(e.language);if(e.format==="json"){p(t);return}let n=t.personal??[];if(e.format==="quiet"){for(let r of n)console.log(r.id);for(let r of t.avatars)console.log(r.id);for(let r of t.voices)console.log(r.id);return}if(n.length>0){f("Your presenters:");for(let r of n)console.log(` ${r.id} ${r.name}`)}f("Avatars:");for(let r of t.avatars){let o=r.renderTiers?.length?` [${r.renderTiers.join(", ")}]`:"";console.log(` ${r.id} ${r.name}${o}`)}f("Voices:");for(let r of t.voices)console.log(` ${r.id} ${r.name}${r.language?` (${r.language})`:""}`)}catch(t){d(t instanceof Error?t.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Qc=new me("generate").description("Generate a reusable presenter clip").option("--avatar-id <id>","Avatar id from 'avatar options'; sandbox runs use the host presenter policy").option("--audio-url <url>","Public narration audio URL for avatar lip sync").option("--voice-id <id>","Voice id from 'avatar options'").option("--script <text>","Exact words for the presenter to speak").requiredOption("-o, --output <path>","Local output path").option("--aspect <aspect>","Aspect: 1:1, 9:16, 16:9","9:16").option("--duration <seconds>","Maximum requested duration (1-300)").option("--transparent","Render a transparent-background WebM presenter clip").option("--background-color <hex>","Solid presenter background color, for example #0F172A").option("--background-image-url <url>","Public image URL used as the presenter background").option("--fit <mode>","Background image fit: contain or cover").option("--output-format <container>","Container: mp4 (default) or webm \u2014 webm renders a transparent-background clip (single scene) for compositing").option("--render-tier <tier>","Render cost/quality: basic, standard, premium","basic").option("--title <title>","Clip title","Presenter clip").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.transparent?"webm":e.outputFormat;!!e.audioUrl==!!e.script&&(d("Provide exactly one avatar speech input: --audio-url or --script"),process.exit(c.INVALID_INPUT)),["1:1","9:16","16:9"].includes(e.aspect)||(d("Aspect must be one of 1:1, 9:16, or 16:9"),process.exit(c.INVALID_INPUT)),e.outputFormat!==void 0&&!["mp4","webm"].includes(e.outputFormat)&&(d("Output format must be mp4 or webm"),process.exit(c.INVALID_INPUT)),e.backgroundColor!==void 0&&!/^#[0-9a-fA-F]{6}$/.test(e.backgroundColor)&&(d("Background color must be a six-digit hex value"),process.exit(c.INVALID_INPUT)),e.backgroundColor&&e.backgroundImageUrl&&(d("Provide only one presenter background"),process.exit(c.INVALID_INPUT)),e.fit!==void 0&&!["contain","cover"].includes(e.fit)&&(d("Fit must be contain or cover"),process.exit(c.INVALID_INPUT)),e.fit&&!e.backgroundImageUrl&&(d("Fit requires --background-image-url"),process.exit(c.INVALID_INPUT)),e.transparent&&e.outputFormat==="mp4"&&(d("--transparent cannot be combined with --output-format mp4"),process.exit(c.INVALID_INPUT)),t==="webm"&&(e.backgroundColor||e.backgroundImageUrl)&&(d("Transparent WebM output cannot be combined with a background"),process.exit(c.INVALID_INPUT)),["basic","standard","premium"].includes(e.renderTier)||(d("Render tier must be basic, standard, or premium"),process.exit(c.INVALID_INPUT));let n=e.duration?Number.parseInt(e.duration,10):void 0;n!==void 0&&(!Number.isFinite(n)||n<1||n>300)&&(d("Duration must be between 1 and 300 seconds"),process.exit(c.INVALID_INPUT));let r=e.format==="human"?zc("Generating presenter clip...").start():null;try{let o=e.audioUrl?{audioUrl:e.audioUrl}:{script:e.script??"",...e.voiceId?{voiceId:e.voiceId}:{}},i=await ho({...o,aspect:e.aspect,...e.avatarId?{avatarId:e.avatarId}:{},...e.backgroundColor?{backgroundHex:e.backgroundColor}:{},...e.backgroundImageUrl?{backgroundImageUrl:e.backgroundImageUrl}:{},...n!==void 0?{durationSec:n}:{},...e.fit?{fit:e.fit}:{},...t?{outputFormat:t}:{},renderTier:e.renderTier,title:e.title});if(!e.wait){r?.stop(),qn(i,e.format);return}let a=await Y(()=>kn(i.requestId),Hc,Xc);if(a.status==="failed")throw new Error(a.error||"Presenter generation failed");if(!a.videoUrl)throw new Error("Presenter generation completed without a video URL");r&&(r.text="Downloading presenter clip..."),await J(a.videoUrl,e.output),r?.stop(),qn(a,e.format),e.format==="human"&&C(`Saved to: ${e.output}`)}catch(o){r?.stop(),d(o instanceof Error?o.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Zc=new me("status").description("Check a presenter clip generation request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{qn(await kn(e),t.format)}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),el=new me("generate").description("Generate another look for an existing personal presenter").argument("<base-profile-id>","Base personal presenter id (pp_*)").requiredOption("--name <name>","Look name").requiredOption("--description <description>","Short look description").requiredOption("--prompt <prompt>","Exact appearance generation prompt").requiredOption("--look-id <id>","Stable template/look id").option("--reference-image <path-or-url...>","Up to three local images or URLs for location, outfit, or style guidance").option("--idempotency-key <key>","Stable retry key for this look request").action(async(e,t)=>{try{let n=t.idempotencyKey??ki(),r=await Ci(t.referenceImage,n),o=await y("generatePresenterLook",{baseProfileId:e,description:t.description,id:t.lookId,prompt:t.prompt,...r?{referenceImages:r}:{},title:t.name},n);p(o)}catch(n){d(n instanceof Error?n.message:"Look generation failed"),process.exit(c.GENERAL_ERROR)}}),tl=new me("status").description("Read presenter look generation status").argument("<run-id>","Durable run ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("generatePresenterLook",e);if(t.format==="json")return p(n);if(t.format==="quiet")return console.log(n.status);f(`Run ID: ${e}`),f(`Status: ${n.status}`),n.error?.message&&d(n.error.message)}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),nl=new me("revise").description("Create a new Look by editing an existing presenter Look").argument("<look-id>","Ready presenter Look id (pp_*)").requiredOption("--instruction <instruction>","What to add, remove, or change").option("--reference-image <path-or-url...>","Up to three local images or URLs for location, outfit, or style guidance").option("--idempotency-key <key>","Stable retry key for this revision").action(async(e,t)=>{try{let n=t.idempotencyKey??ki(),r=await Ci(t.referenceImage,n),o=await y("revisePresenterLook",{instruction:t.instruction,...r?{referenceImages:r}:{},sourceLookId:e},n);p(o)}catch(n){d(n instanceof Error?n.message:"Look revision failed"),process.exit(c.GENERAL_ERROR)}}),rl=new me("revision-status").description("Read presenter Look revision status").argument("<run-id>","Durable run ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("revisePresenterLook",e);if(t.format==="json")return p(n);if(t.format==="quiet")return console.log(n.status);f(`Run ID: ${e}`),f(`Status: ${n.status}`),n.error?.message&&d(n.error.message)}catch(n){d(n instanceof Error?n.message:"Revision status failed"),process.exit(c.GENERAL_ERROR)}}),ol=new me("look").description("Manage looks under an existing personal presenter").addCommand(el).addCommand(nl).addCommand(rl).addCommand(tl),Mn=new me("avatar").description("Generate presenter clips and looks; avatar options lists the voices and looks used by presentation video presenter and cast preset").addCommand(Yc).addCommand(Qc).addCommand(ol).addCommand(Zc);Mn.addHelpText("after",`
|
|
69
|
-
${
|
|
70
|
-
${
|
|
59
|
+
${n.text}`}function _n(e,t){return t?e.messages.filter(r=>r.text.trim()).at(-1)?.text??"":Pn(e.messages)}function uc({abortController:e,input:t,resumeSessionId:n,workspace:r}){let o=(t.modelId??"").trim(),i=t.thinking??null,a={abortController:e,allowedTools:["WebSearch","WebFetch"],cwd:r,env:{...process.env,PATH:Dt()},includePartialMessages:!0,maxTurns:16,permissionMode:"dontAsk"};return lc.has(o)||(a.model=o),t.effort&&(a.effort=t.effort),i&&i!=="disabled"&&(a.thinking={display:"summarized",type:i==="enabled"?"enabled":"adaptive"}),n?a.resume=n:t.system?.trim()&&(a.systemPrompt=t.system),a}async function ui(e){let t=_n(e.input,e.resumeSessionId);if(!t)throw new Error("Chat turn has no user text to send.");let n=new AbortController,r=()=>n.abort();e.signal?.addEventListener("abort",r,{once:!0});let o=null,i=null,a=null,s=null,l=null,f=0,p=new Set;try{let b=dc({prompt:t,options:uc({abortController:n,input:e.input,resumeSessionId:e.resumeSessionId,workspace:e.workspace})});for await(let $ of b){let x=$;if(x.type==="system"&&x.subtype==="init"){typeof x.session_id=="string"&&(i=x.session_id,e.onEvent({eventType:"chat.session",payload:{sessionId:i,sessionPath:ci(e.workspace,i)}})),typeof x.model=="string"&&(o=x.model,e.onEvent({eventType:"chat.model",payload:{modelId:x.model}}));continue}if(x.type==="stream_event"){let k=x.event;if(k?.type!=="content_block_delta")continue;let R=k.delta;if(!R)continue;R.type==="text_delta"&&typeof R.text=="string"?(f+=R.text.length,e.onEvent({eventType:"chat.text.delta",payload:{text:R.text}})):R.type==="thinking_delta"&&typeof R.thinking=="string"&&e.onEvent({eventType:"chat.reasoning.delta",payload:{text:R.thinking}});continue}if(x.type==="assistant"){let k=te(x.message),R=Array.isArray(k.content)?k.content:[];for(let N of R){let E=te(N);if(E.type!=="tool_use")continue;let U=L(E.id),I=L(E.name);!U||!I||p.has(U)||(p.add(U),e.onEvent({eventType:"chat.tool.started",payload:{input:ee(E.input),toolCallId:U,toolName:I}}))}continue}if(x.type==="user"){let k=te(x.message),R=Array.isArray(k.content)?k.content:[];for(let N of R){let E=te(N);if(E.type!=="tool_result")continue;let U=L(E.tool_use_id);U&&e.onEvent({eventType:"chat.tool.completed",payload:{...E.is_error===!0?{errorText:typeof E.content=="string"?Lt(E.content):"Claude tool call failed."}:{},output:ee(E.content),toolCallId:U}})}continue}x.type==="result"&&(typeof x.result=="string"&&(s=x.result),x.usage&&typeof x.usage=="object"&&(a=x.usage),typeof x.session_id=="string"&&(i=x.session_id),(x.is_error===!0||x.subtype!=="success")&&(l=typeof x.result=="string"&&x.result||`Claude turn failed (${String(x.subtype)}).`,e.onEvent({eventType:"chat.error",message:l,payload:{message:l}})))}}finally{e.signal?.removeEventListener("abort",r)}if(e.signal?.aborted)throw new Error("Chat turn cancelled.");if(l)throw new Error(l);let w=s??"";f===0&&w&&e.onEvent({eventType:"chat.text.delta",payload:{text:w}});let v=i?ci(e.workspace,i):null;return{modelId:o,sessionId:i,sessionPath:v&&ac(v)?v:null,text:w,usage:a}}import{spawn as mc}from"child_process";import{closeSync as pc,fstatSync as gc,openSync as fc,readdirSync as hc,readSync as yc}from"fs";import{homedir as bc}from"os";import{join as mi}from"path";import{Codex as wc}from"@openai/codex-sdk";var vc=["/Applications/Codex.app/Contents/Resources/codex"];async function Ut(e){let t=e?[e]:["codex",...vc];for(let n of t){let r=await xc(n);if(r)return{bin:n,version:r}}return null}function xc(e){return new Promise(t=>{let n=mc(e,["--version"],{env:{...process.env,PATH:Dt()},stdio:["ignore","pipe","ignore"]}),r="";n.stdout.on("data",o=>{r+=o.toString("utf8")}),n.on("error",()=>t(null)),n.on("close",o=>{if(o!==0)return t(null);let i=r.trim().split(`
|
|
60
|
+
`)[0]??"";t(i||null)})})}var kc=24,Cc=4*1024*1024,fi=new Set(["custom_tool_call","custom_tool_call_output","dynamic_tool_call","function_call"]);function Ic(e){let t;try{t=Rc(e).split(`
|
|
61
|
+
`)}catch{return[]}let n=new Set,r=new Map,o=null;for(let i of t){if(!i.trim())continue;let a;try{a=JSON.parse(i)}catch{continue}let s=te(a.payload);if(a.type==="response_item"&&s.type==="custom_tool_call"){let l=L(s.call_id),f=L(s.input);l&&s.name==="exec"&&/\btools\.web__run\s*\(/.test(f)&&(n.add(l),o=l);continue}if(a.type==="event_msg"&&s.type==="web_search_end"){let l=L(s.call_id);if(!l||!o)continue;let f=L(s.query),p=te(s.action),v={action:{...p,...f&&!L(p.query)?{query:f}:{}},query:f,sources:pi(s.results),toolCallId:l},b=r.get(o)??[];b.push(v),r.set(o,b);continue}if(a.type==="response_item"&&s.type==="custom_tool_call_output"){let l=L(s.call_id);if(!l||!n.has(l))continue;let f=pi(s.output);for(let p of r.get(l)??[])p.sources.length===0&&(p.sources=f);o===l&&(o=null)}}return Array.from(r.values()).flat()}function Rc(e){let t=fc(e,"r");try{let n=gc(t).size,r=Math.max(0,n-Cc),o=Buffer.alloc(n-r);yc(t,o,0,o.length,r);let i=o.toString("utf8");if(r===0)return i;let a=i.indexOf(`
|
|
62
|
+
`);return a===-1?"":i.slice(a+1)}finally{pc(t)}}function pi(e){let n=Nn(e).match(/https?:\/\/[^\s<>"'()[\]{}\\]+/g)??[],r=new Set,o=[];for(let i of n){let a=i.replace(/[.,;:!?]+$/,"");try{let s=new URL(a);if(s.protocol!=="http:"&&s.protocol!=="https:"||r.has(s.href))continue;if(r.add(s.href),o.push({type:"url",url:s.href}),o.length>=kc)break}catch{}}return o}function Nn(e){return typeof e=="string"?e:Array.isArray(e)?e.map(Nn).join(`
|
|
63
|
+
`):e&&typeof e=="object"?Object.values(e).map(Nn).join(`
|
|
64
|
+
`):""}function Ln(e,t){let n=te(e),r=L(n.type),o=L(n.id),i=L(n.call_id)||L(n.tool_call_id),a=fi.has(r)?i||o:o||i;if(!a)return null;if(r==="command_execution"){let s=L(n.command),l=L(n.status),f={exitCode:typeof n.exit_code=="number"?n.exit_code:null,output:ee(n.aggregated_output)};return{...t&&l==="failed"?{errorText:Lt(n.aggregated_output)||"Command failed."}:{},input:{command:s},...t?{output:f}:{},toolCallId:a,toolName:"Bash"}}if(r==="mcp_tool_call"){let s=te(n.error);return{...t&&L(s.message)?{errorText:L(s.message)}:{},input:ee(n.arguments),...t?{output:ee(n.result??{status:n.status??"completed"})}:{},toolCallId:a,toolName:L(n.tool)||L(n.name)||"Codex tool"}}if(r==="web_search"){let s=L(n.query);return{input:{query:s},...t?{output:{query:s}}:{},toolCallId:a,toolName:"web_search"}}if(r==="file_change"){let s=L(n.status);return{...t&&s==="failed"?{errorText:"Codex could not apply the file changes."}:{},input:{changes:ee(n.changes)},...t?{output:{changes:ee(n.changes),status:s}}:{},toolCallId:a,toolName:"ApplyPatch"}}if(r==="custom_tool_call_output")return{input:{},...t?{output:ee(n.output)}:{},toolCallId:a,toolName:"Codex tool"};if(r==="custom_tool_call"||r==="dynamic_tool_call"||r==="function_call"){let s=L(n.name)||L(n.tool)||"Codex tool",l=n.input??n.arguments??{};return{input:s==="exec"&&typeof l=="string"?{command:l}:ee(l),...t?{output:ee(n.output??n.result??{status:n.status??"completed"})}:{},toolCallId:a,toolName:s}}return null}function Dn(e,t=mi(bc(),".codex","sessions")){try{let r=hc(t,{recursive:!0}).find(o=>typeof o=="string"&&o.endsWith(`${e}.jsonl`));return r?mi(t,r):null}catch{return null}}function Sc(e,t){return t?_n(e,t):Pn(e.messages)}function $c(e,t,n=u.codexSelfConnectorAppId){let r=t.system?.trim(),o={...r?{developer_instructions:r}:{},...n?{apps:{[n]:{enabled:!1}}}:{}};return{codexPathOverride:e,...Object.keys(o).length>0?{config:o}:{}}}var Tc=new Set(["minimal","low","medium","high","xhigh"]);function Ec(e,t){let n={networkAccessEnabled:!0,sandboxMode:"workspace-write",skipGitRepoCheck:!0,webSearchEnabled:!0,workingDirectory:t},r=(e.modelId??"").trim();return r&&r!=="default"&&(n.model=r),e.effort&&Tc.has(e.effort)&&(n.modelReasoningEffort=e.effort),n}async function hi(e){let t=Sc(e.input,e.resumeSessionId);if(!t)throw new Error("Chat turn has no user text to send.");let n=new wc($c(e.bin,e.input)),r=Ec(e.input,e.workspace),o=e.resumeSessionId?n.resumeThread(e.resumeSessionId,r):n.startThread(r),i=e.resumeSessionId??null,a=null,s=null,l=[],f=new Set,p=new Set,w=null,v=x=>{w??=Dn(x,e.sessionsRoot),e.onEvent({eventType:"chat.session",payload:{sessionId:x,sessionPath:w}})},b=x=>{i&&(w??=Dn(i,e.sessionsRoot));let k=w?Ic(w):[],R=L(te(x.input).query),N=gi(R),E=k.find(U=>!f.has(U.toolCallId)&&gi(U.query)===N)??k.find(U=>!f.has(U.toolCallId));E&&f.add(E.toolCallId),e.onEvent({eventType:"chat.tool.completed",payload:{...x,output:E?{action:E.action,query:E.query,sources:E.sources}:{action:{query:R,type:"search"},sourceListUnavailable:!0,sources:[]}}})},{events:$}=await o.runStreamed(t);i&&v(i);for await(let x of $){if(e.signal?.aborted)throw await $.return?.(void 0),new Error("Chat turn cancelled.");let k=x;if(k.type==="thread.started"){typeof k.thread_id=="string"&&(i=k.thread_id,v(k.thread_id));continue}if(k.type==="item.started"){let R=Ln(k.item,!1);if(R){e.onEvent({eventType:"chat.tool.started",payload:R});let N=te(k.item);if(fi.has(L(N.type))&&L(N.status)==="completed"){let E=Ln(N,!0);E&&(p.add(E.toolCallId),e.onEvent({eventType:"chat.tool.completed",payload:E}))}}continue}if(k.type==="item.completed"){let R=k.item;if(!R)continue;if(R.type==="agent_message"&&typeof R.text=="string")l.push(R.text),e.onEvent({eventType:"chat.text.delta",payload:{text:R.text}});else if(R.type==="reasoning"&&typeof R.text=="string")e.onEvent({eventType:"chat.reasoning.delta",payload:{text:R.text}});else{let N=Ln(R,!0);N&&(R.type==="web_search"?b(N):R.type==="custom_tool_call"&&p.has(N.toolCallId)||e.onEvent({eventType:"chat.tool.completed",payload:N}))}continue}if(k.type==="turn.completed"){k.usage&&typeof k.usage=="object"&&(a=k.usage);continue}if(k.type==="turn.failed"){let R=k.error;s=typeof R?.message=="string"&&R.message||"Codex turn failed.",e.onEvent({eventType:"chat.error",message:s,payload:{message:s}})}}if(s)throw new Error(s);return i=o.id??i,i&&(w??=Dn(i,e.sessionsRoot)),{modelId:e.input.modelId??null,sessionId:i,sessionPath:w,text:l.join(`
|
|
65
|
+
|
|
66
|
+
`),usage:a}}function gi(e){return e.trim().replace(/\s+/g," ").toLocaleLowerCase()}import{randomUUID as Lc}from"crypto";import{mkdir as Dc}from"fs/promises";import{hostname as jt,platform as Nc}from"os";import{join as Uc}from"path";var je=class extends Error{constructor(n,r,o=!1){super(n);this.statusCode=r;this.reRegister=o;this.name="RunnerApiError"}statusCode;reRegister};async function Me(e,t={}){let n=await le();t.body!==void 0&&(n["Content-Type"]="application/json");let r=new AbortController,o=setTimeout(()=>r.abort(),t.timeoutMs??3e4),i=()=>r.abort();t.signal?.addEventListener("abort",i,{once:!0});try{let a=await fetch(`${G()}${e}`,{body:t.body!==void 0?JSON.stringify(t.body):void 0,headers:n,method:t.method??"GET",signal:r.signal}),s=await a.text(),l={};try{l=s?JSON.parse(s):{}}catch{l={error:s.slice(0,300)}}if(!a.ok)throw new je(typeof l.error=="string"?l.error:`Runner API returned ${a.status}`,a.status,l.reRegister===!0);return l}finally{clearTimeout(o),t.signal?.removeEventListener("abort",i)}}async function yi(e){await Me("/api/runner/register",{body:e,method:"POST",timeoutMs:15e3})}async function bi(e,t){return(await Me(`/api/runner/work?runnerId=${encodeURIComponent(e)}`,{signal:t,timeoutMs:28e3})).job??null}async function wi(e){await Me("/api/runner/heartbeat",{body:{runnerId:e},method:"POST",timeoutMs:1e4})}async function vi(e,t){return{cancelRequested:(await Me(`/api/runner/jobs/${encodeURIComponent(e)}/events`,{body:{events:t},method:"POST",timeoutMs:15e3})).cancelRequested===!0}}async function Un(e,t,n){await Me(`/api/runner/jobs/${encodeURIComponent(e)}/complete`,{body:{result:n,runnerId:t},method:"POST",timeoutMs:15e3})}async function qt(e,t,n,r=!0){await Me(`/api/runner/jobs/${encodeURIComponent(e)}/fail`,{body:{message:n,retryable:r,runnerId:t},method:"POST",timeoutMs:15e3})}import{mkdirSync as Ac,readFileSync as Oc,writeFileSync as xi}from"fs";import{dirname as Pc,join as _c}from"path";function qn(e){return _c(e,"sessions.json")}function jn(e){try{let t=Oc(qn(e),"utf8"),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return{}}function ki(e,t,n){return t?jn(e)[t]?.[n]??null:null}function Ci(e,t,n,r){if(!(!t||!r))try{let o=qn(e);Ac(Pc(o),{recursive:!0});let i=jn(e);i[t]={...i[t],[n]:r},xi(o,`${JSON.stringify(i,null," ")}
|
|
67
|
+
`,"utf8")}catch{}}function Ii(e,t,n){if(t)try{let r=jn(e);if(!r[t])return;delete r[t][n],xi(qn(e),`${JSON.stringify(r,null," ")}
|
|
68
|
+
`,"utf8")}catch{}}var qc=300,jc=3e4;async function Ri(e){let[t,n]=await Promise.all([Nt(e.claudeBin),Ut(e.codexBin)]);if(!t&&!n)throw new Error("Neither Claude Code nor Codex was found on this machine. Install one and log in, then retry.");t?e.log(`Claude Code detected: ${t.version} (${t.bin})`):e.log("Claude Code not found \u2014 Claude turns will be declined."),n?e.log(`Codex detected: ${n.version} (${n.bin})`):e.log("Codex not found \u2014 Codex turns will be declined.");let r=[...t?["claude-code"]:[],...n?["codex"]:[]],o=`${jt().split(".")[0]}-${Lc().slice(0,8)}`,i=()=>yi({capabilities:["chat_turn","proof"],claudeCodeVersion:t?.version??null,cliVersion:e.version,codexVersion:n?.version??null,hostname:jt(),platform:Nc(),runnerId:o,runtimes:r});for(await i(),e.log(`Registered as ${o} (runtimes: ${r.join(", ")}). Waiting for work\u2026`);!e.signal?.aborted;){let a=null;try{a=await bi(o,e.signal)}catch(s){if(e.signal?.aborted)break;if(s instanceof je&&s.reRegister){e.log("Server asked for re-registration."),await i().catch(()=>{});continue}e.log(`Work poll failed (${s instanceof Error?s.message:"unknown"}); retrying\u2026`),await Vc(e.pollBackoffMs??5e3,e.signal);continue}if(!a){if(e.once)continue;continue}if(e.log(`Claimed ${a.jobType} job ${a.runId}.`),await Mc({claude:t,codex:n,job:a,options:e,runnerId:o}),e.once)break}}async function Mc({claude:e,codex:t,job:n,options:r,runnerId:o}){let i=new AbortController,a=()=>i.abort();r.signal?.addEventListener("abort",a,{once:!0});let s=setInterval(()=>{wi(o).catch(()=>{})},jc),l=[],f=!1,p=async()=>{if(f||l.length===0)return;f=!0;let b=l.splice(0,100);try{let{cancelRequested:$}=await vi(n.runId,b);$&&i.abort()}catch($){$ instanceof je&&$.statusCode===409&&i.abort()}finally{f=!1}},w=setInterval(()=>{p()},qc),v=b=>{l.push(b)};try{if(n.jobType==="runner.proof"){let b=typeof n.input.message=="string"?n.input.message:"proof";v({eventType:"proof.echo",payload:{message:b}}),await Mn(p,l),await Un(n.runId,o,{echo:b}),r.log(`Proof job ${n.runId} completed.`);return}if(n.jobType==="runner.chat_turn"){let b=n.input.runtime==="codex"?"codex":"claude-code",$=b==="codex"?t&&{detection:t,run:hi}:e&&{detection:e,run:ui};if(!$){await qt(n.runId,o,b==="codex"?"Codex is not available on this machine. Install the Codex app or CLI and log in, then retry.":"Claude Code is not available on this machine. Install it and log in, then retry.",!1);return}let x=typeof n.input.chatId=="string"&&n.input.chatId?n.input.chatId:null,k=Uc(r.workspaceRoot,"chats",x??n.runId);await Dc(k,{recursive:!0});let R=Fc(n.input),N=I=>v({eventType:I.eventType,message:I.message??null,payload:I.eventType==="chat.session"?{host:jt(),runtime:b,runtimeVersion:$.detection.version,...I.payload??{}}:I.payload??{}}),E=ki(r.workspaceRoot,x,b),U;try{U=await $.run({bin:$.detection.bin,input:R,onEvent:N,resumeSessionId:E,signal:i.signal,workspace:k})}catch(I){if(!E||i.signal.aborted)throw I;r.log(`Resume of ${b} session failed (${I instanceof Error?I.message:"unknown"}); retrying fresh.`),Ii(r.workspaceRoot,x,b),U=await $.run({bin:$.detection.bin,input:R,onEvent:N,resumeSessionId:null,signal:i.signal,workspace:k})}Ci(r.workspaceRoot,x,b,U.sessionId),v({eventType:"chat.session",payload:{host:jt(),runtime:b,runtimeVersion:$.detection.version,sessionId:U.sessionId,sessionPath:U.sessionPath}}),await Mn(p,l),await Un(n.runId,o,{modelId:U.modelId,runtime:b,runtimeVersion:$.detection.version,sessionId:U.sessionId,sessionPath:U.sessionPath,text:U.text,usage:U.usage??{}}),r.log(`Chat turn ${n.runId} (${b}) completed.`);return}await qt(n.runId,o,`This runner does not support ${n.jobType} jobs. Update the desktop app / CLI.`,!1)}catch(b){let $=b instanceof Error?b.message:"Local runner job crashed.";r.log(`Job ${n.runId} failed: ${$}`),await Mn(p,l).catch(()=>{}),await qt(n.runId,o,$).catch(()=>{})}finally{clearInterval(w),clearInterval(s),r.signal?.removeEventListener("abort",a)}}function Fc(e){let t=Array.isArray(e.messages)?e.messages.map(n=>{if(!n||typeof n!="object")return null;let r=n;return{role:typeof r.role=="string"?r.role:"user",text:typeof r.text=="string"?r.text:""}}).filter(n=>!!n):[];return{effort:typeof e.effort=="string"?e.effort:null,messages:t,modelId:typeof e.modelId=="string"?e.modelId:null,system:typeof e.system=="string"?e.system:null,thinking:typeof e.thinking=="string"?e.thinking:null}}async function Mn(e,t){for(;t.length>0;)await e(),t.length>0&&await new Promise(n=>setTimeout(n,25))}function Vc(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=setTimeout(o,e);function o(){clearTimeout(r),t?.removeEventListener("abort",o),n()}t?.addEventListener("abort",o,{once:!0})})}function Kc(){return Bc(Gc(),`.${u.commands[0]}-runner`,"runs")}var Mt=new Wc("runner").description("Run agent work locally with your own Claude Code / Codex login (desktop lane)");Mt.command("status").description("Check local Claude Code / Codex detection and account auth").action(async()=>{let[e,t]=await Promise.all([Nt(),Ut()]);if(console.log(e?ie.green(`\u2713 Claude Code ${e.version}`):ie.red("\u2717 Claude Code not found on PATH")),console.log(t?ie.green(`\u2713 Codex ${t.version} (${t.bin})`):ie.red("\u2717 Codex not found (PATH or Codex.app)")),!de()){console.log(ie.red(`\u2717 Not logged in. Run '${u.commands[0]} login' first.`)),process.exitCode=2;return}try{let n=await he();console.log(ie.green(`\u2713 Logged in as ${n.user.email}`))}catch(n){console.log(ie.red(`\u2717 Auth check failed: ${n instanceof Error?n.message:"unknown"}`)),process.exitCode=2}});Mt.command("start").description("Start the local runner (register + wait for work)").option("--once","Execute a single job, then exit").option("--workspace <dir>","Workspace root for job scratch directories").option("--claude-bin <path>","Path to the claude binary").option("--codex-bin <path>","Path to the codex binary").action(async e=>{de()||(console.error(ie.red(`Not authenticated. Run '${u.commands[0]} login' first.`)),process.exit(2));let t=new AbortController,n=()=>{console.log(ie.gray(`
|
|
69
|
+
Stopping runner\u2026`)),t.abort()};process.on("SIGINT",n),process.on("SIGTERM",n);try{await Ri({claudeBin:e.claudeBin,codexBin:e.codexBin,log:r=>console.log(ie.gray(`[runner] ${r}`)),once:e.once,signal:t.signal,version:"0.3.19",workspaceRoot:e.workspace??Kc()})}catch(r){console.error(ie.red(r instanceof Error?r.message:String(r))),process.exit(1)}});import q from"chalk";import{Command as Yp}from"commander";import{Command as Fn}from"commander";function Jc(e,t){return[...t,e]}var zc=new Fn("create").description("Start durable ad-set generation").argument("<title>","Ad-set title").requiredOption("--brief <brief>","Campaign brief").option("--hook <text>","Opening hook (repeat)",Jc,[]).option("--style <style>","ugc, clean, cinematic, or testimonial","ugc").option("--branding-id <id>","Branding ID").option("--team-id <id>","Workspace ID").option("--yes","Approve generation").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to approve generation");try{m(await y("createAdSet",{approvalReceipt:"cli:--yes",brandingId:t.brandingId,brief:t.brief,hooks:t.hook.length?t.hook:[t.brief],style:t.style,teamId:t.teamId,title:e}))}catch(n){d(n instanceof Error?n.message:"Generation failed"),process.exit(c.GENERAL_ERROR)}}),Xc=new Fn("status").description("Read ad-set generation status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await T("createAdSet",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),Si=new Fn("ad-set").description("Generate a set of ad creatives (hooks, copy, visuals) from a campaign brief").addCommand(zc).addCommand(Xc);import{randomUUID as Hc}from"crypto";import{Command as Fe}from"commander";function $i(e){return new Fe(e).description(e==="create"?"Create and activate a scheduled agent":"Create a reviewable agent recommendation").argument("<name>","Agent name").requiredOption("--instructions <markdown>","Agent instructions").option("--description <text>","Agent description","").option("--schedule <frequency>","manual, daily, weekdays, weekly, or monthly","weekly").option("--time <hh:mm>","Local run time","09:00").option("--timezone <zone>","IANA timezone","UTC").option("--output <adapter>","Output adapter","digest").option("--team-id <id>","Workspace ID").option("--yes","Approve saving the agent").action(async(t,n)=>{if(!n.yes)return d("Pass --yes to approve this operation");try{m(await y(e==="create"?"createAgent":"recommendAgent",{approvalReceipt:"cli:--yes",description:n.description,instructionsMarkdown:n.instructions,name:t,output:n.output,schedule:n.schedule,scheduleTime:n.time,teamId:n.teamId,timezone:n.timezone}))}catch(r){d(r instanceof Error?r.message:"Agent operation failed"),process.exit(c.GENERAL_ERROR)}})}function Gn(e,t){d(e instanceof Error?e.message:t),process.exit(c.GENERAL_ERROR)}function Ti(e){return`cli:agent-memory:${e}:${Hc()}`}function Yc(e,t){let n=e.indexOf("="),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);return[...t,{name:r.trim(),note:o.trim()}]}function Vn(e,t){return[...t,e]}var Qc=new Fe("show").description("Show what a scheduled agent remembers").argument("<agent-id>","Agent ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await y("getAgentMemory",{agentId:e,teamId:t.teamId}))}catch(n){Gn(n,"Could not read the agent's memory")}}),Zc=new Fe("set").description("Add to or remove from what an agent remembers. Owner or workspace admin only.").argument("<agent-id>","Agent ID").option("--learned <text>","Durable fact to add (repeatable)",Vn,[]).option("--always <text>","Standing instruction to add (repeatable)",Vn,[]).option("--never <text>","Thing it must not do, to add (repeatable)",Vn,[]).option("--track <name=note>","Entity to track, as name=note (repeatable)",Yc,[]).option("--notes <text>","Replace the freeform notes").option("--remove <field>","Remove instead of add: learned, recurringInstructions, negativePreferences, entities, or notes").option("--value <text>","Item to remove; not needed when removing notes").option("--expected-version <n>","Refuse the write unless the stored memory is still at this version").option("--team-id <id>","Workspace ID").action(async(e,t)=>{let n=typeof t.remove=="string";try{m(await y("updateAgentMemory",{agentId:e,entities:t.track.length?t.track:void 0,expectedVersion:t.expectedVersion===void 0?void 0:Number.parseInt(t.expectedVersion,10),learned:t.learned.length?t.learned:void 0,negativePreferences:t.never.length?t.never:void 0,notes:t.notes,operation:n?"remove":"add",recurringInstructions:t.always.length?t.always:void 0,removeField:t.remove,removeValue:t.value,teamId:t.teamId},Ti(n?"remove":"add")))}catch(r){Gn(r,"Could not update the agent's memory")}}),el=new Fe("forget").description("Erase every stored version of an agent's memory. This cannot be undone.").argument("<agent-id>","Agent ID").option("--team-id <id>","Workspace ID").option("--yes","Confirm the erase").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to erase this agent's memory");try{m(await y("forgetAgentMemory",{agentId:e,teamId:t.teamId},Ti("forget")))}catch(n){Gn(n,"Could not erase the agent's memory")}}),tl=new Fe("memory").description("Read, edit, and erase what a scheduled agent remembers").addCommand(Qc).addCommand(Zc).addCommand(el),Ei=new Fe("agent").description("Create scheduled agents and read, edit, or erase what they remember").addCommand($i("create")).addCommand($i("recommend")).addCommand(tl);import{randomUUID as Pi}from"crypto";import{existsSync as ol}from"fs";import{resolve as il}from"path";import ct from"chalk";import{Command as ye}from"commander";import al from"ora";import{mkdir as nl,writeFile as Ai}from"fs/promises";import{dirname as rl}from"path";async function H(e,t){if(await nl(rl(t),{recursive:!0}),e.startsWith("data:")){let o=e.match(/^data:[^;]+;base64,(.+)$/);if(!o)throw new Error("Invalid data URL format");let i=Buffer.from(o[1],"base64");if(i.length===0)throw new Error("Downloaded media was empty");await Ai(t,i);return}let n=await fetch(e);if(!n.ok)throw new Error(`Failed to download media: ${n.status}`);let r=Buffer.from(await n.arrayBuffer());if(r.length===0)throw new Error("Downloaded media was empty");await Ai(t,r)}var sl=15e3,dl=40,Oi=3;async function _i(e,t){if(e?.length){if(e.length>Oi)throw new Error(`A presenter Look accepts at most ${Oi} reference images`);return Promise.all(e.map(async(n,r)=>{if(ol(n))return{url:(await ue(il(n),{idempotencyKey:`${t}:reference:${r+1}`})).url};let o;try{o=new URL(n)}catch(i){throw new Error(`Reference image ${r+1} must be an existing local file or an HTTP(S) URL.`,{cause:i})}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`Reference image ${r+1} must use an HTTP(S) URL.`);return{url:o.toString()}}))}}function Bn(e,t){if(t==="json"){m(e);return}if(t==="quiet"){console.log(e.videoUrl??e.requestId);return}g(`Request ID: ${e.requestId}`),g(`Status: ${e.status}`),e.durationSec!=null&&g(`Duration: ${e.durationSec}s`),e.videoUrl&&C(`Video URL: ${e.videoUrl}`),e.error&&d(`Error: ${e.error}`)}var cl=new ye("options").description("List available presenter avatars and voices").option("--language <language>","Filter voices by language").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{try{let t=await Ro(e.language);if(e.format==="json"){m(t);return}let n=t.personal??[];if(e.format==="quiet"){for(let r of n)console.log(r.id);for(let r of t.avatars)console.log(r.id);for(let r of t.voices)console.log(r.id);return}if(n.length>0){g("Your presenters:");for(let r of n)console.log(` ${r.id} ${r.name}`)}g("Avatars:");for(let r of t.avatars){let o=r.renderTiers?.length?` [${r.renderTiers.join(", ")}]`:"";console.log(` ${r.id} ${r.name}${o}`)}g("Voices:");for(let r of t.voices)console.log(` ${r.id} ${r.name}${r.language?` (${r.language})`:""}`)}catch(t){d(t instanceof Error?t.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),ll=new ye("generate").description("Generate a reusable presenter clip").option("--avatar-id <id>","Avatar id from 'avatar options'; sandbox runs use the host presenter policy").option("--audio-url <url>","Public narration audio URL for avatar lip sync").option("--voice-id <id>","Voice id from 'avatar options'").option("--script <text>","Exact words for the presenter to speak").requiredOption("-o, --output <path>","Local output path").option("--aspect <aspect>","Aspect: 1:1, 9:16, 16:9","9:16").option("--duration <seconds>","Maximum requested duration (1-300)").option("--transparent","Render a transparent-background WebM presenter clip").option("--background-color <hex>","Solid presenter background color, for example #0F172A").option("--background-image-url <url>","Public image URL used as the presenter background").option("--fit <mode>","Background image fit: contain or cover").option("--output-format <container>","Container: mp4 (default) or webm \u2014 webm renders a transparent-background clip (single scene) for compositing").option("--render-tier <tier>","Render cost/quality: basic, standard, premium","basic").option("--title <title>","Clip title","Presenter clip").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.transparent?"webm":e.outputFormat;!!e.audioUrl==!!e.script&&(d("Provide exactly one avatar speech input: --audio-url or --script"),process.exit(c.INVALID_INPUT)),["1:1","9:16","16:9"].includes(e.aspect)||(d("Aspect must be one of 1:1, 9:16, or 16:9"),process.exit(c.INVALID_INPUT)),e.outputFormat!==void 0&&!["mp4","webm"].includes(e.outputFormat)&&(d("Output format must be mp4 or webm"),process.exit(c.INVALID_INPUT)),e.backgroundColor!==void 0&&!/^#[0-9a-fA-F]{6}$/.test(e.backgroundColor)&&(d("Background color must be a six-digit hex value"),process.exit(c.INVALID_INPUT)),e.backgroundColor&&e.backgroundImageUrl&&(d("Provide only one presenter background"),process.exit(c.INVALID_INPUT)),e.fit!==void 0&&!["contain","cover"].includes(e.fit)&&(d("Fit must be contain or cover"),process.exit(c.INVALID_INPUT)),e.fit&&!e.backgroundImageUrl&&(d("Fit requires --background-image-url"),process.exit(c.INVALID_INPUT)),e.transparent&&e.outputFormat==="mp4"&&(d("--transparent cannot be combined with --output-format mp4"),process.exit(c.INVALID_INPUT)),t==="webm"&&(e.backgroundColor||e.backgroundImageUrl)&&(d("Transparent WebM output cannot be combined with a background"),process.exit(c.INVALID_INPUT)),["basic","standard","premium"].includes(e.renderTier)||(d("Render tier must be basic, standard, or premium"),process.exit(c.INVALID_INPUT));let n=e.duration?Number.parseInt(e.duration,10):void 0;n!==void 0&&(!Number.isFinite(n)||n<1||n>300)&&(d("Duration must be between 1 and 300 seconds"),process.exit(c.INVALID_INPUT));let r=e.format==="human"?al("Generating presenter clip...").start():null;try{let o=e.audioUrl?{audioUrl:e.audioUrl}:{script:e.script??"",...e.voiceId?{voiceId:e.voiceId}:{}},i=await So({...o,aspect:e.aspect,...e.avatarId?{avatarId:e.avatarId}:{},...e.backgroundColor?{backgroundHex:e.backgroundColor}:{},...e.backgroundImageUrl?{backgroundImageUrl:e.backgroundImageUrl}:{},...n!==void 0?{durationSec:n}:{},...e.fit?{fit:e.fit}:{},...t?{outputFormat:t}:{},renderTier:e.renderTier,title:e.title});if(!e.wait){r?.stop(),Bn(i,e.format);return}let a=await Z(()=>Tn(i.requestId),dl,sl);if(a.status==="failed")throw new Error(a.error||"Presenter generation failed");if(!a.videoUrl)throw new Error("Presenter generation completed without a video URL");r&&(r.text="Downloading presenter clip..."),await H(a.videoUrl,e.output),r?.stop(),Bn(a,e.format),e.format==="human"&&C(`Saved to: ${e.output}`)}catch(o){r?.stop(),d(o instanceof Error?o.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),ul=new ye("status").description("Check a presenter clip generation request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{Bn(await Tn(e),t.format)}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),ml=new ye("generate").description("Generate another look for an existing personal presenter").argument("<base-profile-id>","Base personal presenter id (pp_*)").requiredOption("--name <name>","Look name").requiredOption("--description <description>","Short look description").requiredOption("--prompt <prompt>","Exact appearance generation prompt").requiredOption("--look-id <id>","Stable template/look id").option("--reference-image <path-or-url...>","Up to three local images or URLs for location, outfit, or style guidance").option("--idempotency-key <key>","Stable retry key for this look request").action(async(e,t)=>{try{let n=t.idempotencyKey??Pi(),r=await _i(t.referenceImage,n),o=await y("generatePresenterLook",{baseProfileId:e,description:t.description,id:t.lookId,prompt:t.prompt,...r?{referenceImages:r}:{},title:t.name},n);m(o)}catch(n){d(n instanceof Error?n.message:"Look generation failed"),process.exit(c.GENERAL_ERROR)}}),pl=new ye("status").description("Read presenter look generation status").argument("<run-id>","Durable run ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("generatePresenterLook",e);if(t.format==="json")return m(n);if(t.format==="quiet")return console.log(n.status);g(`Run ID: ${e}`),g(`Status: ${n.status}`),n.error?.message&&d(n.error.message)}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),gl=new ye("revise").description("Create a new Look by editing an existing presenter Look").argument("<look-id>","Ready presenter Look id (pp_*)").requiredOption("--instruction <instruction>","What to add, remove, or change").option("--reference-image <path-or-url...>","Up to three local images or URLs for location, outfit, or style guidance").option("--idempotency-key <key>","Stable retry key for this revision").action(async(e,t)=>{try{let n=t.idempotencyKey??Pi(),r=await _i(t.referenceImage,n),o=await y("revisePresenterLook",{instruction:t.instruction,...r?{referenceImages:r}:{},sourceLookId:e},n);m(o)}catch(n){d(n instanceof Error?n.message:"Look revision failed"),process.exit(c.GENERAL_ERROR)}}),fl=new ye("revision-status").description("Read presenter Look revision status").argument("<run-id>","Durable run ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("revisePresenterLook",e);if(t.format==="json")return m(n);if(t.format==="quiet")return console.log(n.status);g(`Run ID: ${e}`),g(`Status: ${n.status}`),n.error?.message&&d(n.error.message)}catch(n){d(n instanceof Error?n.message:"Revision status failed"),process.exit(c.GENERAL_ERROR)}}),hl=new ye("look").description("Manage looks under an existing personal presenter").addCommand(ml).addCommand(gl).addCommand(fl).addCommand(pl),Wn=new ye("avatar").description("Generate presenter clips and looks; avatar options lists the voices and looks used by presentation video presenter and cast preset").addCommand(cl).addCommand(ll).addCommand(hl).addCommand(ul);Wn.addHelpText("after",`
|
|
70
|
+
${ct.bold("Examples:")}
|
|
71
|
+
${ct.gray("# Discover the presenter avatars and voices you can use")}
|
|
71
72
|
$ ${u.commands[0]} avatar options
|
|
72
73
|
|
|
73
|
-
${
|
|
74
|
-
${
|
|
74
|
+
${ct.bold("See also:")}
|
|
75
|
+
${ct.gray("# Save a presenter + backdrop + voice combination under a name")}
|
|
75
76
|
$ ${u.commands[0]} cast preset --help
|
|
76
77
|
|
|
77
|
-
${
|
|
78
|
+
${ct.gray("# Apply an avatar, look, or preset to one presentation-video scene")}
|
|
78
79
|
$ ${u.commands[0]} presentation video presenter <project-id>
|
|
79
|
-
`);import{writeFile as
|
|
80
|
-
`);for(let o of r){let i=o.primaryColor?`${
|
|
81
|
-
${
|
|
82
|
-
${
|
|
80
|
+
`);import{writeFile as ji}from"fs/promises";import J from"chalk";import{Command as ne}from"commander";import Tl from"ora";import{createHash as yl}from"crypto";import{existsSync as bl}from"fs";import{basename as wl}from"path";import{Command as Li}from"commander";import vl from"ora";var Di=new Li("logo").description("Brand logo files").addCommand(new Li("set").description("Set a brand's logo, dark variant, or favicon").argument("[brand-id]","Brand ID (defaults to this workspace's default brand)").requiredOption("--file <path>","Local image file to upload and use").option("--variant <variant>","primary | dark | favicon. 'dark' is the reversed lock-up for dark backgrounds","primary").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await A();let n=t.variant??"primary";["primary","dark","favicon"].includes(n)||(d(`--variant must be primary, dark, or favicon (got "${n}")`),process.exit(c.INVALID_INPUT)),bl(t.file)||(d(`File not found: ${t.file}`),process.exit(c.INVALID_INPUT));let r=vl({text:`Uploading ${wl(t.file)}...`,stream:process.stdout}).start(),o;try{o=(await ue(t.file)).url,r.succeed("Uploaded")}catch(i){r.fail("Upload failed"),d(i instanceof Error?i.message:String(i)),process.exit(c.GENERAL_ERROR)}try{m(await y("setBrandLogo",{brandId:e,fileUrl:o,teamId:t.teamId,variant:n},yl("sha256").update(`setBrandLogo:${e??"default"}:${n}:${o}`).digest("hex").slice(0,32)))}catch(i){d(i instanceof Error?i.message:"Write failed"),process.exit(c.GENERAL_ERROR)}}));import{readFile as xl}from"fs/promises";import{randomUUID as kl}from"crypto";import{Command as Ni}from"commander";var Cl=["color.primary","color.background","color.text","color.secondary","color.accent","color.surface","color.link","typography.primary","typography.secondary","typography.h1","typography.h2","typography.h3","typography.h4","typography.h5","typography.h6","typography.paragraph","typography.button","typography.small","typography.label","typography.caption","asset.logo","asset.logo.dark","asset.favicon"];function Il(e){let t=e.split(".").filter(Boolean);for(let n=t.length;n>=2;n--){let r=t.slice(0,n).join(".");if(Cl.includes(r))return{fieldPath:t.slice(n),nodeKey:r}}return{fieldPath:t.slice(2),nodeKey:t.slice(0,2).join(".")}}function Rl(e){let t={};for(let n of e){let r=n.indexOf("=");if(r<=0)throw new Error(`"${n}" is not a token assignment. Use key=value, e.g. color.primary=#114b97`);let o=n.slice(0,r).trim(),i=n.slice(r+1);if(o.split(".").filter(Boolean).length<2)throw new Error(`"${o}" is not a brand token key. Expected something like color.primary or typography.h1.size`);let{fieldPath:s,nodeKey:l}=Il(o),f=Sl(i);if(s.length===0){t[l]=f;continue}let p=t[l],w=p&&typeof p=="object"&&!Array.isArray(p)?p:{},v=w;for(let b of s.slice(0,-1)){let $=v[b],x=$&&typeof $=="object"&&!Array.isArray($)?$:{};v[b]=x,v=x}v[s[s.length-1]]=f,t[l]=w}return t}function Sl(e){return e==="true"?!0:e==="false"?!1:/^-?\d+(?:\.\d+)?$/.test(e)?Number(e):e}function $l(e,t){return e===void 0?{assignments:[...t]}:e.includes("=")?{assignments:[e,...t]}:{assignments:[...t],brandId:e}}var Ui=new Ni("profile").description("Read a brand's design tokens, the keys it is missing, or its design.md").argument("[brand-id]","Brand ID (defaults to this workspace's brand)").option("--format <format>","tokens (default) or md").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{let n=await y("getBrandProfile",{brandId:e,format:t.format,teamId:t.teamId});if(t.format==="md"&&typeof n.designMd=="string"){console.log(n.designMd);return}m(n)}catch(n){d(n instanceof Error?n.message:"Profile read failed"),process.exit(c.GENERAL_ERROR)}}),qi=new Ni("set").description("Write brand design tokens (key=value pairs or a design.md)").argument("[brand-id]","Brand ID (defaults to this workspace's brand)").argument("[tokens...]","Token assignments, e.g. color.primary=#114b97 typography.h1.size=32px").option("--design-md <path>","Apply a whole design.md file instead").option("--no-publish","Stage the change without publishing a new active brand version").option("--team-id <id>","Workspace ID").option("--yes","Confirm writing brand data").action(async(e,t,n)=>{n.yes||(d("Pass --yes to confirm writing brand tokens."),process.exit(c.INVALID_INPUT));let{assignments:r,brandId:o}=$l(e,t),i;try{i=r.length>0?Rl(r):void 0}catch(s){d(s instanceof Error?s.message:"Invalid token pair"),process.exit(c.INVALID_INPUT)}let a;if(n.designMd)try{a=await xl(n.designMd,"utf8")}catch(s){d(`Could not read ${n.designMd}: ${s instanceof Error?s.message:String(s)}`),process.exit(c.INVALID_INPUT)}!i&&!a&&(d("Nothing to write. Pass token assignments (color.primary=#114b97) or --design-md <file>."),process.exit(c.INVALID_INPUT));try{m(await y("updateBrandTokens",{brandId:o,designMd:a,publish:n.publish===!1?!1:void 0,teamId:n.teamId,tokens:i},kl()))}catch(s){d(s instanceof Error?s.message:"Write failed"),process.exit(c.GENERAL_ERROR)}});var Mi=new ne("branding").description("Manage brand profiles, design tokens, logos, competitors, and social handles").addCommand(Ui).addCommand(qi).addCommand(new ne("list").description("List brand profiles").option("-f, --format <format>","Output format (table, json)","table").action(async e=>{await A();try{let t=await In();if(t.brandings.length===0){e.format==="json"?console.log(JSON.stringify([])):(g("No brand profiles found"),console.log(),console.log(J.gray(`Create one with: ${u.commands[0]} branding extract <url>`)));return}e.format==="json"?console.log(JSON.stringify(t.brandings,null,2)):console.log(jr(t.brandings))}catch(t){d(t instanceof Error?t.message:String(t)),process.exit(t.exitCode??1)}})).addCommand(new ne("get").description("Get brand profile details").argument("<id>","Brand profile ID").option("-f, --format <format>","Output format (summary, json)","summary").option("-o, --output <path>","Save JSON to file").action(async(e,t)=>{await A();try{let n=await lo(e);if(t.output){await ji(t.output,JSON.stringify(n,null,2)),C(`Brand profile saved to ${t.output}`);return}if(t.format==="json")console.log(JSON.stringify(n,null,2));else{if(se("Brand Profile"),console.log(),S("ID",n.id),S("Name",n.name),S("Source URL",n.sourceUrl??J.gray("None")),S("Default",n.isDefault?J.green("Yes"):"No"),n.createdAt&&S("Created",new Date(n.createdAt).toLocaleString()),console.log(),n.primaryColor||n.colors.length>0){if(console.log(J.bold(" Colors")),n.primaryColor){let o=J.bgHex(n.primaryColor)(" ");console.log(` Primary: ${o} ${n.primaryColor}`)}if(n.colors.length>0){console.log(" Palette:");for(let o of n.colors.slice(0,10)){let i=J.bgHex(o.hex)(" "),a=o.role?J.gray(` (${o.role})`):"";console.log(` ${i} ${o.hex}${a}`)}}console.log()}n.logoUrl&&(console.log(J.bold(" Logo")),console.log(` ${n.logoUrl}`),console.log());let r=n.typography;r&&Object.keys(r).length>0&&(console.log(J.bold(" Typography")),(r.primary||r.headings)&&console.log(` Headings: ${r.primary||r.headings||"-"}`),(r.secondary||r.body)&&console.log(` Body: ${r.secondary||r.body||"-"}`),console.log()),(n.confidence||n.extractionMethod)&&(console.log(J.bold(" Extraction")),n.confidence&&console.log(` Confidence: ${Math.round(n.confidence*100)}%`),n.extractionMethod&&console.log(` Method: ${n.extractionMethod}`),console.log()),console.log(J.gray(" Use --format json for full details")),console.log()}}catch(n){d(n instanceof Error?n.message:String(n)),process.exit(n.exitCode??1)}})).addCommand(new ne("find").description("Find existing brand profile by name or URL").argument("<query>","Brand name or website URL to search for").action(async e=>{await A();try{let t=await In(),n=e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,""),r=t.brandings.filter(o=>{let i=(o.name||"").toLowerCase(),a=(o.sourceUrl||"").toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"");return i.includes(n)||a.includes(n)||i.length>0&&n.includes(i)||a.length>0&&n.includes(a)});if(r.length===0){g(`No brand profiles matching "${e}"`),console.log(J.gray(` Extract one with: ${u.commands[0]} branding extract <url>`));return}console.log(`Found ${r.length} brand${r.length>1?"s":""}:
|
|
81
|
+
`);for(let o of r){let i=o.primaryColor?`${J.bgHex(o.primaryColor)(" ")} ${o.primaryColor}`:"";console.log(` ${J.bold(o.name)} ${J.gray(o.id)}`),o.sourceUrl&&console.log(` ${J.gray(o.sourceUrl)}`),i&&console.log(` ${i}`),console.log()}console.log(J.gray(` Export with: ${u.commands[0]} branding get <id> -o branding.json`))}catch(t){d(t instanceof Error?t.message:String(t)),process.exit(t.exitCode??1)}})).addCommand(new ne("extract").description("Extract brand profile from a website").argument("<url>","Website URL to extract branding from").option("--team-id <id>","Team ID").option("--yes","Confirm starting a paid/external extraction").option("--no-save","Extract without saving").option("-o, --output <path>","Save JSON to file").action(async(e,t)=>{await A(),t.yes||(d("Pass --yes to confirm brand extraction."),process.exit(c.INVALID_INPUT));try{new URL(e.startsWith("http")?e:`https://${e}`)}catch{d("Invalid URL format"),process.exit(6)}let n=e.startsWith("http")?e:`https://${e}`,r=t.teamId??kt(),o=Tl({text:`Extracting branding from ${n}...`,stream:process.stdout}).start();try{let i=await uo(n,r,"cli:--yes");o.succeed("Brand extraction started");let a=JSON.stringify(i,null,2);t.output?(await ji(t.output,a),C(`Brand profile saved to ${t.output}`)):console.log(a),g(`Check progress with: ${u.commands[0]} branding status ${i.runId}`),console.log()}catch(i){o.fail("Extraction failed"),d(i instanceof Error?i.message:String(i)),process.exit(i.exitCode??1)}})).addCommand(new ne("status").description("Check a brand extraction run").argument("<run-id>","Run ID returned by branding extract").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await T("extractBranding",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}})).addCommand(new ne("set-default").description("Set a brand profile as default").argument("<id>","Brand profile ID").action(async e=>{await A(),g(`To set brand ${e} as default, use the web dashboard.`),console.log(),console.log(J.gray("API support for setting default brand is coming soon."))})).addCommand(new ne("competitor").description("Brand competitor commands").addCommand(new ne("list").description("List competitors for a brand").option("--branding-id <id>","Brand ID").option("--team-id <id>","Workspace ID").action(async e=>{try{console.log(JSON.stringify(await y("getBrandCompetitors",{brandingId:e.brandingId,teamId:e.teamId}),null,2))}catch(t){d(t instanceof Error?t.message:"Lookup failed"),process.exit(1)}})).addCommand(new ne("add").description("Add or update a brand competitor").argument("<name>","Competitor name").option("--branding-id <id>","Brand ID").option("--team-id <id>","Workspace ID").option("--website <url>","Competitor website").option("--x-handle <handle>","Competitor X handle").option("--yes","Confirm writing brand data").action(async(e,t)=>{t.yes||(d("Pass --yes to confirm adding a competitor."),process.exit(c.INVALID_INPUT));try{m(await y("addCompetitor",{approvalReceipt:"cli:--yes",brandingId:t.brandingId,name:e,teamId:t.teamId,website:t.website,xHandle:t.xHandle}))}catch(n){d(n instanceof Error?n.message:"Write failed"),process.exit(c.GENERAL_ERROR)}}))).addCommand(Di).addCommand(new ne("social").description("Brand social handle commands").addCommand(new ne("add").description("Add or update a brand social handle").argument("<platform>","Social platform").argument("<handle>","Account handle").option("--branding-id <id>","Brand ID").option("--team-id <id>","Workspace ID").option("--yes","Confirm writing brand data").action(async(e,t,n)=>{n.yes||(d("Pass --yes to confirm adding a social handle."),process.exit(c.INVALID_INPUT));try{m(await y("addBrandSocialHandle",{approvalReceipt:"cli:--yes",brandingId:n.brandingId,handle:t,platform:e,teamId:n.teamId}))}catch(r){d(r instanceof Error?r.message:"Write failed"),process.exit(c.GENERAL_ERROR)}})));import lt from"chalk";import{Command as Ve}from"commander";function El(e){switch(e.background){case"color":{if(!e.backgroundColor)throw new Error("--background color needs --background-color <hex>, e.g. #1d4ed8");return{hex:e.backgroundColor,kind:"color"}}case"image":{if(!e.backgroundImage)throw new Error("--background image needs --background-image <url>");return{fit:e.fit,kind:"image",url:e.backgroundImage}}default:return{kind:e.background}}}function Fi(e,t){return{background:El(t),name:e,presenterProfileId:t.presenter,...t.voiceId?{voiceId:t.voiceId}:{}}}function Ft(e,t){if(t==="json"){m(e);return}if(t==="quiet"){console.log(e.id);return}C(`${e.name} (${e.id})`),g(` Presenter: ${e.presenterProfileId}`),g(` Backdrop: ${Al(e.background)}`),e.voiceId&&g(` Voice: ${e.voiceId}`)}function Al(e){switch(e.kind){case"color":return`color ${e.hex}`;case"image":return`image ${e.url} (${e.fit})`;default:return e.kind}}function Vi(e){return e.requiredOption("--presenter <profileId>",`Trained personal presenter id (pp_*), from \`${u.commands[0]} avatar options\``).option("--background <kind>","Backdrop: original, transparent, color, or image","original").option("--background-color <hex>","Backdrop color, e.g. #1d4ed8").option("--background-image <url>","Backdrop image URL").option("--fit <fit>","How an image backdrop fills the frame","cover").option("--voice-id <voiceId>","Workspace voice to save with this preset").option("-f, --format <format>","Output format: human, json, quiet","human")}var Ol=new Ve("list").description("List saved cast presets you can use").option("--cast-member-id <castMemberId>","Only this person's presets").option("--branding-id <brandingId>","Narrow to one brand").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{try{let t=await _o({...e.brandingId?{brandingId:e.brandingId}:{},...e.castMemberId?{castMemberId:e.castMemberId}:{}});if(e.format==="json"){m(t);return}if(e.format==="quiet"){for(let n of t.presets)console.log(n.id);return}if(t.presets.length===0){g("No presets saved yet.");return}for(let n of t.presets)Ft(n,"human")}catch(t){d(t instanceof Error?t.message:String(t)),process.exit(c.API_ERROR)}}),Pl=Vi(new Ve("create").description("Save one way a cast member appears").argument("<name>",'What to call this preset, e.g. "In the cafe"').requiredOption("--cast-member-id <castMemberId>","The person this preset is a way of showing")).action(async(e,t)=>{try{let n=await Lo({castMemberId:t.castMemberId,...Fi(e,t)});Ft(n.preset,t.format)}catch(n){d(n instanceof Error?n.message:String(n)),process.exit(c.API_ERROR)}}),_l=Vi(new Ve("update").description("Change a saved preset (sends the complete preset)").argument("<presetId>","The preset to change").requiredOption("--name <name>","What to call it")).action(async(e,t)=>{try{let n=await Do({presetId:e,...Fi(t.name,t)});Ft(n.preset,t.format)}catch(n){d(n instanceof Error?n.message:String(n)),process.exit(c.API_ERROR)}}),Ll=new Ve("delete").description("Retire a saved preset. Existing videos keep working.").argument("<presetId>","The preset to retire").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await No(e);if(t.format==="human"){C(`Retired "${n.preset.name}".`);return}Ft(n.preset,t.format)}catch(n){d(n instanceof Error?n.message:String(n)),process.exit(c.API_ERROR)}}),Dl=new Ve("preset").description("Saved ways a cast member appears").addCommand(Ol).addCommand(Pl).addCommand(_l).addCommand(Ll),Kn=new Ve("cast").description("The faces and voices your videos can use").addCommand(Dl);Kn.addHelpText("after",`
|
|
82
|
+
${lt.bold("Examples:")}
|
|
83
|
+
${lt.gray("# List the saved presenter/backdrop/voice combinations")}
|
|
83
84
|
$ ${u.commands[0]} cast preset list
|
|
84
85
|
|
|
85
|
-
${
|
|
86
|
-
${
|
|
86
|
+
${lt.bold("See also:")}
|
|
87
|
+
${lt.gray("# The presenter avatars, looks, and voices a preset is built from")}
|
|
87
88
|
$ ${u.commands[0]} avatar options
|
|
88
89
|
|
|
89
|
-
${
|
|
90
|
+
${lt.gray("# Use a preset on one presentation-video scene")}
|
|
90
91
|
$ ${u.commands[0]} presentation video presenter <project-id>
|
|
91
|
-
`);import{readFile as
|
|
92
|
-
${
|
|
93
|
-
${
|
|
92
|
+
`);import{readFile as Nl}from"fs/promises";import ut from"chalk";import{Command as Gi}from"commander";var Ul=new Gi("extract").description("Extract normalized text from a URL or local file").argument("<source>","URL, encoded source, or local file path").option("--team-id <id>","Workspace ID").option("--mime-type <type>","Source MIME type").option("--max-length <count>","Maximum output characters","30000").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=e,r;e.includes("://")||(n=await Nl(e,"utf8"),r=e);let o=await y("extractContent",{filename:r,maxLength:Number.parseInt(t.maxLength,10),mimeType:t.mimeType,source:n,teamId:t.teamId});t.format!=="quiet"&&m(o)}catch(n){d(n instanceof Error?n.message:"Extraction failed"),process.exit(c.GENERAL_ERROR)}}),Jn=new Gi("content").description("Extract normalized text from a URL, a local file, or an encoded document").addCommand(Ul);Jn.addHelpText("after",`
|
|
93
|
+
${ut.bold("Examples:")}
|
|
94
|
+
${ut.gray("# Normalized text from a local document")}
|
|
94
95
|
$ ${u.commands[0]} content extract ./paper.pdf
|
|
95
96
|
|
|
96
|
-
${
|
|
97
|
-
${
|
|
97
|
+
${ut.bold("See also:")}
|
|
98
|
+
${ut.gray("# Web pages, with page metadata and cost reporting")}
|
|
98
99
|
$ ${u.commands[0]} scrape https://example.com/post
|
|
99
100
|
|
|
100
|
-
${
|
|
101
|
+
${ut.gray("# Spoken words out of audio or video")}
|
|
101
102
|
$ ${u.commands[0]} transcript --help
|
|
102
|
-
`);import
|
|
103
|
-
Uploading ${t.file.length} file(s)...`));try{x=await
|
|
104
|
-
`),process.stdout.write(r.content)}catch(n){Re(n,"Could not read the document")}}),ql=new he("update").description("Edit a document under an optimistic lock").argument("<document-id>","Document id").requiredOption("--expected-version <n>","The version you last read; the edit is rejected if it has moved on").option("--team-id <id>","Workspace ID").option("--content <text>","New body: literal text, @<path> to read a file, or '-' for stdin").option("--title <text>","New title").option("--summary <text>","New Library-card summary").option("--change-summary <text>","What changed, recorded on the version").action(async(e,t)=>{try{let n=t.content!==void 0;p(await y("updateDocument",{changeSummary:t.changeSummary,content:n?await Ni(t):void 0,documentId:e,expectedVersion:Number(t.expectedVersion),summary:t.summary,teamId:t.teamId,title:t.title},Nt("update")))}catch(n){Re(n,"Could not update the document")}}),Ml=new he("delete").description("Remove a document from the Library").argument("<document-id>","Document id").option("--team-id <id>","Workspace ID").option("--yes","Skip the confirmation prompt").action(async(e,t)=>{try{!t.yes&&process.stdin.isTTY&&(d("Refusing to delete without confirmation. Re-run with --yes to remove this document."),process.exit(c.GENERAL_ERROR)),p(await y("deleteDocument",{documentId:e,teamId:t.teamId},Nt("delete")))}catch(n){Re(n,"Could not delete the document")}}),Fl=new he("versions").description("List a document's version history").argument("<document-id>","Document id").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await y("listDocumentVersions",{documentId:e,teamId:t.teamId}))}catch(n){Re(n,"Could not list versions")}}),Vl=new he("restore").description("Restore an earlier version by appending it as the current one").argument("<document-id>","Document id").requiredOption("--version-number <n>","The historical version to restore").requiredOption("--expected-version <n>","The version you last read; the restore is rejected if it has moved on").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await y("restoreDocumentVersion",{documentId:e,expectedVersion:Number(t.expectedVersion),teamId:t.teamId,versionNumber:Number(t.versionNumber)},Nt("restore")))}catch(n){Re(n,"Could not restore the version")}}),Ui=new he("document").description("Create, read and edit Library documents").addCommand(Dl).addCommand(Nl).addCommand(Ul).addCommand(ql).addCommand(Ml).addCommand(Fl).addCommand(Vl);import{Command as jl}from"commander";import Ut from"chalk";var qi=new jl("get").description("Get presentation details").argument("<slug>","Presentation slug (e.g., my-presentation-v1-abc123)").option("-f, --format <format>","Output format (summary, full, json)","summary").option("--include <fields>","Fields to include (comma-separated: slides,styling)").option("-l, --language <lang>","Language for view URL","en").action(async(e,t)=>{await A();try{let n=await ge(e);if(t.format==="json"){console.log(JSON.stringify(n,null,2));return}let r=Pe(n.slug,t.language);re("Presentation Details"),console.log(),S("Slug",n.slug),S("Title",n.title||"Untitled"),S("Description",n.description||Ut.gray("None")),S("Slides",String(n.numberOfSlides||"-")),S("Mode",n.mode||"-"),S("Created",pn(n.createdAt)),n.updatedAt&&S("Updated",pn(n.updatedAt)),console.log(),r!=="N/A"&&console.log(Ut.bold(" Open: ")+Ut.cyan.underline(r)),console.log(),t.format==="full"&&t.include?.includes("slides")&&(console.log(Ut.gray("(Full slide content available in JSON format)")),console.log())}catch(n){d(n instanceof Error?n.message:String(n)),process.exit(n.exitCode??1)}});import{Command as Mt}from"commander";import Gl from"ora";function ne(e,t){let n=e instanceof Error?e.message:"Unknown error";return!t||n.includes(t)?n:`${n} Request ID: ${t}. Resume with the matching status command; do not start a duplicate run.`}function Bl(e){let t=e?.trim().toLowerCase();if(!(!t||t==="any"||t==="all"))return t==="web"||t==="stock"?[t]:void 0}function Wl(e){let t=e.assetType??"image";if(t!=="image"&&t!=="icon")throw new Error("Asset type must be image or icon");let n;if(e.maxResults&&(n=Number.parseInt(e.maxResults,10),Number.isNaN(n)||n<1))throw new Error("Max results must be a positive number");return{query:t==="icon"?`${e.query.trim()} transparent icon isolated symbol`:e.query.trim(),options:{maxResults:n||10,size:e.size,safeSearch:e.safeSearch,assetType:t,sources:Bl(e.source),transparentBackground:t==="icon"}}}function Kl(e){let t=e.url||e.imageUrl;if(!t)throw new Error("Image search returned a result without a URL");return t}function Jl(e){return e.transparent??e.isTransparent??e.metadata?.transparent??e.metadata?.isTransparent}function zl(e){let t=[],n=e.reduce((r,o)=>Math.max(r,o.length),0);for(let r=0;r<n;r+=1)for(let o of e){let i=o[r];i!==void 0&&t.push(i)}return t}function Xl(e,t){let n=e.data.results.map(r=>r.results.map(o=>{let i=o,a=Jl(i);if(t==="icon"&&a!==!0)throw new Error("Icon search returned a result without a verified transparent background");return{...i,url:Kl(i),provider:r.providerName,assetType:t,...a!==void 0?{transparent:a}:{}}}));return zl(n)}function Hl(e){return e.error||e.status==="failed"||e.status==="errored"||e.status==="cancelled"?"failed":e.done||e.status==="completed"?"completed":e.status==="in_progress"?"processing":"pending"}function qt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Yl(e){return{requestId:e.runId,status:Hl(e),...e.entity?.url?{url:e.entity.url}:{},...e.error?.message?{error:e.error.message}:{},...qt(e.output?.width)!==void 0?{width:qt(e.output?.width)}:{},...qt(e.output?.height)!==void 0?{height:qt(e.output?.height)}:{}}}async function Mi(e,t){return Yl(await T("createImage",e,t))}function Gn(e,t){if(t==="json"){p(e);return}if(t==="quiet"){console.log(e.output??e.url??e.requestId);return}f(`Request ID: ${e.requestId}`),f(`Status: ${e.status}`),e.url&&C(`Image URL: ${e.url}`),e.output&&C(`Saved to: ${e.output}`),e.error&&d(`Error: ${e.error}`)}var Ql=new Mt("search").description("Search images across the web and licensed stock").requiredOption("-q, --query <query>","Search query").option("-n, --max-results <number>","Maximum number of results (default: 10)").option("-s, --size <size>","Image size: small, medium, large, any","large").option("--asset-type <type>","Asset intent: image or transparent icon","image").option("--source <source>","Catalog: web, stock, or any (default: any)","any").option("--safe-search","Enable safe search (default: true)",!0).option("--no-safe-search","Disable safe search").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.format,n=t==="human"?Gl("Searching for images...").start():null,r;try{r=Wl(e)}catch(o){n?.stop(),d(o instanceof Error?o.message:"Invalid image search request"),process.exit(c.INVALID_INPUT);return}try{let o=await lo(r);n?.stop(),o.success||(d("Search failed"),process.exit(c.GENERAL_ERROR));let i=r.options?.assetType??"image",a=Xl(o,i);if(t==="json"){p({success:!0,query:e.query,assetType:i,totalResults:a.length,images:a});return}if(t==="quiet"){for(let s of a)console.log(s.url);return}if(a.length===0){f("No images found");return}C(`Found ${a.length} images for "${e.query}"`),console.log();for(let s=0;s<a.length;s++){let l=a[s];console.log(`[${s+1}] ${l.title||"Untitled"}`),console.log(` URL: ${l.url}`),console.log(` Size: ${l.width}x${l.height}`),l.author&&console.log(` Author: ${l.author}`),console.log(` Provider: ${l.provider}`),console.log()}f(`Total cost: $${o.data.totalCost.toFixed(4)}`)}catch(o){n?.stop(),d(o instanceof Error?o.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Zl=new Mt("generate").description("Generate an image and optionally save it locally").argument("[prompt]","Image prompt").option("-p, --prompt <text>","Image prompt (named compatibility form)").option("--provider <provider>","Provider override").option("--model <model>","Model override").option("--width <pixels>","Width").option("--height <pixels>","Height").option("--team-id <id>","Workspace ID").option("-o, --output <path>","Local output path").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").option("--yes","Approve generation").action(async(e,t)=>{let n,r=e??t.prompt;r?.trim()||(d("Provide an image prompt as an argument or with --prompt"),process.exit(c.INVALID_INPUT)),t.yes||(d("Pass --yes to approve image generation"),process.exit(c.INVALID_INPUT)),!t.wait&&t.output&&(d("--output requires waiting for completion; remove --no-wait"),process.exit(c.INVALID_INPUT));try{let o=await y("createImage",{approvalReceipt:"cli:--yes",height:t.height?Number.parseInt(t.height,10):void 0,model:t.model,prompt:r.trim(),provider:t.provider,teamId:t.teamId,width:t.width?Number.parseInt(t.width,10):void 0});if(n=o.runId,!t.wait){Gn({requestId:o.runId,status:"pending"},t.format);return}let i=await Y(()=>Mi(o.runId,t.teamId),180,2e3);if(i.status==="failed")throw new Error(i.error||"Image generation failed");if(!i.url)throw new Error("Image generation completed without an image URL");let a=t.output?{...i,output:t.output}:i;t.output&&await J(i.url,t.output),Gn(a,t.format)}catch(o){d(ne(o,n),t.format),process.exit(c.GENERAL_ERROR)}}),eu=new Mt("status").description("Read image generation status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").option("-o, --output <path>","Download a completed image").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await Mi(e,t.teamId);if(t.output){if(n.status!=="completed"||!n.url)throw new Error("Image generation is not complete");await J(n.url,t.output),n.output=t.output}Gn(n,t.format)}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),Fi=new Mt("image").description("Image search and generation commands").addCommand(Ql).addCommand(Zl).addCommand(eu);import{Command as Bn}from"commander";var tu=new Bn("search").description("Search the workspace Knowledge Hub").argument("[query]","Optional search query").option("--team-id <id>","Workspace ID").option("--kind <kind>","Knowledge kind").option("--limit <count>","Maximum results","10").action(async(e,t)=>{try{p(await y("searchKnowledge",{kind:t.kind,limit:Number.parseInt(t.limit,10),query:e,teamId:t.teamId}))}catch(n){d(n instanceof Error?n.message:"Knowledge search failed"),process.exit(c.GENERAL_ERROR)}}),nu=new Bn("bundle").description("Read a bounded Open Knowledge Format bundle").option("--team-id <id>","Workspace ID").option("--kind <kind>","Knowledge kind").action(async e=>{try{p(await y("getKnowledgeBundle",{kind:e.kind,teamId:e.teamId}))}catch(t){d(t instanceof Error?t.message:"Knowledge bundle failed"),process.exit(c.GENERAL_ERROR)}}),Vi=new Bn("knowledge").description("Search the workspace Knowledge Hub and read bounded knowledge bundles").addCommand(tu).addCommand(nu);import{randomUUID as ru}from"crypto";import Ft from"chalk";import{Command as pe}from"commander";function Wn(e){if(e!==void 0)return e==="root"?null:e}function qe(e){return`cli:library:${e}:${ru()}`}function Se(e,t){d(e instanceof Error?e.message:t),process.exit(c.GENERAL_ERROR)}var ou=new pe("list").description("List the Library folder tree").option("--team-id <id>","Workspace ID").option("--counts","Include how many items are in each folder").action(async e=>{try{p(await y("listLibraryFolders",{includeEntryCounts:!!e.counts,teamId:e.teamId}))}catch(t){Se(t,"Could not list folders")}}),iu=new pe("create").description("Create a Library folder").argument("<name>","Folder name").option("--team-id <id>","Workspace ID").option("--parent <id>","Parent folder id; omit for a top-level folder").option("--color <color>","Colour token (slate, blue, green, amber, red, violet)").action(async(e,t)=>{try{p(await y("createLibraryFolder",{color:t.color,name:e,parentId:Wn(t.parent),teamId:t.teamId},qe("create")))}catch(n){Se(n,"Could not create the folder")}}),au=new pe("rename").description("Rename a Library folder").argument("<folder-id>","Folder id").argument("<name>","New name").option("--team-id <id>","Workspace ID").action(async(e,t,n)=>{try{p(await y("renameLibraryFolder",{folderId:e,name:t,teamId:n.teamId},qe("rename")))}catch(r){Se(r,"Could not rename the folder")}}),su=new pe("recolor").description("Set or clear a Library folder's colour").argument("<folder-id>","Folder id").requiredOption("--color <color>","Colour token (slate, blue, green, amber, red, violet), or 'none' to clear").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await y("recolorLibraryFolder",{color:t.color==="none"?null:t.color,folderId:e,teamId:t.teamId},qe("recolor")))}catch(n){Se(n,"Could not recolour the folder")}}),du=new pe("move").description("Move a Library folder under a new parent").argument("<folder-id>","Folder id").requiredOption("--to <id>","New parent folder id, or 'root' for top level").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await y("moveLibraryFolder",{folderId:e,newParentId:Wn(t.to),teamId:t.teamId},qe("move")))}catch(n){Se(n,"Could not move the folder")}}),cu=new pe("delete").description("Delete a folder and its subfolders; items inside are unfiled").argument("<folder-id>","Folder id").requiredOption("--yes","Confirm deletion").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await y("deleteLibraryFolder",{folderId:e,teamId:t.teamId},qe("delete")))}catch(n){Se(n,"Could not delete the folder")}}),lu=new pe("folders").description("Manage Library folders").addCommand(ou).addCommand(iu).addCommand(au).addCommand(su).addCommand(du).addCommand(cu),uu=new pe("file").description("File an artifact into a Library folder").argument("<kind>","Artifact kind, e.g. presentation or microsite").argument("<target-id>","Id of the artifact itself").requiredOption("--folder <id>","Destination folder id, or 'root' to unfile the artifact").option("--team-id <id>","Workspace ID").action(async(e,t,n)=>{try{p(await y("fileArtifactIntoFolder",{folderId:Wn(n.folder),kind:e,targetId:t,teamId:n.teamId},qe("file")))}catch(r){Se(r,"Could not file that item")}}),Kn=new pe("library").description("Library folders and filing").addCommand(lu).addCommand(uu);Kn.addHelpText("after",`
|
|
105
|
-
${
|
|
106
|
-
${
|
|
103
|
+
`);import z from"chalk";import{Command as ql}from"commander";import{existsSync as jl,readFileSync as Ml}from"fs";import Fl,{resolve as Bi}from"path";var Wi=new ql("create").description("Create a new presentation").argument("<topic>","The topic or title for the presentation").option("-n, --slides <count>","Number of slides (1-20)").option("-m, --mode <mode>","Generation quality (best, balanced, fast, ultrafast, instant, image-min, image, image-max) \u2014 default: fast. image-min/image/image-max render each slide as a full-bleed AI image (text not editable); slower + pricier, require image-mode access, and cap at 25 slides. image-min is cheapest (brand colors only, no exact fonts).").option("--image-tier <tier>","Embedded-image quality for HTML modes. Each tier is a per-image credit ceiling as well as its price: quick (+20/slide), smart (default, +60/slide), balanced (+250/slide), best (+500/slide, slow). Ignored for image-*/instant modes.").option("-t, --tone <tone>","Tone (creative, professional, educational, formal, casual)").option("--amount <amount>","Content density (minimal, concise, detailed, extensive)").option("--audience <text>","Target audience description").option("-l, --language <lang>","Output language").option("--branding-id <id>","Branding ID (from `ccr branding list` or `ccr branding extract`)").option("--brand-domain <url>","Brand the deck by website/domain (e.g. https://www.pfizer.com). Errors if no matching saved brand exists.").option("--template <id>","Slide template ID to style the deck after (from `ccr templates`). A default template is applied automatically when omitted.").option("-c, --context <text>","Inline text context (research notes, key facts)").option("--context-file <path>","Path to a context file (text, markdown, JSON)").option("--stdin","Read context from stdin").option("-f, --file <paths...>","Files to upload (PDF, PPTX, DOCX, images)").option("-g, --goal <type>","Goal (inform, persuade, train, learn, entertain, report)").option("--styling <mode>","Styling mode (freeform, brand-only, brand-plus-style, style-only, no-styling)").option("--reference-url <url>","Image URL to use as visual style reference").option("--thinking-depth <depth>","AI thinking depth (quick, moderate, deep, profound)").option("--theme <preset>","[instant mode only] Color theme preset (blue, violet, rose, orange, green)").option("--primary-color <hex>","[instant mode only] Primary color (e.g., #0066CC)").option("--secondary-color <hex>","[instant mode only] Secondary color").option("--accent-color <hex>","[instant mode only] Accent color").option("--background-color <hex>","[instant mode only] Background color").option("--foreground-color <hex>","[instant mode only] Foreground/text color").option("--decorations <style>","[instant mode only] Background decoration (none, waves-bottom-left, waves-top-right, blob-corners, minimal)").option("--team-id <id>","Team ID (switch teams)").option("-o, --output <format>","Output format (human, json, quiet)").option("--no-stream","Wait for completion without streaming progress").option("--wait","Poll until generation completes").option("--debug","Enable debug logging").option("--open","Open in browser after creation").option("--id <uuid>","Use a specific UUID for the presentation").option("--studio","Studio mode: use current directory name as presentation ID (auto-links to Studio preview)").action(async(e,t)=>{await A();let n;t.slides!==void 0&&(n=parseInt(t.slides,10),(Number.isNaN(n)||n<1||n>20)&&(d("Slide count must be between 1 and 20"),process.exit(6)));let r=["best","balanced","fast","ultrafast","instant","image-min","image","image-max"];t.mode&&!r.includes(t.mode)&&(d(`Invalid mode: ${t.mode}. Valid: ${r.join(", ")}`),process.exit(6));let o=["smart","fast","balanced","best"];t.imageTier&&!o.includes(t.imageTier)&&(d(`Invalid image tier: ${t.imageTier}. Valid: ${o.join(", ")}`),process.exit(6));let i=["creative","professional","educational","formal","casual"];t.tone&&!i.includes(t.tone)&&(d(`Invalid tone: ${t.tone}. Valid: ${i.join(", ")}`),process.exit(6));let a=["minimal","concise","detailed","extensive"];t.amount&&!a.includes(t.amount)&&(d(`Invalid amount: ${t.amount}. Valid: ${a.join(", ")}`),process.exit(6));let s=["freeform","brand-only","brand-plus-style","style-only","no-styling"];t.styling&&!s.includes(t.styling)&&(d(`Invalid styling: ${t.styling}. Valid: ${s.join(", ")}`),process.exit(6));let l=["quick","moderate","deep","profound"];t.thinkingDepth&&!l.includes(t.thinkingDepth)&&(d(`Invalid thinking-depth: ${t.thinkingDepth}. Valid: ${l.join(", ")}`),process.exit(6));let f=["inform","persuade","train","learn","entertain","report"];t.goal&&!f.includes(t.goal)&&(d(`Invalid goal: ${t.goal}. Valid: ${f.join(", ")}`),process.exit(6));let p=["blue","violet","rose","orange","green"];t.theme&&!p.includes(t.theme)&&(d(`Invalid theme: ${t.theme}. Valid: ${p.join(", ")}`),process.exit(6));let w=["none","waves-bottom-left","waves-top-right","blob-corners","minimal"];t.decorations&&!w.includes(t.decorations)&&(d(`Invalid decorations: ${t.decorations}. Valid: ${w.join(", ")}`),process.exit(6));let v=t.theme||t.primaryColor||t.secondaryColor||t.accentColor||t.backgroundColor||t.foregroundColor||t.decorations;v&&t.mode&&t.mode!=="instant"&&(d("--theme, --primary-color, --decorations and other color options are only supported with --mode instant"),process.exit(6));let b=t.mode??(v?"instant":"fast"),$=/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;for(let[I,W]of[["primary-color",t.primaryColor],["secondary-color",t.secondaryColor],["accent-color",t.accentColor],["background-color",t.backgroundColor],["foreground-color",t.foregroundColor]])W&&!$.test(W)&&(d(`Invalid ${I}: ${W}. Must be hex (e.g., #0066CC)`),process.exit(6));try{t.output!=="json"&&t.output!=="quiet"&&process.stdout.write(z.gray("Checking generation limits... "));let I=await go(b,n??10,t.teamId);if(t.output!=="json"&&t.output!=="quiet"){console.log(z.green("\u2713"));let W=I.remaining[b],Y=I.limits[b],Se=W===void 0||Y===void 0?"":` | ${b}: ${W}/${Y} remaining`;console.log(z.gray(` Plan: ${I.planName}${Se}`))}}catch(I){t.output==="json"?console.log(JSON.stringify({success:!1,error:I instanceof Error?I.message:String(I)})):(console.log(z.red("\u2717")),d(I instanceof Error?I.message:String(I))),process.exit(I.exitCode??1)}let x=[];if(t.file&&t.file.length>0){for(let I of t.file)jl(Bi(I))||(d(`File not found: ${I}`),process.exit(6));t.output!=="json"&&t.output!=="quiet"&&console.log(z.gray(`
|
|
104
|
+
Uploading ${t.file.length} file(s)...`));try{x=await eo(t.file.map(I=>Bi(I)),(I,W,Y)=>{t.output!=="json"&&t.output!=="quiet"&&Y&&process.stdout.write(`\r ${z.cyan("\u2B06")} Uploading: ${Y} (${I+1}/${W})`)}),t.output!=="json"&&t.output!=="quiet"&&console.log(`\r ${z.green("\u2713")} Uploaded ${x.length} file(s) `)}catch(I){d(`Failed to upload files: ${I instanceof Error?I.message:String(I)}`),process.exit(1)}}let k;(t.stdin||!process.stdin.isTTY)&&(k=await Vl(),t.stdin&&!k&&(d("No content received from stdin"),process.exit(6)));let R=t.context;if(t.contextFile)try{R=Ml(t.contextFile,"utf-8"),R.trim()||(d(`Context file is empty: ${t.contextFile}`),process.exit(6))}catch{d(`Failed to read context file: ${t.contextFile}`),process.exit(6)}!k&&!R&&x.length===0&&(d("Context is required to create a presentation."),console.log(),console.log(z.gray(" -f, --file <paths...> Upload files (PDF, PPTX, images)")),console.log(z.gray(" -c, --context <text> Inline text context")),console.log(z.gray(" --context-file <path> Read from a file")),console.log(z.gray(` cat file | ${u.commands[0]} Pipe content`)),process.exit(6));let N=[...x];k&&N.push({id:`stdin-${Date.now()}`,content:k,title:"Piped Content",mime:"text/plain",selected:!0}),R&&N.push({id:`context-${Date.now()}`,content:R,title:"Context",mime:"text/plain",selected:!0});let E,U=t.primaryColor||t.secondaryColor||t.accentColor||t.backgroundColor||t.foregroundColor;(t.theme||U||t.decorations)&&(E={},t.theme&&(E.preset=t.theme),U&&(E.custom={},t.primaryColor&&(E.custom.primary=t.primaryColor),t.secondaryColor&&(E.custom.secondary=t.secondaryColor),t.accentColor&&(E.custom.accent=t.accentColor),t.backgroundColor&&(E.custom.background=t.backgroundColor),t.foregroundColor&&(E.custom.foreground=t.foregroundColor)),t.decorations&&(E.decorations=t.decorations));try{let I=await to({topic:e,...n!==void 0&&{slideCount:n},mode:b,...t.imageTier&&{imageTier:t.imageTier},...t.tone&&{tone:t.tone},...t.amount&&{amount:t.amount},...t.audience&&{audience:t.audience},...t.language&&{language:t.language},...t.brandingId&&{brandingId:t.brandingId},...t.brandDomain&&{brandDomain:t.brandDomain},...t.template&&{templateId:t.template},...t.styling&&{stylingMode:t.styling},...t.referenceUrl&&{referenceUrl:t.referenceUrl},...t.thinkingDepth&&{thinkingDepth:t.thinkingDepth},...t.goal&&{goal:t.goal},...t.teamId&&{teamId:t.teamId},...E&&{theme:E},...t.studio?{documentId:Fl.basename(process.cwd())}:t.id?{documentId:t.id}:{},...N.length>0&&{contentSources:{uploadedFiles:N,contextFiles:[]}}});if(!t.wait){t.output==="json"?console.log(JSON.stringify({success:!0,run:I},null,2)):t.output!=="quiet"&&(C("Presentation generation queued"),S("Run ID",I.runId),S("Status",I.status),console.log(z.gray(` Check later with presentation status ${I.runId}`)));return}let W=await T("createSlides",I.runId,t.teamId);for(;!W.done;)t.output!=="json"&&t.output!=="quiet"&&console.log(z.gray(` ${W.message}`)),await new Promise(Se=>setTimeout(Se,(W.nextPollAfterSeconds??5)*1e3)),W=await T("createSlides",I.runId,t.teamId);if(W.error)throw new Error(oe(W.error));let Y=W.entity?await we(W.entity.id):void 0;if(t.output==="json")console.log(JSON.stringify({success:!0,presentation:Y,run:W,viewUrl:Y?Ue(Y.slug,t.language??"en"):void 0},null,2));else{console.log(),C("Presentation created successfully"),console.log(),S("Title",Y?.title??e),S("Slides",String(Y?.numberOfSlides??n??"\u2014")),console.log();let Se=Y?Ue(Y.slug,t.language??"en"):"N/A";Se!=="N/A"&&(console.log(z.bold(" Open: ")+z.cyan.underline(Se)),t.open&&await(await import("open")).default(Se)),console.log()}}catch(I){t.output==="json"?console.log(JSON.stringify({success:!1,error:I instanceof Error?I.message:String(I)})):d(I instanceof Error?I.message:String(I)),process.exit(I.exitCode??1)}});async function Vl(){return new Promise(e=>{let t="";if(process.stdin.setEncoding("utf8"),process.stdin.isTTY){e("");return}process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t.trim())}),setTimeout(()=>{e(t.trim())},100)})}import{randomUUID as Gl}from"crypto";import{readFile as Bl}from"fs/promises";import{Command as xe}from"commander";var zn=["text/markdown","text/csv","text/plain"];async function Ki(e){let t=e.content;if(t!==void 0&&t!=="-"&&!t.startsWith("@"))return t;if(t?.startsWith("@"))return Bl(t.slice(1),"utf8");if(t==="-"||!process.stdin.isTTY)return Wl();d("No document body. Pass --content <text>, --content @<path>, or pipe it on stdin."),process.exit(c.GENERAL_ERROR)}async function Wl(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}function Vt(e){return`cli:document:${e}:${Gl()}`}function Oe(e,t){d(e instanceof Error?e.message:t),process.exit(c.GENERAL_ERROR)}function Kl(e){if(!e)return;let t=e.split(".").pop()?.toLowerCase();if(t==="md"||t==="markdown")return"text/markdown";if(t==="csv")return"text/csv";if(t==="txt")return"text/plain"}var Jl=new xe("create").description("Save a document into the Library").argument("<title>","Document title").option("--team-id <id>","Workspace ID").option("--content <text>","Document body: literal text, @<path> to read a file, or '-' for stdin").option("--media-type <type>",`One of ${zn.join(", ")}; inferred from an @<path> body when omitted`).option("--summary <text>","One line for the Library card").action(async(e,t)=>{try{let n=t.mediaType??Kl(t.content?.startsWith("@")?t.content.slice(1):void 0);n||(d(`Cannot tell what this document is. Pass --media-type (${zn.join(", ")}).`),process.exit(c.GENERAL_ERROR)),m(await y("createDocument",{content:await Ki(t),mediaType:n,summary:t.summary,teamId:t.teamId,title:e},Vt("create")))}catch(n){Oe(n,"Could not save the document")}}),zl=new xe("list").description("List the workspace's documents, newest first").option("--team-id <id>","Workspace ID").option("--media-type <type>",`Filter to one of ${zn.join(", ")}`).option("--limit <n>","Maximum documents to return (default 50)").action(async e=>{try{m(await y("listDocuments",{limit:e.limit?Number(e.limit):void 0,mediaType:e.mediaType,teamId:e.teamId}))}catch(t){Oe(t,"Could not list documents")}}),Xl=new xe("read").description("Print a document's body").argument("<document-id>","Document id").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{let n=await y("readDocument",{documentId:e,teamId:t.teamId}),{document:r}=n;process.stderr.write(`${r.title} \xB7 ${r.mediaType} \xB7 v${r.version} \xB7 ${r.byteLength} bytes
|
|
105
|
+
`),process.stdout.write(r.content)}catch(n){Oe(n,"Could not read the document")}}),Hl=new xe("update").description("Edit a document under an optimistic lock").argument("<document-id>","Document id").requiredOption("--expected-version <n>","The version you last read; the edit is rejected if it has moved on").option("--team-id <id>","Workspace ID").option("--content <text>","New body: literal text, @<path> to read a file, or '-' for stdin").option("--title <text>","New title").option("--summary <text>","New Library-card summary").option("--change-summary <text>","What changed, recorded on the version").action(async(e,t)=>{try{let n=t.content!==void 0;m(await y("updateDocument",{changeSummary:t.changeSummary,content:n?await Ki(t):void 0,documentId:e,expectedVersion:Number(t.expectedVersion),summary:t.summary,teamId:t.teamId,title:t.title},Vt("update")))}catch(n){Oe(n,"Could not update the document")}}),Yl=new xe("delete").description("Remove a document from the Library").argument("<document-id>","Document id").option("--team-id <id>","Workspace ID").option("--yes","Skip the confirmation prompt").action(async(e,t)=>{try{!t.yes&&process.stdin.isTTY&&(d("Refusing to delete without confirmation. Re-run with --yes to remove this document."),process.exit(c.GENERAL_ERROR)),m(await y("deleteDocument",{documentId:e,teamId:t.teamId},Vt("delete")))}catch(n){Oe(n,"Could not delete the document")}}),Ql=new xe("versions").description("List a document's version history").argument("<document-id>","Document id").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await y("listDocumentVersions",{documentId:e,teamId:t.teamId}))}catch(n){Oe(n,"Could not list versions")}}),Zl=new xe("restore").description("Restore an earlier version by appending it as the current one").argument("<document-id>","Document id").requiredOption("--version-number <n>","The historical version to restore").requiredOption("--expected-version <n>","The version you last read; the restore is rejected if it has moved on").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await y("restoreDocumentVersion",{documentId:e,expectedVersion:Number(t.expectedVersion),teamId:t.teamId,versionNumber:Number(t.versionNumber)},Vt("restore")))}catch(n){Oe(n,"Could not restore the version")}}),Ji=new xe("document").description("Create, read and edit Library documents").addCommand(Jl).addCommand(zl).addCommand(Xl).addCommand(Hl).addCommand(Yl).addCommand(Ql).addCommand(Zl);import{Command as ae}from"commander";var eu=new ae("create").description("Create a transcript-native footage edit project").requiredOption("--title <title>","Project title").requiredOption("--source <asset-ids...>","Analyzed source recording IDs").requiredOption("--strategy <json>","Editorial strategy JSON object").requiredOption("--ranges <json>","Selected ranges JSON array").requiredOption("--outputs <json>","Output variants JSON array").option("--overlays <json>","Overlay JSON array","[]").option("--music-asset-id <id>","Music media asset ID").option("--source-chat-id <id>","Source chat ID").requiredOption("--idempotency-key <key>","Stable retry key").option("--team-id <id>","Workspace ID").action(async e=>{await ke("createFootageProject",{input:{musicAssetId:e.musicAssetId??null,outputs:mt(e.outputs,"outputs"),overlays:mt(e.overlays,"overlays"),ranges:mt(e.ranges,"ranges"),sourceAssetIds:e.source,sourceChatId:e.sourceChatId,strategy:mt(e.strategy,"strategy"),teamId:e.teamId,title:e.title},idempotencyKey:e.idempotencyKey})}),tu=new ae("show").description("Read a footage project and its append-only versions").argument("<project-id>","Project ID or slug").option("--version-id <id>","Historical version ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await ke("getFootageProject",{input:{projectId:e,teamId:t.teamId,versionId:t.versionId}})}),nu=new ae("revise").description("Append a semantic footage draft revision").argument("<project-id>","Project ID or slug").requiredOption("--base-version-id <id>","Current version ID").requiredOption("--change-summary <text>","Human-readable change summary").option("--title <title>","Replacement title").option("--strategy <json>","Replacement strategy JSON object").option("--ranges <json>","Replacement ranges JSON array").option("--outputs <json>","Replacement outputs JSON array").option("--overlays <json>","Replacement overlays JSON array").option("--music-asset-id <id-or-null>","Replacement music asset ID or null").requiredOption("--idempotency-key <key>","Stable retry key").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await ke("reviseFootageProject",{input:Hi({baseVersionId:t.baseVersionId,changeSummary:t.changeSummary,musicAssetId:t.musicAssetId==="null"?null:t.musicAssetId,outputs:Gt(t.outputs,"outputs"),overlays:Gt(t.overlays,"overlays"),projectId:e,ranges:Gt(t.ranges,"ranges"),strategy:Gt(t.strategy,"strategy"),teamId:t.teamId,title:t.title}),idempotencyKey:t.idempotencyKey})}),ru=new ae("restore").description("Restore a historical footage version as a new head").argument("<project-id>","Project ID or slug").argument("<version-id>","Historical version ID").option("--change-summary <text>","Change summary","Restored version").requiredOption("--idempotency-key <key>","Stable retry key").option("--team-id <id>","Workspace ID").action(async(e,t,n)=>{await ke("restoreFootageProjectVersion",{input:{changeSummary:n.changeSummary,projectId:e,teamId:n.teamId,versionId:t},idempotencyKey:n.idempotencyKey})}),ou=new ae("branch").description("Branch a historical footage version into a new project").argument("<project-id>","Source project ID or slug").argument("<version-id>","Historical version ID").requiredOption("--title <title>","New project title").requiredOption("--idempotency-key <key>","Stable retry key").option("--team-id <id>","Workspace ID").action(async(e,t,n)=>{await ke("branchFootageProjectVersion",{input:{projectId:e,teamId:n.teamId,title:n.title,versionId:t},idempotencyKey:n.idempotencyKey})}),iu=new ae("inspect").description("Create proxy, filmstrip, and waveform evidence for one range").argument("<project-id>","Project ID or slug").argument("<range-id>","Stable range ID").requiredOption("--version-id <id>","Exact version ID").requiredOption("--idempotency-key <key>","Stable retry key").option("--team-id <id>","Workspace ID").action(async(e,t,n)=>{await ke("inspectFootageRange",{input:{projectId:e,rangeId:t,teamId:n.teamId,versionId:n.versionId},idempotencyKey:n.idempotencyKey})}),au=new ae("inspection-status").description("Read a footage range inspection run").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await Xi("inspectFootageRange",e,t.teamId)}),su=new ae("render").description("Render an exact approved footage draft version").argument("<project-id>","Project ID or slug").requiredOption("--version-id <id>","Exact version ID").option("--output <ids...>","Output IDs; omit to render every output").requiredOption("--approval-receipt <receipt>","Browser-issued approval receipt").requiredOption("--idempotency-key <key>","Key bound into the receipt").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await ke("renderFootageProject",{input:Hi({approvalReceipt:t.approvalReceipt,outputIds:t.output,projectId:e,teamId:t.teamId,versionId:t.versionId}),idempotencyKey:t.idempotencyKey})}),du=new ae("render-status").description("Read a Footage Studio render run").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await Xi("renderFootageProject",e,t.teamId)}),cu=new ae("import-takes").description("Import all completed takes from a clipping invocation").argument("<project-id>","Project ID or slug").requiredOption("--invocation-id <id>","cc-services clipping invocation ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await ke("importFootageProviderTakes",{input:{invocationId:t.invocationId,projectId:e,teamId:t.teamId}})}),zi=new ae("footage").description("Create, inspect, revise, and render transcript-native footage edits").addCommand(eu).addCommand(tu).addCommand(nu).addCommand(ru).addCommand(ou).addCommand(iu).addCommand(au).addCommand(su).addCommand(du).addCommand(cu);async function ke(e,t){try{m(await y(e,t.input,t.idempotencyKey))}catch(n){d(n instanceof Error?n.message:"Footage operation failed"),process.exit(c.GENERAL_ERROR)}}async function Xi(e,t,n){try{m(await T(e,t,n))}catch(r){d(r instanceof Error?r.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}function mt(e,t){try{return JSON.parse(e)}catch{throw new Error(`${t} must be valid JSON.`)}}function Gt(e,t){return typeof e=="string"?mt(e,t):void 0}function Hi(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}import{Command as lu}from"commander";import Bt from"chalk";var Yi=new lu("get").description("Get presentation details").argument("<slug>","Presentation slug (e.g., my-presentation-v1-abc123)").option("-f, --format <format>","Output format (summary, full, json)","summary").option("--include <fields>","Fields to include (comma-separated: slides,styling)").option("-l, --language <lang>","Language for view URL","en").action(async(e,t)=>{await A();try{let n=await we(e);if(t.format==="json"){console.log(JSON.stringify(n,null,2));return}let r=Ue(n.slug,t.language);se("Presentation Details"),console.log(),S("Slug",n.slug),S("Title",n.title||"Untitled"),S("Description",n.description||Bt.gray("None")),S("Slides",String(n.numberOfSlides||"-")),S("Mode",n.mode||"-"),S("Created",vn(n.createdAt)),n.updatedAt&&S("Updated",vn(n.updatedAt)),console.log(),r!=="N/A"&&console.log(Bt.bold(" Open: ")+Bt.cyan.underline(r)),console.log(),t.format==="full"&&t.include?.includes("slides")&&(console.log(Bt.gray("(Full slide content available in JSON format)")),console.log())}catch(n){d(n instanceof Error?n.message:String(n)),process.exit(n.exitCode??1)}});import{Command as Kt}from"commander";import uu from"ora";function mu(e){let t=e?.trim().toLowerCase();if(!(!t||t==="any"||t==="all"))return t==="web"||t==="stock"?[t]:void 0}function pu(e){let t=e.assetType??"image";if(t!=="image"&&t!=="icon")throw new Error("Asset type must be image or icon");let n;if(e.maxResults&&(n=Number.parseInt(e.maxResults,10),Number.isNaN(n)||n<1))throw new Error("Max results must be a positive number");return{query:t==="icon"?`${e.query.trim()} transparent icon isolated symbol`:e.query.trim(),options:{maxResults:n||10,size:e.size,safeSearch:e.safeSearch,assetType:t,sources:mu(e.source),transparentBackground:t==="icon"}}}function gu(e){let t=e.url||e.imageUrl;if(!t)throw new Error("Image search returned a result without a URL");return t}function fu(e){return e.transparent??e.isTransparent??e.metadata?.transparent??e.metadata?.isTransparent}function hu(e){let t=[],n=e.reduce((r,o)=>Math.max(r,o.length),0);for(let r=0;r<n;r+=1)for(let o of e){let i=o[r];i!==void 0&&t.push(i)}return t}function yu(e,t){let n=e.data.results.map(r=>r.results.map(o=>{let i=o,a=fu(i);if(t==="icon"&&a!==!0)throw new Error("Icon search returned a result without a verified transparent background");return{...i,url:gu(i),provider:r.providerName,assetType:t,...a!==void 0?{transparent:a}:{}}}));return hu(n)}function bu(e){return e.error||e.status==="failed"||e.status==="errored"||e.status==="cancelled"?"failed":e.done||e.status==="completed"?"completed":e.status==="in_progress"?"processing":"pending"}function Wt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function wu(e){return{requestId:e.runId,status:bu(e),...e.entity?.url?{url:e.entity.url}:{},...e.error?{error:oe(e.error)}:{},...Wt(e.output?.width)!==void 0?{width:Wt(e.output?.width)}:{},...Wt(e.output?.height)!==void 0?{height:Wt(e.output?.height)}:{}}}async function Qi(e,t){return wu(await T("createImage",e,t))}function Xn(e,t){if(t==="json"){m(e);return}if(t==="quiet"){console.log(e.output??e.url??e.requestId);return}g(`Request ID: ${e.requestId}`),g(`Status: ${e.status}`),e.url&&C(`Image URL: ${e.url}`),e.output&&C(`Saved to: ${e.output}`),e.error&&d(`Error: ${e.error}`)}var vu=new Kt("search").description("Search images across the web and licensed stock").requiredOption("-q, --query <query>","Search query").option("-n, --max-results <number>","Maximum number of results (default: 10)").option("-s, --size <size>","Image size: small, medium, large, any","large").option("--asset-type <type>","Asset intent: image or transparent icon","image").option("--source <source>","Catalog: web, stock, or any (default: any)","any").option("--safe-search","Enable safe search (default: true)",!0).option("--no-safe-search","Disable safe search").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.format,n=t==="human"?uu("Searching for images...").start():null,r;try{r=pu(e)}catch(o){n?.stop(),d(o instanceof Error?o.message:"Invalid image search request"),process.exit(c.INVALID_INPUT);return}try{let o=await vo(r);n?.stop(),o.success||(d("Search failed"),process.exit(c.GENERAL_ERROR));let i=r.options?.assetType??"image",a=yu(o,i);if(t==="json"){m({success:!0,query:e.query,assetType:i,totalResults:a.length,images:a});return}if(t==="quiet"){for(let s of a)console.log(s.url);return}if(a.length===0){g("No images found");return}C(`Found ${a.length} images for "${e.query}"`),console.log();for(let s=0;s<a.length;s++){let l=a[s];console.log(`[${s+1}] ${l.title||"Untitled"}`),console.log(` URL: ${l.url}`),console.log(` Size: ${l.width}x${l.height}`),l.author&&console.log(` Author: ${l.author}`),console.log(` Provider: ${l.provider}`),console.log()}g(`Total cost: $${o.data.totalCost.toFixed(4)}`)}catch(o){n?.stop(),d(o instanceof Error?o.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),xu=new Kt("generate").description("Generate an image and optionally save it locally").argument("[prompt]","Image prompt").option("-p, --prompt <text>","Image prompt (named compatibility form)").option("--provider <provider>","Provider override").option("--model <model>","Model override").option("--width <pixels>","Width").option("--height <pixels>","Height").option("--team-id <id>","Workspace ID").option("-o, --output <path>","Local output path").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").option("--yes","Approve generation").action(async(e,t)=>{let n,r=e??t.prompt;r?.trim()||(d("Provide an image prompt as an argument or with --prompt"),process.exit(c.INVALID_INPUT)),t.yes||(d("Pass --yes to approve image generation"),process.exit(c.INVALID_INPUT)),!t.wait&&t.output&&(d("--output requires waiting for completion; remove --no-wait"),process.exit(c.INVALID_INPUT));try{let o=await y("createImage",{approvalReceipt:"cli:--yes",height:t.height?Number.parseInt(t.height,10):void 0,model:t.model,prompt:r.trim(),provider:t.provider,teamId:t.teamId,width:t.width?Number.parseInt(t.width,10):void 0});if(n=o.runId,!t.wait){Xn({requestId:o.runId,status:"pending"},t.format);return}let i=await Z(()=>Qi(o.runId,t.teamId),180,2e3);if(i.status==="failed")throw new Error(i.error||"Image generation failed");if(!i.url)throw new Error("Image generation completed without an image URL");let a=t.output?{...i,output:t.output}:i;t.output&&await H(i.url,t.output),Xn(a,t.format)}catch(o){d(re(o,n),t.format),process.exit(c.GENERAL_ERROR)}}),ku=new Kt("status").description("Read image generation status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").option("-o, --output <path>","Download a completed image").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await Qi(e,t.teamId);if(t.output){if(n.status!=="completed"||!n.url)throw new Error("Image generation is not complete");await H(n.url,t.output),n.output=t.output}Xn(n,t.format)}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),Zi=new Kt("image").description("Image search and generation commands").addCommand(vu).addCommand(xu).addCommand(ku);import{Command as Hn}from"commander";var Cu=new Hn("search").description("Search the workspace Knowledge Hub").argument("[query]","Optional search query").option("--team-id <id>","Workspace ID").option("--kind <kind>","Knowledge kind").option("--limit <count>","Maximum results","10").action(async(e,t)=>{try{m(await y("searchKnowledge",{kind:t.kind,limit:Number.parseInt(t.limit,10),query:e,teamId:t.teamId}))}catch(n){d(n instanceof Error?n.message:"Knowledge search failed"),process.exit(c.GENERAL_ERROR)}}),Iu=new Hn("bundle").description("Read a bounded Open Knowledge Format bundle").option("--team-id <id>","Workspace ID").option("--kind <kind>","Knowledge kind").action(async e=>{try{m(await y("getKnowledgeBundle",{kind:e.kind,teamId:e.teamId}))}catch(t){d(t instanceof Error?t.message:"Knowledge bundle failed"),process.exit(c.GENERAL_ERROR)}}),ea=new Hn("knowledge").description("Search the workspace Knowledge Hub and read bounded knowledge bundles").addCommand(Cu).addCommand(Iu);import{randomUUID as Ru}from"crypto";import Jt from"chalk";import{Command as be}from"commander";function Yn(e){if(e!==void 0)return e==="root"?null:e}function Ge(e){return`cli:library:${e}:${Ru()}`}function Pe(e,t){d(e instanceof Error?e.message:t),process.exit(c.GENERAL_ERROR)}var Su=new be("list").description("List the Library folder tree").option("--team-id <id>","Workspace ID").option("--counts","Include how many items are in each folder").action(async e=>{try{m(await y("listLibraryFolders",{includeEntryCounts:!!e.counts,teamId:e.teamId}))}catch(t){Pe(t,"Could not list folders")}}),$u=new be("create").description("Create a Library folder").argument("<name>","Folder name").option("--team-id <id>","Workspace ID").option("--parent <id>","Parent folder id; omit for a top-level folder").option("--color <color>","Colour token (slate, blue, green, amber, red, violet)").action(async(e,t)=>{try{m(await y("createLibraryFolder",{color:t.color,name:e,parentId:Yn(t.parent),teamId:t.teamId},Ge("create")))}catch(n){Pe(n,"Could not create the folder")}}),Tu=new be("rename").description("Rename a Library folder").argument("<folder-id>","Folder id").argument("<name>","New name").option("--team-id <id>","Workspace ID").action(async(e,t,n)=>{try{m(await y("renameLibraryFolder",{folderId:e,name:t,teamId:n.teamId},Ge("rename")))}catch(r){Pe(r,"Could not rename the folder")}}),Eu=new be("recolor").description("Set or clear a Library folder's colour").argument("<folder-id>","Folder id").requiredOption("--color <color>","Colour token (slate, blue, green, amber, red, violet), or 'none' to clear").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await y("recolorLibraryFolder",{color:t.color==="none"?null:t.color,folderId:e,teamId:t.teamId},Ge("recolor")))}catch(n){Pe(n,"Could not recolour the folder")}}),Au=new be("move").description("Move a Library folder under a new parent").argument("<folder-id>","Folder id").requiredOption("--to <id>","New parent folder id, or 'root' for top level").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await y("moveLibraryFolder",{folderId:e,newParentId:Yn(t.to),teamId:t.teamId},Ge("move")))}catch(n){Pe(n,"Could not move the folder")}}),Ou=new be("delete").description("Delete a folder and its subfolders; items inside are unfiled").argument("<folder-id>","Folder id").requiredOption("--yes","Confirm deletion").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await y("deleteLibraryFolder",{folderId:e,teamId:t.teamId},Ge("delete")))}catch(n){Pe(n,"Could not delete the folder")}}),Pu=new be("folders").description("Manage Library folders").addCommand(Su).addCommand($u).addCommand(Tu).addCommand(Eu).addCommand(Au).addCommand(Ou),_u=new be("file").description("File an artifact into a Library folder").argument("<kind>","Artifact kind, e.g. presentation or microsite").argument("<target-id>","Id of the artifact itself").requiredOption("--folder <id>","Destination folder id, or 'root' to unfile the artifact").option("--team-id <id>","Workspace ID").action(async(e,t,n)=>{try{m(await y("fileArtifactIntoFolder",{folderId:Yn(n.folder),kind:e,targetId:t,teamId:n.teamId},Ge("file")))}catch(r){Pe(r,"Could not file that item")}}),Qn=new be("library").description("Library folders and filing").addCommand(Pu).addCommand(_u);Qn.addHelpText("after",`
|
|
106
|
+
${Jt.bold("Examples:")}
|
|
107
|
+
${Jt.gray("# Browse the folder tree and file an artifact into a folder")}
|
|
107
108
|
$ ${u.commands[0]} library folders list
|
|
108
109
|
$ ${u.commands[0]} library file presentation <id> --folder <folder-id>
|
|
109
110
|
|
|
110
|
-
${
|
|
111
|
-
${
|
|
111
|
+
${Jt.bold("See also:")}
|
|
112
|
+
${Jt.gray("# A different thing: reusable video clips, not Library folders")}
|
|
112
113
|
$ ${u.commands[0]} video library --help
|
|
113
|
-
`);import{Command as st}from"commander";var ji=new st("analyze").description("Transcribe an uploaded recording and publish it for generation").argument("<asset-id>","Recording ID").option("--language <code>","BCP-47 language hint for the spoken audio").option("--no-diarize","Skip speaker attribution (cheaper, but a multi-speaker recording becomes much weaker as generation input)").option("--team-id <id>","Workspace ID").option("--yes","Confirm the charge \u2014 billed per source-minute").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to confirm. Analysis is billed per minute of source audio.");try{p(await y("analyzeMediaAsset",{assetId:e,diarize:t.diarize,language:t.language,teamId:t.teamId}))}catch(n){d(n instanceof Error?n.message:"Analysis failed"),process.exit(c.GENERAL_ERROR)}}),mu=new st("status").description("Read an analysis run's status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await T("analyzeMediaAsset",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}});ji.addCommand(mu);var Gi=new st("import").description("Import a recording from a connected account").argument("<remote-file-id>","The provider's own ID for the recording").requiredOption("--provider <id>","Provider id of the connected account, e.g. google").requiredOption("--connector <id>","Connected account ID to read from").option("--title <title>","Name for the imported recording").option("--chat <id>","Chat this import was requested from").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await y("importConnectorRecording",{connectorId:t.connector,providerId:t.provider,remoteFileId:e,sourceChatId:t.chat,teamId:t.teamId,title:t.title}))}catch(n){d(n instanceof Error?n.message:"Import failed"),process.exit(c.GENERAL_ERROR)}}),pu=new st("status").description("Read an import run's status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await T("importConnectorRecording",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}});Gi.addCommand(pu);var Bi=new st("media").description("Ingest and transcribe recordings you already own").addCommand(ji).addCommand(Gi);import{Command as Jn}from"commander";var gu=new Jn("create").description("Start background microsite generation").argument("<title>","Microsite title").requiredOption("--description <brief>","Microsite brief").option("--audience <audience>","Target audience").option("--tone <tone>","Tone").option("--language <language>","Content language","en").option("--branding-id <id>","Branding ID").option("--team-id <id>","Workspace ID").option("--yes","Approve generation").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to approve generation");try{p(await y("createMicrosite",{approvalReceipt:"cli:--yes",audience:t.audience,brandingId:t.brandingId,description:t.description,language:t.language,teamId:t.teamId,title:e,tone:t.tone}))}catch(n){d(n instanceof Error?n.message:"Generation failed"),process.exit(c.GENERAL_ERROR)}}),fu=new Jn("status").description("Read microsite generation status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await T("createMicrosite",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),Wi=new Jn("microsite").description("Generate a shareable multi-section web microsite from a brief").addCommand(gu).addCommand(fu);import{Command as Hn}from"commander";import zn from"ora";function Xn(e,t){if(t==="json"){let{cost:n,...r}=e;p(r);return}if(t==="quiet"){e.outputUrl?console.log(e.outputUrl):console.log(e.requestId);return}f(`Request ID: ${e.requestId}`),f(`Status: ${e.status}`),e.duration&&f(`Duration: ${e.duration}s`),e.outputUrl&&C(`Output URL: ${e.outputUrl}`),e.cost!==void 0&&f(`Cost: $${e.cost.toFixed(4)}`),e.error&&d(`Error: ${e.error}`)}var hu=new Hn("create").description("Mix audio tracks into a video (music will loop to match video duration)").requiredOption("--video <url>","Input video file/URL").option("--music <url>","Background music file/URL (will loop if shorter than video)").option("--voice <url>","Voiceover file/URL").option("--music-volume <percent>","Music volume 0-100 (default: 30, recommended for mix with voice)","30").option("--voice-volume <percent>","Voice volume 0-100","100").option("-o, --output <path>","Output file path").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{!e.music&&!e.voice&&(d("At least one of --music or --voice must be provided"),process.exit(c.INVALID_INPUT));let t=parseInt(e.musicVolume,10)/100,n=parseInt(e.voiceVolume,10)/100;(Number.isNaN(t)||t<0||t>1)&&(d("Music volume must be between 0 and 100"),process.exit(c.INVALID_INPUT)),(Number.isNaN(n)||n<0||n>2)&&(d("Voice volume must be between 0 and 200"),process.exit(c.INVALID_INPUT));let r=e.format,o=r==="human"?zn("Mixing audio...").start():null,i=[{url:e.video,role:"video"}];e.music&&i.push({url:e.music,role:"background",volume:t*5}),e.voice&&i.push({url:e.voice,role:"voice",volume:n*2});try{let a=await co({operation:"add-to-video",inputs:i,options:{musicVolume:t,voiceVolume:n}});if(!e.wait){o?.stop(),Xn(a,r);return}o&&(o.text=`Processing (ID: ${a.requestId})...`);let s=await Y(()=>vn(a.requestId),120,3e3);if(o?.stop(),s.status==="failed"&&(d(s.error||"Audio mixing failed"),process.exit(c.GENERAL_ERROR)),Xn(s,r),e.output){if(!s.outputUrl)throw new Error("Audio mix completed without an output URL");let l=r==="human"?zn("Downloading...").start():null;await J(s.outputUrl,e.output),l?.stop(),r==="human"&&C(`Saved to: ${e.output}`)}}catch(a){o?.stop(),d(a instanceof Error?a.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),yu=new Hn("status").description("Check status of an audio mix request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{let n=t.format==="human"?zn("Checking status...").start():null;try{let r=await vn(e);n?.stop(),Xn(r,t.format)}catch(r){n?.stop(),d(r instanceof Error?r.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Ki=new Hn("mix").description("Audio mixing commands").addCommand(hu).addCommand(yu);import{Command as Qn}from"commander";import Iu from"ora";import{readFileSync as bu}from"fs";var Ji=500,zi=1e4,Vt=100,Xi=1e4,Hi=1e3,Qi=["duration_s","idempotency_key","narration","schema_version","video_description"],wu=["end_s","id","start_s","text","words"],vu=["end","id","start","text"],xu=["description","end_s","id","start_s"];function Zi(e){let t=ta(e);if(na(t),dt(t,Qi,""),t.duration_s<3)throw new Error("Music request duration_s must be between 3 and 600");return t}function ea(e){let t=ta(e);na(t),dt(t,[...Qi,"visual_event"],"");let n=t.visual_event;if(!jt(n))throw new Error("SFX request visual_event is required");if(dt(n,xu,"visual_event"),!ye(n.description))throw new Error("SFX request visual_event.description is required");if(!ye(n.id)||!be(n.start_s))throw new Error("SFX request visual_event requires id and start_s");if(n.end_s!==void 0&&(!be(n.end_s)||n.end_s<n.start_s))throw new Error("SFX request visual_event.end_s must be after start_s");return t}function ta(e){try{let t=JSON.parse(bu(e,"utf8"));if(!jt(t))throw new Error("request must be a JSON object");return t}catch(t){throw new Error(`Cannot read audio request ${e}: ${t instanceof Error?t.message:String(t)}`)}}function na(e){if(e.schema_version!==1)throw new Error("Audio request schema_version must be 1");if(!ye(e.video_description))throw new Error("Audio request video_description is required");if(!be(e.duration_s)||e.duration_s<.5||e.duration_s>600)throw new Error("Audio request duration_s must be between 0.5 and 600");if(!Array.isArray(e.narration))throw new Error("Audio request narration must be an array");if(e.narration.length>Ji)throw new Error(`Audio request narration holds at most ${Ji} lines`);if(e.narration.forEach(ku),e.idempotency_key!==void 0&&!ye(e.idempotency_key))throw new Error("Audio request idempotency_key must be a non-empty string")}function ku(e,t){let n=`narration.${t}`;if(!jt(e))throw new Error(`Audio request ${n} must be an object`);if(dt(e,wu,n),!ye(e.id)||e.id.length>Vt)throw new Error(`Audio request ${n}.id is required (1-${Vt} characters)`);if(!ye(e.text)||e.text.trim().length>Xi)throw new Error(`Audio request ${n}.text is required (1-${Xi} characters)`);if(Yi(e.start_s,`${n}.start_s`),Yi(e.end_s,`${n}.end_s`),be(e.start_s)&&be(e.end_s)&&e.end_s<e.start_s)throw new Error(`Audio request ${n}.end_s must be greater than or equal to ${n}.start_s`);if(e.words!==void 0){if(!Array.isArray(e.words)||e.words.length>zi)throw new Error(`Audio request ${n}.words must be an array of at most ${zi} entries`);e.words.forEach((r,o)=>{Cu(r,`${n}.words.${o}`)})}}function Cu(e,t){if(!jt(e))throw new Error(`Audio request ${t} must be an object`);if(dt(e,vu,t),!ye(e.text)||e.text.trim().length>Hi)throw new Error(`Audio request ${t}.text is required (1-${Hi} characters)`);if(!be(e.start)||!be(e.end))throw new Error(`Audio request ${t} requires numeric start and end seconds`);if(e.end<e.start)throw new Error(`Audio request ${t}.end must be greater than or equal to ${t}.start`);if(e.id!==void 0&&(!ye(e.id)||e.id.length>Vt))throw new Error(`Audio request ${t}.id must be 1-${Vt} characters`)}function Yi(e,t){if(e!==void 0&&!be(e))throw new Error(`Audio request ${t} must be a non-negative number`)}function dt(e,t,n){let r=Object.keys(e).filter(i=>!t.includes(i));if(r.length===0)return;let o=n?`${n} `:"";throw new Error(`Audio request ${o}has unknown field(s): ${r.join(", ")}. Allowed: ${t.join(", ")}`)}function jt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ye(e){return typeof e=="string"&&e.trim().length>0}function be(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Yn(e,t){if(t==="json"){let{cost:n,...r}=e;p(r);return}if(t==="quiet"){console.log(e.audioUrl??e.requestId);return}f(`Request ID: ${e.requestId}`),f(`Status: ${e.status}`),e.duration&&f(`Duration: ${e.duration}s`),e.audioUrl&&C(`Audio URL: ${e.audioUrl}`),e.cost!==void 0&&f(`Cost: $${e.cost.toFixed(4)}`),e.error&&d(`Error: ${e.error}`)}var Ru=new Qn("generate").description("Generate music that follows a video's narration and final timing").requiredOption("--request <path>","JSON file with video description, narration, and final timing").option("-o, --output <path>","Output file path").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{!e.wait&&e.output&&(d("--output requires waiting for completion; remove --no-wait"),process.exit(c.INVALID_INPUT));let t;try{t=Zi(e.request)}catch(i){d(i instanceof Error?i.message:String(i)),process.exit(c.INVALID_INPUT)}let n=e.format,r=n==="human"?Iu("Generating music for video...").start():null,o;try{let i=await so(t);if(o=i.requestId,!e.wait){r?.stop(),Yn(i,n);return}r&&(r.text=`Processing (ID: ${i.requestId})...`);let a=i.status==="completed"||i.status==="failed"?i:await Y(()=>wn(i.requestId),180,2e3);if(r?.stop(),a.status==="failed"&&(d(a.error||"Music generation failed"),process.exit(c.GENERAL_ERROR)),e.output){if(!a.audioUrl)throw new Error("Music completed without an audio URL");await J(a.audioUrl,e.output),n==="human"&&C(`Saved to: ${e.output}`),a.output=e.output}Yn(a,n)}catch(i){r?.stop(),d(ne(i,o),n),process.exit(c.GENERAL_ERROR)}}),Su=new Qn("status").description("Check status of a music generation request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{Yn(await wn(e),t.format)}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),ra=new Qn("music").description("Video-aware music generation commands").addCommand(Ru).addCommand(Su);import{Command as Zn}from"commander";function oa(e,t){return[...t,e]}var $u=new Zn("create").description("Create a standalone poll").argument("<question>","Poll question").option("--option <text>","Choice (repeat 2-10 times)",oa,[]).option("--type <type>","single, multiple, or word-cloud","single").option("--title <title>","Poll title").option("--team-id <id>","Workspace ID").option("--yes","Approve creation").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to approve poll creation");try{p(await y("createPoll",{approvalReceipt:"cli:--yes",options:t.option.map(n=>({text:n})),pollType:t.type,question:e,teamId:t.teamId,title:t.title}))}catch(n){d(n instanceof Error?n.message:"Poll creation failed"),process.exit(c.GENERAL_ERROR)}}),Tu=new Zn("edit").description("Edit a standalone poll").argument("<poll-id>","Poll UUID").option("--question <question>","New question").option("--option <text>","Replacement choice (repeat)",oa).option("--type <type>","single, multiple, or word-cloud").option("--title <title>","Poll title").option("--team-id <id>","Workspace ID").option("--yes","Approve update").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to approve poll update");try{p(await y("editPoll",{approvalReceipt:"cli:--yes",options:t.option?.map(n=>({text:n})),pollId:e,pollType:t.type,question:t.question,teamId:t.teamId,title:t.title}))}catch(n){d(n instanceof Error?n.message:"Poll update failed"),process.exit(c.GENERAL_ERROR)}}),ia=new Zn("poll").description("Standalone poll commands").addCommand($u).addCommand(Tu);import{randomUUID as Uu}from"crypto";import{readFile as qu}from"fs/promises";import $e from"chalk";import{Command as X}from"commander";import{randomUUID as tr}from"crypto";import{readFile as Eu}from"fs/promises";import{Command as Gt}from"commander";var aa=new Gt("edit").description("Apply one atomic draft edit: narration, scene patch/move/remove, composition, or intro/outro card").argument("<project-id>","Presentation-video project UUID or editor slug").requiredOption("--edit <json-or-path>","Edit object as inline JSON or a JSON file path").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key").action(async(e,t)=>{await Bt("Draft edit failed",async()=>y("editPresentationVideoDraft",{edit:await Au(t.edit),projectId:e,teamId:t.teamId},t.idempotencyKey??tr()))}),sa=new Gt("versions").description("List saved presentation-video draft versions").argument("<project-id>","Presentation-video project UUID or editor slug").option("--before-version <number>","Continue below this version number",er(1)).option("--limit <number>","Maximum versions",er(1,100)).option("--team-id <id>","Workspace ID override").action(async(e,t)=>{await Bt("Version list failed",()=>y("listPresentationVideoVersions",{beforeVersion:t.beforeVersion,limit:t.limit,projectId:e,teamId:t.teamId}))}),da=new Gt("restore").description("Restore a saved draft version as a new version").argument("<project-id>","Presentation-video project UUID or editor slug").argument("<version-number>","Version number",er(1)).option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key").action(async(e,t,n)=>{await Bt("Version restore failed",()=>y("restorePresentationVideoVersion",{projectId:e,teamId:n.teamId,versionNumber:t},n.idempotencyKey??tr()))}),ca=new Gt("refresh").description("Refresh deck-backed scenes from the latest presentation version").argument("<project-id>","Presentation-video project UUID or editor slug").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key").action(async(e,t)=>{await Bt("Slide refresh failed",()=>y("refreshPresentationVideoSlides",{projectId:e,teamId:t.teamId},t.idempotencyKey??tr()))});async function Au(e){let t=e.trim(),n=t.startsWith("{")?t:await Eu(t,"utf8"),r=JSON.parse(n);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("--edit must contain one JSON object.");return r}function er(e,t=Number.MAX_SAFE_INTEGER){return n=>{let r=Number(n);if(!Number.isInteger(r)||r<e||r>t)throw new Error(`Expected an integer between ${e} and ${t}.`);return r}}async function Bt(e,t){try{p(await t())}catch(n){d(n instanceof Error?n.message:e),process.exit(c.GENERAL_ERROR)}}import{randomUUID as Ou}from"crypto";import{Command as Pu}from"commander";var _u=["basic","standard","premium"],la=new Pu("presenter").description("Set one scene to a different avatar/look or preset, or restore the project default").argument("<project-id>","Presentation video project ID").argument("<slide-id>","Slide or intro/outro scene ID").option("--avatar-id <id>","Exact avatar/look ID from presenter list").option("--cast-preset-id <id>","Saved cast preset ID").option("--no-apply-preset-voice","Preserve this scene's current voice instead of applying the preset voice").option("--inherit","Remove the override and inherit the project default").option("--render-tier <tier>","Avatar render tier: basic, standard, or premium").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key for this update").action(async(e,t,n)=>{try{if(+!!n.avatarId+ +!!n.castPresetId+ +(n.inherit===!0)!==1)throw new Error("Pass exactly one of --avatar-id, --cast-preset-id, or --inherit.");if(n.renderTier&&!n.avatarId)throw new Error("--render-tier can only be used with --avatar-id.");if(n.renderTier&&!_u.includes(n.renderTier))throw new Error("--render-tier must be basic, standard, or premium.");p(await y("setPresentationVideoScenePresenter",{applyPresetVoice:n.castPresetId?n.applyPresetVoice:void 0,avatarId:n.avatarId,castPresetId:n.castPresetId,inherit:n.inherit,projectId:e,renderTier:n.renderTier,slideId:t,teamId:n.teamId},Lu(n.idempotencyKey)))}catch(r){d(r instanceof Error?r.message:"Scene presenter update failed"),process.exit(c.GENERAL_ERROR)}});function Lu(e){return e||Ou()}import{Command as nr}from"commander";var ua=new nr("inspect").description("Read a presentation-video project and its ordered scene timeline").argument("<project-id>","Presentation-video project UUID or editor slug").option("--team-id <id>","Workspace ID override").action(async(e,t)=>{try{p(await y("getPresentationVideoProject",{projectId:e,teamId:t.teamId}))}catch(n){d(n instanceof Error?n.message:"Project read failed"),process.exit(c.GENERAL_ERROR)}}),Du=new nr("list").description("List generated clips and uploaded recordings usable in a presentation video").argument("<project-id>","Target presentation-video project UUID or slug").option("--cursor <cursor>","Opaque cursor from the previous page").option("--limit <number>","Maximum clips to return",Nu).option("--query <text>","Filter clips by title").option("--team-id <id>","Workspace ID override").action(async(e,t)=>{try{p(await y("listReusableVideoClips",{cursor:t.cursor,limit:t.limit,projectId:e,query:t.query,teamId:t.teamId}))}catch(n){d(n instanceof Error?n.message:"Clip list failed"),process.exit(c.GENERAL_ERROR)}}),ma=new nr("library").description("Reusable generated clips and uploaded recordings").addCommand(Du);function Nu(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>100)throw new Error("--limit must be an integer between 1 and 100.");return t}var Mu=new X("status").description("Check a presentation generation run").argument("<run-id>","Run ID returned by presentation generation").option("--team-id <id>","Workspace ID override").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("createSlides",e,t.teamId);if(t.format==="json"){p(n);return}if(t.format==="quiet"){console.log(n.status);return}f(`Status: ${n.status}`),f(n.message),n.progress!==null&&f(`Progress: ${n.progress}%`),n.error&&d(n.error.message)}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Fu=new X("transform").description("Transform an uploaded PowerPoint import for review").argument("<import-id>","PowerPoint import ID returned by Mindframes").option("--idempotency-key <key>","Stable retry key").action(async(e,t)=>{try{let n=await y("transformPresentationImport",{importId:e},t.idempotencyKey);p(n)}catch(n){d(n instanceof Error?n.message:"Transform failed"),process.exit(c.GENERAL_ERROR)}}),Vu=new X("status").description("Read a PowerPoint import run").argument("<run-id>","Run ID returned by PowerPoint import").option("--team-id <id>","Workspace ID override").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("importPowerPoint",e,t.teamId);t.format==="json"?p(n):t.format==="quiet"?console.log(n.status):(f(`Status: ${n.status}`),f(n.message),n.error&&d(n.error.message))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),pa=new X("import").description("Import a PowerPoint through the review-gated reconstruction pipeline").option("--file <path>","Path to the .pptx to import").option("--filename <name>","Override the uploaded filename").option("--mode <mode>","Import mode: preserve or rebrand","preserve").option("--branding-id <id>","Saved brand ID (required for rebrand mode)").option("--source-chat-id <id>","Associate the import with an existing chat").option("--title <title>","Presentation title").option("--idempotency-key <key>","Stable retry key").action(async e=>{if(!e.file){pa.help();return}e.file.toLowerCase().endsWith(".pptx")||(d("PowerPoint import requires a .pptx file."),process.exit(c.INVALID_INPUT));try{let t=await se(e.file),n=await y("importPowerPoint",{brandingId:e.brandingId,filename:e.filename??t.name,mode:e.mode,sourceChatId:e.sourceChatId,sourceUrl:t.url,title:e.title},e.idempotencyKey??Uu());p(n)}catch(t){d(t instanceof Error?t.message:"Import failed"),process.exit(c.GENERAL_ERROR)}}).addCommand(Fu).addCommand(Vu),ju=new X("speaker-notes-status").description("Check a speaker-notes generation run").argument("<run-id>","Run ID returned by speaker-notes generation").option("--team-id <id>","Workspace ID override").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("generateSpeakerNotes",e,t.teamId);t.format==="json"?p(n):t.format==="quiet"?console.log(n.status):(f(`Status: ${n.status}`),f(n.message))}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Gu=new X("video-narration-status").description("Check a presentation-video narration regeneration run").argument("<run-id>","Run ID returned by video-narration").option("--team-id <id>","Workspace ID override").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("regeneratePresentationVideoNarration",e,t.teamId);t.format==="json"?p(n):t.format==="quiet"?console.log(n.status):(f(`Status: ${n.status}`),f(n.message))}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Bu=new X("status").description("Read a presentation-video MP4 render run").argument("<run-id>","Run ID returned by presentation video").option("--team-id <id>","Workspace ID override").action(async(e,t)=>{try{p(await T("createPresentationVideo",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),Wu=new X("prepare").description("Create or reuse a presentation-video project for a presentation").argument("<presentation-id>","Presentation ID, document ID, or slug").option("--force-new","Create a fresh video project even if the current presentation version already has one").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key for this prepare request").option("--yes","Confirm creating or reusing the presentation video project").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to confirm preparing a presentation video.");try{p(await y("preparePresentationVideo",{forceNew:t.forceNew,presentationId:e,teamId:t.teamId},t.idempotencyKey))}catch(n){d(n instanceof Error?n.message:"Prepare failed"),process.exit(c.GENERAL_ERROR)}}),Ku=new X("settings").description("Update saved presentation-video render settings").argument("<project-id>","Presentation video project ID").requiredOption("--settings <json-or-path>","Settings patch as JSON or a path to a JSON file").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key for this settings update").option("--yes","Confirm updating presentation video settings").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to confirm updating presentation video settings.");try{p(await y("updatePresentationVideoSettings",{projectId:e,settings:await ga(t.settings),teamId:t.teamId},t.idempotencyKey))}catch(n){d(n instanceof Error?n.message:"Settings update failed"),process.exit(c.GENERAL_ERROR)}}),Ju=new X("video").description("Create an MP4 video from a presentation").argument("[presentation-id]","Presentation ID, document ID, or slug").option("--project-id <id>","Advanced: render an already-configured presentation video project").option("--settings <json-or-path>","Settings patch as JSON or a path to a JSON file; only valid with presentation-id").option("--force-new","Create a fresh video project even if the current presentation version already has one").option("--force-rerender","Start a new MP4 render even when the current project fingerprint has a completed render").option("--render-engine <engine>","Renderer for this MP4 only: remotion (Standard) or hyperframes (Premium)").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key for this render request").option("--yes","Confirm starting the MP4 render").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to confirm presentation video rendering.");try{if(!e&&!t.projectId)throw new Error("Pass a presentation id or --project-id.");if(e&&t.projectId)throw new Error("Pass either presentation id or --project-id, not both.");if(t.projectId&&(t.settings||t.forceNew))throw new Error("--settings and --force-new require a presentation id, not --project-id.");if(t.renderEngine&&t.renderEngine!=="remotion"&&t.renderEngine!=="hyperframes")throw new Error("--render-engine must be remotion or hyperframes.");p(await y("createPresentationVideo",{forceNew:t.forceNew,forceRerender:t.forceRerender,presentationId:e,projectId:t.projectId,renderEngine:t.renderEngine,settings:t.settings?await ga(t.settings):void 0,teamId:t.teamId},t.idempotencyKey))}catch(n){d(n instanceof Error?n.message:"Render failed"),process.exit(c.GENERAL_ERROR)}}).addCommand(Wu).addCommand(ua).addCommand(aa).addCommand(la).addCommand(ca).addCommand(da).addCommand(Ku).addCommand(Bu).addCommand(sa);async function ga(e){let t=e.trim(),n=t.startsWith("{")?t:await qu(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("--settings must be a JSON object.");return r}function zu(e,t){return[...t,e]}var Xu=new X("speaker-notes").description("Generate or regenerate persisted presentation speaker notes").argument("<presentation-id>","Presentation ID or slug").option("--mode <mode>","ensure or regenerate","ensure").option("--style <style>","concise or detailed","concise").option("--instructions <text>","Instructions for every selected slide").option("--language <language>","Output language").option("--slide-id <id>","Target one slide (repeatable)",zu,[]).option("--no-follow","Return immediately with the durable run ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{if(!["ensure","regenerate"].includes(t.mode))throw new Error("--mode must be ensure or regenerate");if(!["concise","detailed"].includes(t.style))throw new Error("--style must be concise or detailed");let n=await Jr(e,{instructions:t.instructions,language:t.language,mode:t.mode,slideIds:t.slideId.length?t.slideId:void 0,style:t.style});if(t.format==="json"||!t.follow){p(n);return}f(`Speaker notes run: ${n.runId}`);let r=await yn(n.runId);await fa(r)}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Hu=new X("video-narration").description("Regenerate one slide narration in a presentation video draft").argument("<project-id>","Presentation video project ID").requiredOption("--slide-id <id>","Slide ID in the video draft").option("--instructions <text>","Optional regeneration instructions").option("--no-follow","Return immediately with the durable run ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await zr(e,{instructions:t.instructions,slideId:t.slideId});if(t.format==="json"||!t.follow){p(n);return}f(`Narration run: ${n.runId}`),await fa(await yn(n.runId))}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}});async function fa(e){let t=e.body?.getReader();if(!t)throw new Error("Speaker notes event stream is unavailable");let n=new TextDecoder,r="";for(;;){let{done:o,value:i}=await t.read();r+=n.decode(i,{stream:!o});let a=r.split(`
|
|
114
|
-
|
|
115
|
-
`);r=
|
|
116
|
-
`).find(
|
|
117
|
-
${
|
|
118
|
-
$ ${u.commands[0]} presentation video prepare <slug> ${
|
|
119
|
-
$ ${u.commands[0]} presentation video
|
|
120
|
-
$ ${u.commands[0]} presentation video <
|
|
121
|
-
$ ${u.commands[0]} presentation video
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
114
|
+
`);import{Command as pt}from"commander";function F(e,t){let n={...t},r=e.parent,o=!1;for(;r;){let i=r.opts?.();if(i){o=!0;for(let[a,s]of Object.entries(i))n[a]===void 0&&s!==void 0&&(n[a]=s)}r=r.parent}return o?n:t}var ta=new pt("analyze").description("Transcribe an uploaded recording and publish it for generation").argument("<asset-id>","Recording ID").option("--language <code>","BCP-47 language hint for the spoken audio").option("--no-diarize","Skip speaker attribution (cheaper, but a multi-speaker recording becomes much weaker as generation input)").option("--team-id <id>","Workspace ID").option("--yes","Confirm the charge \u2014 billed per source-minute").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to confirm. Analysis is billed per minute of source audio.");try{m(await y("analyzeMediaAsset",{assetId:e,diarize:t.diarize,language:t.language,teamId:t.teamId}))}catch(n){d(n instanceof Error?n.message:"Analysis failed"),process.exit(c.GENERAL_ERROR)}}),Lu=new pt("status").description("Read an analysis run's status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async function(e,t){let n=F(this,t);try{m(await T("analyzeMediaAsset",e,n.teamId))}catch(r){d(r instanceof Error?r.message:"Status failed"),process.exit(c.GENERAL_ERROR)}});ta.addCommand(Lu);var na=new pt("import").description("Import a recording from a connected account").argument("<remote-file-id>","The provider's own ID for the recording").requiredOption("--provider <id>","Provider id of the connected account, e.g. google").requiredOption("--connector <id>","Connected account ID to read from").option("--title <title>","Name for the imported recording").option("--chat <id>","Chat this import was requested from").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await y("importConnectorRecording",{connectorId:t.connector,providerId:t.provider,remoteFileId:e,sourceChatId:t.chat,teamId:t.teamId,title:t.title}))}catch(n){d(n instanceof Error?n.message:"Import failed"),process.exit(c.GENERAL_ERROR)}}),Du=new pt("status").description("Read an import run's status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async function(e,t){let n=F(this,t);try{m(await T("importConnectorRecording",e,n.teamId))}catch(r){d(r instanceof Error?r.message:"Status failed"),process.exit(c.GENERAL_ERROR)}});na.addCommand(Du);var ra=new pt("media").description("Ingest and transcribe recordings you already own").addCommand(ta).addCommand(na);import{Command as Zn}from"commander";var Nu=new Zn("create").description("Start background microsite generation").argument("<title>","Microsite title").requiredOption("--description <brief>","Microsite brief").option("--audience <audience>","Target audience").option("--tone <tone>","Tone").option("--language <language>","Content language","en").option("--branding-id <id>","Branding ID").option("--team-id <id>","Workspace ID").option("--yes","Approve generation").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to approve generation");try{m(await y("createMicrosite",{approvalReceipt:"cli:--yes",audience:t.audience,brandingId:t.brandingId,description:t.description,language:t.language,teamId:t.teamId,title:e,tone:t.tone}))}catch(n){d(n instanceof Error?n.message:"Generation failed"),process.exit(c.GENERAL_ERROR)}}),Uu=new Zn("status").description("Read microsite generation status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await T("createMicrosite",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),oa=new Zn("microsite").description("Generate a shareable multi-section web microsite from a brief").addCommand(Nu).addCommand(Uu);import{Command as nr}from"commander";import er from"ora";function tr(e,t){if(t==="json"){let{cost:n,...r}=e;m(r);return}if(t==="quiet"){e.outputUrl?console.log(e.outputUrl):console.log(e.requestId);return}g(`Request ID: ${e.requestId}`),g(`Status: ${e.status}`),e.duration&&g(`Duration: ${e.duration}s`),e.outputUrl&&C(`Output URL: ${e.outputUrl}`),e.cost!==void 0&&g(`Cost: $${e.cost.toFixed(4)}`),e.error&&d(`Error: ${e.error}`)}var qu=new nr("create").description("Mix audio tracks into a video (music will loop to match video duration)").requiredOption("--video <url>","Input video file/URL").option("--music <url>","Background music file/URL (will loop if shorter than video)").option("--voice <url>","Voiceover file/URL").option("--music-volume <percent>","Music volume 0-100 (default: 30, recommended for mix with voice)","30").option("--voice-volume <percent>","Voice volume 0-100","100").option("-o, --output <path>","Output file path").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{!e.music&&!e.voice&&(d("At least one of --music or --voice must be provided"),process.exit(c.INVALID_INPUT));let t=parseInt(e.musicVolume,10)/100,n=parseInt(e.voiceVolume,10)/100;(Number.isNaN(t)||t<0||t>1)&&(d("Music volume must be between 0 and 100"),process.exit(c.INVALID_INPUT)),(Number.isNaN(n)||n<0||n>2)&&(d("Voice volume must be between 0 and 200"),process.exit(c.INVALID_INPUT));let r=e.format,o=r==="human"?er("Mixing audio...").start():null,i=[{url:e.video,role:"video"}];e.music&&i.push({url:e.music,role:"background",volume:t*5}),e.voice&&i.push({url:e.voice,role:"voice",volume:n*2});try{let a=await wo({operation:"add-to-video",inputs:i,options:{musicVolume:t,voiceVolume:n}});if(!e.wait){o?.stop(),tr(a,r);return}o&&(o.text=`Processing (ID: ${a.requestId})...`);let s=await Z(()=>Sn(a.requestId),120,3e3);if(o?.stop(),s.status==="failed"&&(d(s.error||"Audio mixing failed"),process.exit(c.GENERAL_ERROR)),tr(s,r),e.output){if(!s.outputUrl)throw new Error("Audio mix completed without an output URL");let l=r==="human"?er("Downloading...").start():null;await H(s.outputUrl,e.output),l?.stop(),r==="human"&&C(`Saved to: ${e.output}`)}}catch(a){o?.stop(),d(a instanceof Error?a.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),ju=new nr("status").description("Check status of an audio mix request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{let n=t.format==="human"?er("Checking status...").start():null;try{let r=await Sn(e);n?.stop(),tr(r,t.format)}catch(r){n?.stop(),d(r instanceof Error?r.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),ia=new nr("mix").description("Audio mixing commands").addCommand(qu).addCommand(ju);import{Command as or}from"commander";import Ku from"ora";import{readFileSync as Mu}from"fs";var aa=500,sa=1e4,zt=100,da=1e4,ca=1e3,ua=["duration_s","idempotency_key","narration","schema_version","video_description"],Fu=["end_s","id","start_s","text","words"],Vu=["end","id","start","text"],Gu=["description","end_s","id","start_s"];function ma(e){let t=ga(e);if(fa(t),gt(t,ua,""),t.duration_s<3)throw new Error("Music request duration_s must be between 3 and 600");return t}function pa(e){let t=ga(e);fa(t),gt(t,[...ua,"visual_event"],"");let n=t.visual_event;if(!Xt(n))throw new Error("SFX request visual_event is required");if(gt(n,Gu,"visual_event"),!Ce(n.description))throw new Error("SFX request visual_event.description is required");if(!Ce(n.id)||!Ie(n.start_s))throw new Error("SFX request visual_event requires id and start_s");if(n.end_s!==void 0&&(!Ie(n.end_s)||n.end_s<n.start_s))throw new Error("SFX request visual_event.end_s must be after start_s");return t}function ga(e){try{let t=JSON.parse(Mu(e,"utf8"));if(!Xt(t))throw new Error("request must be a JSON object");return t}catch(t){throw new Error(`Cannot read audio request ${e}: ${t instanceof Error?t.message:String(t)}`)}}function fa(e){if(e.schema_version!==1)throw new Error("Audio request schema_version must be 1");if(!Ce(e.video_description))throw new Error("Audio request video_description is required");if(!Ie(e.duration_s)||e.duration_s<.5||e.duration_s>600)throw new Error("Audio request duration_s must be between 0.5 and 600");if(!Array.isArray(e.narration))throw new Error("Audio request narration must be an array");if(e.narration.length>aa)throw new Error(`Audio request narration holds at most ${aa} lines`);if(e.narration.forEach(Bu),e.idempotency_key!==void 0&&!Ce(e.idempotency_key))throw new Error("Audio request idempotency_key must be a non-empty string")}function Bu(e,t){let n=`narration.${t}`;if(!Xt(e))throw new Error(`Audio request ${n} must be an object`);if(gt(e,Fu,n),!Ce(e.id)||e.id.length>zt)throw new Error(`Audio request ${n}.id is required (1-${zt} characters)`);if(!Ce(e.text)||e.text.trim().length>da)throw new Error(`Audio request ${n}.text is required (1-${da} characters)`);if(la(e.start_s,`${n}.start_s`),la(e.end_s,`${n}.end_s`),Ie(e.start_s)&&Ie(e.end_s)&&e.end_s<e.start_s)throw new Error(`Audio request ${n}.end_s must be greater than or equal to ${n}.start_s`);if(e.words!==void 0){if(!Array.isArray(e.words)||e.words.length>sa)throw new Error(`Audio request ${n}.words must be an array of at most ${sa} entries`);e.words.forEach((r,o)=>{Wu(r,`${n}.words.${o}`)})}}function Wu(e,t){if(!Xt(e))throw new Error(`Audio request ${t} must be an object`);if(gt(e,Vu,t),!Ce(e.text)||e.text.trim().length>ca)throw new Error(`Audio request ${t}.text is required (1-${ca} characters)`);if(!Ie(e.start)||!Ie(e.end))throw new Error(`Audio request ${t} requires numeric start and end seconds`);if(e.end<e.start)throw new Error(`Audio request ${t}.end must be greater than or equal to ${t}.start`);if(e.id!==void 0&&(!Ce(e.id)||e.id.length>zt))throw new Error(`Audio request ${t}.id must be 1-${zt} characters`)}function la(e,t){if(e!==void 0&&!Ie(e))throw new Error(`Audio request ${t} must be a non-negative number`)}function gt(e,t,n){let r=Object.keys(e).filter(i=>!t.includes(i));if(r.length===0)return;let o=n?`${n} `:"";throw new Error(`Audio request ${o}has unknown field(s): ${r.join(", ")}. Allowed: ${t.join(", ")}`)}function Xt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ce(e){return typeof e=="string"&&e.trim().length>0}function Ie(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function rr(e,t){if(t==="json"){let{cost:n,...r}=e;m(r);return}if(t==="quiet"){console.log(e.audioUrl??e.requestId);return}g(`Request ID: ${e.requestId}`),g(`Status: ${e.status}`),e.duration&&g(`Duration: ${e.duration}s`),e.audioUrl&&C(`Audio URL: ${e.audioUrl}`),e.cost!==void 0&&g(`Cost: $${e.cost.toFixed(4)}`),e.error&&d(`Error: ${e.error}`)}var Ju=new or("generate").description("Generate music that follows a video's narration and final timing").requiredOption("--request <path>","JSON file with video description, narration, and final timing").option("-o, --output <path>","Output file path").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{!e.wait&&e.output&&(d("--output requires waiting for completion; remove --no-wait"),process.exit(c.INVALID_INPUT));let t;try{t=ma(e.request)}catch(i){d(i instanceof Error?i.message:String(i)),process.exit(c.INVALID_INPUT)}let n=e.format,r=n==="human"?Ku("Generating music for video...").start():null,o;try{let i=await bo(t);if(o=i.requestId,!e.wait){r?.stop(),rr(i,n);return}r&&(r.text=`Processing (ID: ${i.requestId})...`);let a=i.status==="completed"||i.status==="failed"?i:await Z(()=>Rn(i.requestId),180,2e3);if(r?.stop(),a.status==="failed"&&(d(a.error||"Music generation failed"),process.exit(c.GENERAL_ERROR)),e.output){if(!a.audioUrl)throw new Error("Music completed without an audio URL");await H(a.audioUrl,e.output),n==="human"&&C(`Saved to: ${e.output}`),a.output=e.output}rr(a,n)}catch(i){r?.stop(),d(re(i,o),n),process.exit(c.GENERAL_ERROR)}}),zu=new or("status").description("Check status of a music generation request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{rr(await Rn(e),t.format)}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),ha=new or("music").description("Video-aware music generation commands").addCommand(Ju).addCommand(zu);import{Command as ir}from"commander";function ya(e,t){return[...t,e]}var Xu=new ir("create").description("Create a standalone poll").argument("<question>","Poll question").option("--option <text>","Choice (repeat 2-10 times)",ya,[]).option("--type <type>","single, multiple, or word-cloud","single").option("--title <title>","Poll title").option("--team-id <id>","Workspace ID").option("--yes","Approve creation").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to approve poll creation");try{m(await y("createPoll",{approvalReceipt:"cli:--yes",options:t.option.map(n=>({text:n})),pollType:t.type,question:e,teamId:t.teamId,title:t.title}))}catch(n){d(n instanceof Error?n.message:"Poll creation failed"),process.exit(c.GENERAL_ERROR)}}),Hu=new ir("edit").description("Edit a standalone poll").argument("<poll-id>","Poll UUID").option("--question <question>","New question").option("--option <text>","Replacement choice (repeat)",ya).option("--type <type>","single, multiple, or word-cloud").option("--title <title>","Poll title").option("--team-id <id>","Workspace ID").option("--yes","Approve update").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to approve poll update");try{m(await y("editPoll",{approvalReceipt:"cli:--yes",options:t.option?.map(n=>({text:n})),pollId:e,pollType:t.type,question:t.question,teamId:t.teamId,title:t.title}))}catch(n){d(n instanceof Error?n.message:"Poll update failed"),process.exit(c.GENERAL_ERROR)}}),ba=new ir("poll").description("Standalone poll commands").addCommand(Xu).addCommand(Hu);import{randomUUID as cr}from"crypto";import{readFile as im}from"fs/promises";import M from"chalk";import{Command as X}from"commander";import{randomUUID as sr}from"crypto";import{readFile as Yu}from"fs/promises";import{Command as Ht}from"commander";var wa=new Ht("edit").description("Apply one atomic draft edit: narration, scene patch/move/remove, composition, or intro/outro card").argument("<project-id>","Presentation-video project UUID or editor slug").requiredOption("--edit <json-or-path>","Edit object as inline JSON or a JSON file path").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key").action(async function(e,t){let n=F(this,t);await Yt("Draft edit failed",async()=>y("editPresentationVideoDraft",{edit:await Qu(n.edit),projectId:e,teamId:n.teamId},n.idempotencyKey??sr()))}),va=new Ht("versions").description("List saved presentation-video draft versions").argument("<project-id>","Presentation-video project UUID or editor slug").option("--before-version <number>","Continue below this version number",ar(1)).option("--limit <number>","Maximum versions",ar(1,100)).option("--team-id <id>","Workspace ID override").action(async function(e,t){let n=F(this,t);await Yt("Version list failed",()=>y("listPresentationVideoVersions",{beforeVersion:n.beforeVersion,limit:n.limit,projectId:e,teamId:n.teamId}))}),xa=new Ht("restore").description("Restore a saved draft version as a new version").argument("<project-id>","Presentation-video project UUID or editor slug").argument("<version-number>","Version number",ar(1)).option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key").action(async function(e,t,n){let r=F(this,n);await Yt("Version restore failed",()=>y("restorePresentationVideoVersion",{projectId:e,teamId:r.teamId,versionNumber:t},r.idempotencyKey??sr()))}),ka=new Ht("refresh").description("Refresh deck-backed scenes from the latest presentation version").argument("<project-id>","Presentation-video project UUID or editor slug").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key").action(async function(e,t){let n=F(this,t);await Yt("Slide refresh failed",()=>y("refreshPresentationVideoSlides",{projectId:e,teamId:n.teamId},n.idempotencyKey??sr()))});async function Qu(e){let t=e.trim(),n=t.startsWith("{")?t:await Yu(t,"utf8"),r=JSON.parse(n);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("--edit must contain one JSON object.");return r}function ar(e,t=Number.MAX_SAFE_INTEGER){return n=>{let r=Number(n);if(!Number.isInteger(r)||r<e||r>t)throw new Error(`Expected an integer between ${e} and ${t}.`);return r}}async function Yt(e,t){try{m(await t())}catch(n){d(n instanceof Error?n.message:e),process.exit(c.GENERAL_ERROR)}}import{randomUUID as Zu}from"crypto";import{Command as em}from"commander";var tm=["basic","standard","premium"],Ca=new em("presenter").description("Set one scene to a different avatar/look or preset, or restore the project default").argument("<project-id>","Presentation video project ID").argument("<slide-id>","Slide or intro/outro scene ID").option("--avatar-id <id>","Exact avatar/look ID from presenter list").option("--cast-preset-id <id>","Saved cast preset ID").option("--no-apply-preset-voice","Preserve this scene's current voice instead of applying the preset voice").option("--inherit","Remove the override and inherit the project default").option("--render-tier <tier>","Avatar render tier: basic, standard, or premium").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key for this update").action(async function(e,t,n){let r=F(this,n);try{if(+!!r.avatarId+ +!!r.castPresetId+ +(r.inherit===!0)!==1)throw new Error("Pass exactly one of --avatar-id, --cast-preset-id, or --inherit.");if(r.renderTier&&!r.avatarId)throw new Error("--render-tier can only be used with --avatar-id.");if(r.renderTier&&!tm.includes(r.renderTier))throw new Error("--render-tier must be basic, standard, or premium.");m(await y("setPresentationVideoScenePresenter",{applyPresetVoice:r.castPresetId?r.applyPresetVoice:void 0,avatarId:r.avatarId,castPresetId:r.castPresetId,inherit:r.inherit,projectId:e,renderTier:r.renderTier,slideId:t,teamId:r.teamId},nm(r.idempotencyKey)))}catch(o){d(o instanceof Error?o.message:"Scene presenter update failed"),process.exit(c.GENERAL_ERROR)}});function nm(e){return e||Zu()}import{Command as dr}from"commander";var Ia=new dr("inspect").description("Read a presentation-video project and its ordered scene timeline").argument("<project-id>","Presentation-video project UUID or editor slug").option("--team-id <id>","Workspace ID override").action(async function(e,t){let n=F(this,t);try{m(await y("getPresentationVideoProject",{projectId:e,teamId:n.teamId}))}catch(r){d(r instanceof Error?r.message:"Project read failed"),process.exit(c.GENERAL_ERROR)}}),rm=new dr("list").description("List generated clips and uploaded recordings usable in a presentation video").argument("<project-id>","Target presentation-video project UUID or slug").option("--cursor <cursor>","Opaque cursor from the previous page").option("--limit <number>","Maximum clips to return",om).option("--query <text>","Filter clips by title").option("--team-id <id>","Workspace ID override").action(async function(e,t){let n=F(this,t);try{m(await y("listReusableVideoClips",{cursor:n.cursor,limit:n.limit,projectId:e,query:n.query,teamId:n.teamId}))}catch(r){d(r instanceof Error?r.message:"Clip list failed"),process.exit(c.GENERAL_ERROR)}}),Ra=new dr("library").description("Reusable generated clips and uploaded recordings").addCommand(rm);function om(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>100)throw new Error("--limit must be an integer between 1 and 100.");return t}var am=new X("status").description("Check a presentation generation run").argument("<run-id>","Run ID returned by presentation generation").option("--team-id <id>","Workspace ID override").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("createSlides",e,t.teamId);if(t.format==="json"){m(n);return}if(t.format==="quiet"){console.log(n.status);return}g(`Status: ${n.status}`),g(n.message),n.progress!==null&&g(`Progress: ${n.progress}%`),n.error&&d(oe(n.error))}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),sm=new X("transform").description("Transform an uploaded PowerPoint import for review").argument("<import-id>","PowerPoint import ID returned by Mindframes").option("--idempotency-key <key>","Stable retry key").action(async function(e,t){let n=F(this,t);try{let r=await y("transformPresentationImport",{importId:e},n.idempotencyKey);m(r)}catch(r){d(r instanceof Error?r.message:"Transform failed"),process.exit(c.GENERAL_ERROR)}}),dm=new X("status").description("Read a PowerPoint import run").argument("<run-id>","Run ID returned by PowerPoint import").option("--team-id <id>","Workspace ID override").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("importPowerPoint",e,t.teamId);t.format==="json"?m(n):t.format==="quiet"?console.log(n.status):(g(`Status: ${n.status}`),g(n.message),n.error&&d(oe(n.error)))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),Sa=new X("import").description("Import a PowerPoint through the review-gated reconstruction pipeline").option("--file <path>","Path to the .pptx to import").option("--filename <name>","Override the uploaded filename").option("--mode <mode>","Import mode: preserve or rebrand","preserve").option("--branding-id <id>","Saved brand ID (required for rebrand mode)").option("--source-chat-id <id>","Associate the import with an existing chat").option("--title <title>","Presentation title").option("--idempotency-key <key>","Stable retry key").action(async e=>{if(!e.file){Sa.help();return}e.file.toLowerCase().endsWith(".pptx")||(d("PowerPoint import requires a .pptx file."),process.exit(c.INVALID_INPUT));try{let t=await ue(e.file),n=await y("importPowerPoint",{brandingId:e.brandingId,filename:e.filename??t.name,mode:e.mode,sourceChatId:e.sourceChatId,sourceUrl:t.url,title:e.title},e.idempotencyKey??cr());m(n)}catch(t){d(t instanceof Error?t.message:"Import failed"),process.exit(c.GENERAL_ERROR)}}).addCommand(sm).addCommand(dm),cm=new X("speaker-notes-status").description("Check a speaker-notes generation run").argument("<run-id>","Run ID returned by speaker-notes generation").option("--team-id <id>","Workspace ID override").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("generateSpeakerNotes",e,t.teamId);t.format==="json"?m(n):t.format==="quiet"?console.log(n.status):(g(`Status: ${n.status}`),g(n.message))}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),lm=new X("video-narration-status").description("Check a presentation-video narration regeneration run").argument("<run-id>","Run ID returned by video-narration").option("--team-id <id>","Workspace ID override").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await T("regeneratePresentationVideoNarration",e,t.teamId);t.format==="json"?m(n):t.format==="quiet"?console.log(n.status):(g(`Status: ${n.status}`),g(n.message))}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),um=new X("status").description("Read a presentation-video MP4 render run").argument("<run-id>","Run ID returned by presentation video").option("--team-id <id>","Workspace ID override").action(async function(e,t){let n=F(this,t);try{m(await T("createPresentationVideo",e,n.teamId))}catch(r){d(r instanceof Error?r.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),mm=new X("prepare").description("Create or reuse a presentation-video project for a presentation").argument("<presentation-id>","Presentation ID, document ID, or slug").option("--force-new","Create a fresh video project even if the current presentation version already has one").option("--narrate","Also generate the narration the project is missing (costs credits; requires --yes)").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key for this prepare request").option("--yes","Confirm the narration charge when --narrate is used").action(async function(e,t){let n=F(this,t);if(n.narrate&&!n.yes)return d("Pass --yes to confirm. --narrate generates speaker notes and costs credits.");try{m(await y("preparePresentationVideo",{forceNew:n.forceNew,narrate:n.narrate,presentationId:e,teamId:n.teamId},n.idempotencyKey??cr()))}catch(r){d(r instanceof Error?r.message:"Prepare failed"),process.exit(c.GENERAL_ERROR)}}),pm=new X("status").description("Read a presentation-video narration run").argument("<run-id>","Run ID returned by presentation video narrate").option("--team-id <id>","Workspace ID override").action(async function(e,t){let n=F(this,t);try{m(await T("ensurePresentationVideoNarration",e,n.teamId))}catch(r){d(r instanceof Error?r.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),gm=new X("narrate").description("Generate the narration a presentation-video project is still missing").argument("<project-id>","Presentation video project ID").option("--no-wait","Return immediately with the durable run ID").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key for this narration request").option("--yes","Confirm the narration charge").action(async function(e,t){let n=F(this,t);if(!n.yes)return d("Pass --yes to confirm. Generating narration costs credits.");try{let r=await y("ensurePresentationVideoNarration",{projectId:e,teamId:n.teamId},n.idempotencyKey??cr());if(n.wait===!1||r.runStatus==="completed"){m(r);return}m(r),await lr(r.runId,"presentation video narrate status",()=>Et(r.runId))}catch(r){d(r instanceof Error?r.message:"Narration failed"),process.exit(c.GENERAL_ERROR)}}).addCommand(pm),fm=new X("settings").description("Update saved presentation-video render settings").argument("<project-id>","Presentation video project ID").option("--settings <json-or-path>","Settings patch as JSON or a path to a JSON file").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key for this settings update").option("--yes","Confirm updating presentation video settings").action(async function(e,t){let n=F(this,t);if(n.settings||(d("Pass --settings <json-or-path> with the patch to apply."),process.exit(c.INVALID_INPUT)),!n.yes)return d("Pass --yes to confirm updating presentation video settings.");try{m(await y("updatePresentationVideoSettings",{projectId:e,settings:await $a(n.settings),teamId:n.teamId},n.idempotencyKey))}catch(r){d(r instanceof Error?r.message:"Settings update failed"),process.exit(c.GENERAL_ERROR)}}),hm=new X("video").description("Create an MP4 video from a presentation").argument("[presentation-id]","Presentation ID, document ID, or slug").option("--project-id <id>","Advanced: render an already-configured presentation video project").option("--settings <json-or-path>","Settings patch as JSON or a path to a JSON file; only valid with presentation-id").option("--force-new","Create a fresh video project even if the current presentation version already has one").option("--force-rerender","Start a new MP4 render even when the current project fingerprint has a completed render").option("--render-engine <engine>","Renderer for this MP4 only: remotion (Standard) or hyperframes (Premium)").option("--team-id <id>","Workspace ID override").option("--idempotency-key <key>","Stable retry key for this render request").option("--yes","Confirm starting the MP4 render").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to confirm presentation video rendering.");try{if(!e&&!t.projectId)throw new Error("Pass a presentation id or --project-id.");if(e&&t.projectId)throw new Error("Pass either presentation id or --project-id, not both.");if(t.projectId&&(t.settings||t.forceNew))throw new Error("--settings and --force-new require a presentation id, not --project-id.");if(t.renderEngine&&t.renderEngine!=="remotion"&&t.renderEngine!=="hyperframes")throw new Error("--render-engine must be remotion or hyperframes.");m(await y("createPresentationVideo",{forceNew:t.forceNew,forceRerender:t.forceRerender,presentationId:e,projectId:t.projectId,renderEngine:t.renderEngine,settings:t.settings?await $a(t.settings):void 0,teamId:t.teamId},t.idempotencyKey))}catch(n){let r=n instanceof Error?n.message:"Render failed";d(r);let o=zr({binary:u.commands[0],message:r,projectId:t.projectId});o&&Nr(o),process.exit(c.GENERAL_ERROR)}}).addCommand(mm).addCommand(gm).addCommand(Ia).addCommand(wa).addCommand(Ca).addCommand(ka).addCommand(xa).addCommand(fm).addCommand(um).addCommand(va);async function $a(e){let t=e.trim(),n=t.startsWith("{")?t:await im(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("--settings must be a JSON object.");return r}function ym(e,t){return[...t,e]}var bm=new X("speaker-notes").description("Generate or regenerate persisted presentation speaker notes").argument("<presentation-id>","Presentation ID or slug").option("--mode <mode>","ensure or regenerate","ensure").option("--style <style>","concise or detailed","concise").option("--instructions <text>","Instructions for every selected slide").option("--language <language>","Output language").option("--slide-id <id>","Target one slide (repeatable)",ym,[]).option("--no-follow","Return immediately with the durable run ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{if(!["ensure","regenerate"].includes(t.mode))throw new Error("--mode must be ensure or regenerate");if(!["concise","detailed"].includes(t.style))throw new Error("--style must be concise or detailed");let n=await ro(e,{instructions:t.instructions,language:t.language,mode:t.mode,slideIds:t.slideId.length?t.slideId:void 0,style:t.style});if(t.format==="json"||!t.follow){m(n);return}g(`Speaker notes run: ${n.runId}`),await lr(n.runId,"presentation speaker-notes-status",()=>Et(n.runId))}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),wm=new X("video-narration").description("Regenerate one slide narration in a presentation video draft").argument("<project-id>","Presentation video project ID").requiredOption("--slide-id <id>","Slide ID in the video draft").option("--instructions <text>","Optional regeneration instructions").option("--no-follow","Return immediately with the durable run ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await oo(e,{instructions:t.instructions,slideId:t.slideId});if(t.format==="json"||!t.follow){m(n);return}g(`Narration run: ${n.runId}`),await lr(n.runId,"presentation video-narration-status",()=>Et(n.runId))}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}});async function lr(e,t,n){let r=null;try{r=await xm(await n())}catch(o){let i=o instanceof Error&&o.message.trim()?o.message.trim():"the event stream ended unexpectedly";j(`Stopped following run ${e}: ${i}. The run is unaffected \u2014 check it with '${u.commands[0]} ${t} ${e}'.`);return}if(r)throw new Error(`Run ${e} ${r.status}: ${r.message} Inspect it with '${u.commands[0]} ${t} ${e}'.`)}function vm(e){let t=e.eventType;if(t==="run.completed"||t==="durable_run.completed")return"completed";let n=t==="run.failed"||t==="durable_run.failed"?"failed":t==="run.cancelled"||t==="durable_run.cancelled"?"cancelled":null;return n?{message:e.payload?.message?.trim()||e.message?.trim()||"the run reported no error message",status:n}:null}async function xm(e){let t=e.body?.getReader();if(!t)throw new Error("Speaker notes event stream is unavailable");let n=new TextDecoder,r="",o=null;for(;;){let{done:i,value:a}=await t.read();r+=n.decode(a,{stream:!i});let s=r.split(`
|
|
115
|
+
|
|
116
|
+
`);r=s.pop()??"";for(let l of s){let f=l.split(`
|
|
117
|
+
`).find(v=>v.startsWith("data:"))?.slice(5).trim();if(!f)continue;let p=JSON.parse(f);p.eventType?.startsWith("slide.")&&g(`${p.eventType}${p.payload?.slideId?` \xB7 ${p.payload.slideId}`:""}`);let w=vm(p);w==="completed"?o=null:w&&(o=w)}if(i)return o}}var ur=new X("presentation").description("Create an MP4 video from a finished presentation, plus speaker notes, PowerPoint import, and run status").addCommand(am).addCommand(Sa).addCommand(bm).addCommand(cm).addCommand(hm).addCommand(wm).addCommand(lm);ur.addHelpText("after",`
|
|
118
|
+
${M.bold("Deck to MP4:")}
|
|
119
|
+
$ ${u.commands[0]} presentation video prepare <slug> ${M.gray("# create/reuse the video project (free)")}
|
|
120
|
+
$ ${u.commands[0]} presentation video narrate <project-id> --yes ${M.gray("# fill in missing narration")}
|
|
121
|
+
$ ${u.commands[0]} presentation video inspect <project-id> ${M.gray("# review the scene timeline")}
|
|
122
|
+
$ ${u.commands[0]} presentation video <slug> --yes ${M.gray("# start the MP4 render")}
|
|
123
|
+
$ ${u.commands[0]} presentation video status <run-id> ${M.gray("# follow the render")}
|
|
124
|
+
|
|
125
|
+
${M.bold("Voice and avatar defaults:")}
|
|
126
|
+
${M.gray("# prepare picks the narration voice for you \u2014 the one this user last")}
|
|
127
|
+
${M.gray("# chose if it is still ready, otherwise the first ready voice \u2014 and")}
|
|
128
|
+
${M.gray("# reports it. Show which voice was selected and offer to change it")}
|
|
129
|
+
${M.gray("# instead of interviewing the user about voices. Every voice in")}
|
|
130
|
+
${M.gray("# avatar options carries a previewUrl audio sample they can hear.")}
|
|
131
|
+
${M.gray('# No avatar is chosen, on purpose: "slides with a voiceover" is the')}
|
|
132
|
+
${M.gray("# normal outcome, so presenter: null is finished, not misconfigured.")}
|
|
133
|
+
${M.gray("# Ask whether they want a presenter; do not assume either way.")}
|
|
134
|
+
$ ${u.commands[0]} avatar options ${M.gray("# real voice and avatar ids + previews")}
|
|
135
|
+
$ ${u.commands[0]} presentation video settings <project-id> --yes --settings '{"voiceId":"<id>"}'
|
|
136
|
+
$ ${u.commands[0]} presentation video settings <project-id> --yes --settings '{"avatarId":"<id>"}'
|
|
137
|
+
|
|
138
|
+
${M.bold("Before rendering:")}
|
|
139
|
+
${M.gray("# The render costs credits and is what the user will share; everything")}
|
|
140
|
+
${M.gray("# before it is free and undoable. Show the narration text, the voice, the")}
|
|
141
|
+
${M.gray("# presenter (or none), music, format and captions, and get an explicit")}
|
|
142
|
+
${M.gray("# yes. --yes is your intent, not the user's consent.")}
|
|
143
|
+
$ ${u.commands[0]} presentation video inspect <project-id> ${M.gray("# narration text + settings to show")}
|
|
144
|
+
|
|
145
|
+
${M.bold("See also:")}
|
|
146
|
+
${M.gray("# Building a video from scratch instead of from a deck")}
|
|
125
147
|
$ ${u.commands[0]} video --help
|
|
126
|
-
`);import{writeFile as
|
|
127
|
-
${
|
|
128
|
-
${
|
|
148
|
+
`);import{writeFile as km}from"fs/promises";import ft from"chalk";import{Command as Cm}from"commander";import Im from"ora";var mr=new Cm("scrape").description("Extract content from a URL").argument("<url>","URL to scrape").option("--team-id <id>","Workspace ID").option("-o, --output <path>","Save content to file").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{let n=t.format,r=n==="human"?Im("Scraping URL...").start():null;try{let o=await Co(e,t.teamId);r?.stop(),(!o.success||!o.data)&&(d(o.error||"Failed to scrape URL"),process.exit(c.GENERAL_ERROR));let i=o.data;if(t.output&&(await km(t.output,i.content,"utf-8"),n==="human"&&C(`Content saved to: ${t.output}`)),n==="json"){let{cost:a,...s}=i;m(s);return}if(n==="quiet"){console.log(i.content);return}i.title&&(console.log(),console.log(`Title: ${i.title}`)),i.metadata?.description&&console.log(`Description: ${i.metadata.description}`),console.log(`URL: ${i.url}`),console.log(`Tokens: ~${i.metadata?.tokenUsage?.toLocaleString()||"unknown"}`),i.warning&&j(i.warning),t.output||(console.log(),console.log("--- Content ---"),console.log(i.content)),i.cost&&i.cost>0&&g(`Cost: $${i.cost.toFixed(6)}`)}catch(o){r?.stop(),d(o instanceof Error?o.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}});mr.addHelpText("after",`
|
|
149
|
+
${ft.bold("Examples:")}
|
|
150
|
+
${ft.gray("# Pull the readable content of a web page")}
|
|
129
151
|
$ ${u.commands[0]} scrape https://example.com/post
|
|
130
152
|
|
|
131
|
-
${
|
|
132
|
-
${
|
|
153
|
+
${ft.bold("See also:")}
|
|
154
|
+
${ft.gray("# Local files and documents, not just URLs")}
|
|
133
155
|
$ ${u.commands[0]} content extract ./paper.pdf
|
|
134
156
|
|
|
135
|
-
${
|
|
157
|
+
${ft.gray("# Spoken words out of audio or video")}
|
|
136
158
|
$ ${u.commands[0]} transcript --help
|
|
137
|
-
`);import
|
|
138
|
-
${
|
|
159
|
+
`);import pr from"chalk";import{Command as ht}from"commander";function Qt(e,t){t!=="quiet"&&m(e)}var Rm=new ht("web").description("Search current public web sources").argument("<query>","Search query").option("--team-id <id>","Workspace ID").option("--max-results <count>","Maximum results","5").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await y("searchInternet",{maxResults:Number.parseInt(t.maxResults,10),query:e,teamId:t.teamId});Qt(n,t.format)}catch(n){d(n instanceof Error?n.message:"Search failed"),process.exit(c.GENERAL_ERROR)}}),Sm=new ht("news").description("Search recent news").argument("<topic>","News topic").option("--team-id <id>","Workspace ID").option("--timeframe <value>","Timeframe hint").option("--max-results <count>","Maximum results","6").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await y("getNews",{maxResults:Number.parseInt(t.maxResults,10),teamId:t.teamId,timeframe:t.timeframe,topic:e});Qt(n,t.format)}catch(n){d(n instanceof Error?n.message:"News search failed"),process.exit(c.GENERAL_ERROR)}});function Ta(e){let t=e?.trim().toLowerCase();if(!(!t||t==="any"||t==="all"))return t==="web"||t==="stock"?[t]:void 0}var $m=new ht("images").description("Search images across the web and licensed stock").argument("<query>","Image search query").option("--team-id <id>","Workspace ID").option("--max-results <count>","Maximum results","10").option("--aspect <aspect>","Aspect: any, square, wide, tall","any").option("--source <source>","Catalog: web, stock, or any (default: any)","any").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await y("searchImages",{aspect:t.aspect,maxResults:Number.parseInt(t.maxResults,10),query:e,sources:Ta(t.source),teamId:t.teamId});Qt(n,t.format)}catch(n){d(n instanceof Error?n.message:"Image search failed"),process.exit(c.GENERAL_ERROR)}}),Tm=new ht("video").description("Search video across the web and licensed stock").argument("<query>","Video search query").option("--team-id <id>","Workspace ID").option("--max-results <count>","Maximum results","10").option("--source <source>","Catalog: web, stock, or any (default: any)","any").option("--orientation <value>","Orientation: landscape, portrait, square, any","any").option("--license <value>","License: free, premium, any","any").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{let n=await y("searchStockVideo",{license:t.license,maxResults:Number.parseInt(t.maxResults,10),orientation:t.orientation,query:e,sources:Ta(t.source),teamId:t.teamId});Qt(n,t.format)}catch(n){d(n instanceof Error?n.message:"Video search failed"),process.exit(c.GENERAL_ERROR)}}),gr=new ht("search").description("Web, news, image, and stock-video search").addCommand(Rm).addCommand(Sm).addCommand($m).addCommand(Tm);gr.addHelpText("after",`
|
|
160
|
+
${pr.bold("Examples:")}
|
|
139
161
|
$ ${u.commands[0]} search web "state of AI video 2026"
|
|
140
162
|
$ ${u.commands[0]} search news "vaccine approvals"
|
|
141
163
|
|
|
142
|
-
${
|
|
143
|
-
${
|
|
164
|
+
${pr.bold("See also:")}
|
|
165
|
+
${pr.gray("# `search images` and `search video` overlap with these")}
|
|
144
166
|
$ ${u.commands[0]} image search --help
|
|
145
167
|
$ ${u.commands[0]} video find --help
|
|
146
|
-
`);import{Command as
|
|
168
|
+
`);import{Command as hr}from"commander";import Em from"ora";function fr(e,t){if(t==="json"){let{cost:n,...r}=e;m(r);return}if(t==="quiet"){console.log(e.audioUrl??e.requestId??e.id);return}g(`Request ID: ${e.requestId||e.id}`),g(`Status: ${e.status}`),e.duration&&g(`Duration: ${e.duration}s`),e.audioUrl&&C(`Audio URL: ${e.audioUrl}`),e.cost!==void 0&&g(`Cost: $${e.cost.toFixed(4)}`),e.error&&d(`Error: ${e.error}`)}var Am=new hr("generate").description("Generate one SFX cue from a video's final facts and visual event").requiredOption("--request <path>","JSON file with video description, narration timings, and visual_event").option("-o, --output <path>","Output file path").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{!e.wait&&e.output&&(d("--output requires waiting for completion; remove --no-wait"),process.exit(c.INVALID_INPUT));let t;try{t=pa(e.request)}catch(i){d(i instanceof Error?i.message:String(i)),process.exit(c.INVALID_INPUT)}let n=e.format,r=n==="human"?Em("Generating sound effect for video...").start():null,o;try{let i=await Io(t);if(o=i.requestId||i.id,!e.wait){r?.stop(),fr(i,n);return}let a=i.requestId||i.id;r&&(r.text=`Processing (ID: ${a})...`);let s=i.status==="completed"||i.status==="failed"?i:await Z(()=>$n(a),60,2e3);if(r?.stop(),s.status==="failed"&&(d(s.error||"Sound effects generation failed"),process.exit(c.GENERAL_ERROR)),e.output){if(!s.audioUrl)throw new Error("Sound effect completed without an audio URL");await H(s.audioUrl,e.output),n==="human"&&C(`Saved to: ${e.output}`)}fr(s,n)}catch(i){r?.stop(),d(re(i,o),n),process.exit(c.GENERAL_ERROR)}}),Om=new hr("status").description("Check status of a sound effects generation request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{fr(await $n(e),t.format)}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Ea=new hr("sfx").description("Video-aware sound effects generation commands").addCommand(Am).addCommand(Om);import{writeFile as Pm}from"fs/promises";import{Command as _m}from"commander";import Lm from"ora";var Aa=new _m("transcript").description("Fetch a YouTube video's transcript").argument("<url>","YouTube URL or 11-character video id").option("--team-id <id>","Workspace ID").option("--language <codes>","Comma-separated language priority list, e.g. 'en,de' or 'asr-en'").option("--no-timestamps","Print plain text without [m:ss] prefixes").option("-o, --output <path>","Save the transcript to a file").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{let n=t.format,r=n==="human"?Lm("Fetching transcript...").start():null;try{let o=await ko(e,t.teamId,t.language);r?.stop();let i=t.timestamps?o.cues.map(a=>`[${a.timestamp}] ${a.text}`).join(`
|
|
147
169
|
`):o.cues.map(a=>a.text).join(`
|
|
148
|
-
`);if(t.output&&(await
|
|
149
|
-
`);for(let i of o){let a=i.match(/pts_time:([\d.]+)/);if(a){let s=parseFloat(a[1]);s-r[r.length-1]>=1.5&&r.push(s)}}return r}function
|
|
150
|
-
`),x=
|
|
151
|
-
Results saved to: ${r}`)}});import{mkdir as Rm}from"fs/promises";import{join as Sm}from"path";import{Command as ut}from"commander";import Ea from"ora";var $m=5e3,Tm=120,Ta=5;function Em(e,t){return[...t,e]}function Am(e,t){try{let n=new URL(e);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error;return n.toString()}catch{throw new Error(`${t} must be a public HTTP(S) URL`)}}function Aa(e){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))throw new Error("Source video id must be a UUID");return e}function Om(e){if(e.mode&&!["speed","precision"].includes(e.mode))throw new Error("Lip-sync mode must be speed or precision");return{audioUrl:Am(e.audioUrl,"Audio URL"),...e.mode?{mode:e.mode}:{},sourceVideoId:Aa(e.sourceVideoId)}}function Pm(e){let t=[],n=new Set;for(let o of e.targetLanguage){let i=o.trim(),a=i.toLocaleLowerCase("en-US");!i||n.has(a)||(n.add(a),t.push(i))}if(t.length===0)throw new Error("Provide at least one target language");if(t.length>Ta)throw new Error(`Provide at most ${Ta} target languages`);if(t.find(o=>o.length<2||o.length>40))throw new Error("Target languages must be between 2 and 40 characters");return{...e.captions?{captions:!0}:{},sourceVideoId:Aa(e.sourceVideoId),targetLanguages:t}}function _m(e){return e.error||e.status==="failed"||e.status==="cancelled"?"failed":e.done||e.status==="completed"?"completed":e.status==="in_progress"||e.status==="processing"?"processing":"pending"}function cr(e){return{requestId:e.runId,status:_m(e),...e.entity?.url?{videoUrl:e.entity.url}:{},...e.output?{output:e.output}:{},...e.error?.message?{error:e.error.message}:{}}}function Oa(e){return{requestId:e.runId,status:"pending"}}async function Pa(e,t){return Y(async()=>cr(await T(e,t)),Tm,$m)}function Fe(e,t){if(t==="json"){p(e);return}if(t==="quiet"){console.log(e.videoUrl??e.requestId);return}f(`Request ID: ${e.requestId}`),f(`Status: ${e.status}`),e.videoUrl&&C(`Video URL: ${e.videoUrl}`),e.error&&d(`Error: ${e.error}`)}function Lm(e){return Array.isArray(e?.languages)?e.languages.filter(t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t;return typeof n.language=="string"&&(n.status==="completed"||n.status==="failed")&&typeof n.videoId=="string"&&(n.videoUrl===null||typeof n.videoUrl=="string")}):[]}function Dm(e){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"translation"}.mp4`}function Nm(e,t){let n=Dm(e);if(!t.has(n))return t.add(n),n;let r=n.slice(0,-4),o=2;for(;t.has(`${r}-${o}.mp4`);)o+=1;let i=`${r}-${o}.mp4`;return t.add(i),i}async function Um(e,t){let n=Lm(e.output).filter(i=>i.status==="completed"&&!!i.videoUrl);if(n.length===0)throw new Error("Video translation completed without downloadable results");await Rm(t,{recursive:!0});let r=[],o=new Set;for(let i of n){let a=Sm(t,Nm(i.language,o));await J(i.videoUrl,a),r.push({language:i.language,path:a})}return r}var qm=new ut("status").description("Check a video lip-sync request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{Fe(cr(await T("lipsyncVideo",e)),t.format)}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),_a=new ut("lipsync").description("Re-voice a ready workspace video with a public audio URL").requiredOption("--source-video-id <uuid>","READY workspace video UUID").requiredOption("--audio-url <url>","Public replacement voice audio URL").option("--mode <mode>","Quality mode: speed or precision","speed").requiredOption("-o, --output <path>","Local output video path").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.format==="human"?Ea("Starting video lip-sync...").start():null,n;try{let r=await yo(Om(e));if(n=r.runId,!e.wait){t?.stop(),Fe(Oa(r),e.format);return}t&&(t.text="Waiting for video lip-sync...");let o=await Pa("lipsyncVideo",r.runId);if(o.status==="failed")throw new Error(o.error??"Video lip-sync failed");if(!o.videoUrl)throw new Error("Video lip-sync completed without a video URL");t&&(t.text="Downloading lip-synced video..."),await J(o.videoUrl,e.output),t?.stop(),Fe(o,e.format),e.format==="human"&&C(`Saved to: ${e.output}`)}catch(r){t?.stop(),d(ne(r,n),e.format),process.exit(c.GENERAL_ERROR)}}).addCommand(qm),La=new ut("translate-languages").description("List supported video translation target languages").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{try{let t=await bo();if(e.format==="json")p({languages:t});else for(let n of t)console.log(n)}catch(t){d(t instanceof Error?t.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Mm=new ut("status").description("Check a video translation request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{try{Fe(cr(await T("translateVideo",e)),t.format)}catch(n){d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Da=new ut("translate").description("Translate a ready workspace video into one or more languages").requiredOption("--source-video-id <uuid>","READY workspace video UUID").option("--target-language <language>","Target language (repeatable)",Em,[]).option("--captions","Burn provider-generated captions into translated videos").requiredOption("--output-dir <path>","Directory for translated videos").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.format==="human"?Ea("Starting video translation...").start():null,n;try{let r=await wo(Pm(e));if(n=r.runId,!e.wait){t?.stop(),Fe(Oa(r),e.format);return}t&&(t.text="Waiting for video translations...");let o=await Pa("translateVideo",r.runId);if(o.status==="failed")throw new Error(o.error??"Video translation failed");t&&(t.text="Downloading translated videos...");let i=await Um(o,e.outputDir);if(t?.stop(),e.format==="json")p({...o,downloads:i});else if(e.format==="quiet")for(let a of i)console.log(a.path);else{Fe(o,e.format);for(let a of i)C(`${a.language}: ${a.path}`)}}catch(r){t?.stop(),d(ne(r,n),e.format),process.exit(c.GENERAL_ERROR)}}).addCommand(Mm);async function Gm(){return process.stdin.isTTY?null:new Promise(e=>{let t="",n=!1;process.stdin.setEncoding("utf-8"),process.stdin.on("data",r=>{t+=r}),process.stdin.on("end",()=>{n||(n=!0,e(t.trim()||null))}),process.stdin.on("error",()=>{n||(n=!0,e(null))}),setTimeout(()=>{!n&&!t&&(n=!0,e(null))},500)})}function Bm(e){let t=e?.trim().toLowerCase();if(!(!t||t==="any"||t==="all"))return t==="web"||t==="stock"?[t]:void 0}var Wm=new H("find").description("Find video clips across the web and licensed stock").argument("<query>","Search query").option("-n, --max-results <count>","Maximum number of results","10").option("-o, --orientation <type>","Video orientation: landscape, portrait, square, any","any").option("-l, --license <type>","License type: free, premium, any","free").option("--source <source>","Catalog: web, stock, or any (default: any)","any").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{let{maxResults:n,orientation:r,license:o,format:i}=t,a=i==="human"?Ua("Finding videos...").start():null;try{let s=await uo({query:e,options:{maxResults:parseInt(n,10),orientation:r,license:o,sources:Bm(t.source)}});a?.stop();let l=s.data.results.flatMap(g=>g.results);if(i==="json"){let{totalCost:g,...m}=s.data;p({...s,data:m});return}if(i==="quiet"){l.forEach(g=>{console.log(g.embedUrl||g.previewUrl||g.thumbnailUrl)});return}if(l.length===0){f("No videos found");return}C(`Found ${l.length} videos for "${e}"`),console.log(),l.forEach((g,m)=>{let w=g.kind==="embed";console.log(`[${m+1}] ${g.title}`),console.log(` ${w?"Embed":"URL"}: ${g.embedUrl||g.previewUrl||g.thumbnailUrl}`),console.log(w?` Duration: ${g.duration}s | Embed only \u2014 plays in the host player, do not download`:` Duration: ${g.duration}s | Size: ${g.width}x${g.height}`),console.log(` Provider: ${g.provider}`),console.log()}),f(`Total cost: $${s.data.totalCost.toFixed(4)}`)}catch(s){a?.stop(),d(s instanceof Error?s.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Km=new H("create").description("Generate one video from a pinned storyboard revision").requiredOption("--storyboard-revision <id>","Immutable storyboard revision UUID").option("--source-video <id>","Ready video from an earlier create call to use as base footage").option("--draft","Generate at 480p for a faster draft").option("--team-id <id>","Workspace ID").option("--approval-receipt <receipt>","Receipt returned by the browser confirmation URL; omit on the first call to get that URL").requiredOption("--idempotency-key <key>","Stable invocation key bound into the approval receipt").option("--yes","Approve paid video generation").action(async e=>{if(!e.yes)return d("Pass --yes to approve video generation");try{p(await vo({quality:e.draft?"draft":void 0,sourceVideoId:e.sourceVideo,storyboardRevisionId:e.storyboardRevision,teamId:e.teamId},e.approvalReceipt,e.idempotencyKey))}catch(t){d(t instanceof Error?t.message:"Generation failed"),process.exit(c.GENERAL_ERROR)}});async function qa(e){let t=e==="-"?await Gm():await Vm(e,"utf-8");if(!t?.trim())throw new Error(e==="-"?"No storyboard Markdown was received on stdin":`Storyboard file is empty: ${e}`);return t}async function Ma(e,t={}){if(e)return e.length===1&&e[0]==="none"?[]:Promise.all(e.map(async n=>{let r;try{let v=JSON.parse(n);if(!v||typeof v!="object"||Array.isArray(v))throw new Error("Media binding must be a JSON object");r=v}catch(v){throw new Error(`Invalid --media binding. Pass one JSON object per binding, for example '{"handle":"actress-photo","path":"./actress.jpg","purpose":"identity"}'.`,{cause:v})}let o=de(r.handle),i=de(r.path),a=de(r.fileUrl)??de(r.url),s=de(r.purpose),l=de(r.videoRole),g=de(r.analysisId)??de(r.analysis);if(!o||!i&&!a||!s)throw new Error("Invalid --media binding. handle, purpose, and either path or url are required strings.");if(i&&a)throw new Error("A media binding cannot contain both path and url.");if(i&&s==="source"&&g)throw new Error("A source analysis is bound to the original uploaded URL. Reuse the url/name/mime/size binding printed by 'video reference analyze' instead of uploading path again.");if(i&&!t.uploadIdempotencyKey)throw new Error("Local storyboard media requires the command idempotency key.");let m=i?await se(pt(i),{idempotencyKey:`${t.uploadIdempotencyKey}:media:${o}`}):{name:de(r.name),size:Number(r.size),type:de(r.mime),url:a};if(!m.name||!m.type||!m.url||!Number.isSafeInteger(m.size)||m.size<=0)throw new Error(`URL media binding "${n}" requires name, mime, and positive integer size.`);let w=m.type.startsWith("video/")?"video":m.type.startsWith("audio/")?"audio":m.type.startsWith("image/")?"image":null;if(!w)throw new Error(`Unsupported media type for ${i??a}: ${m.type}`);if(!["source","style","identity","required"].includes(s))throw new Error(`Invalid media purpose: ${s}`);if(l&&!["reference","first-frame","last-frame"].includes(l))throw new Error(`Invalid videoRole: ${l}`);if(l&&w!=="image")throw new Error("videoRole is supported only for image bindings.");return{...g?{analysisId:g}:{},fileUrl:m.url,handle:o,kind:w,mime:m.type,name:m.name,purpose:s,size:m.size,...l?{videoRole:l}:{}}}))}function de(e){return typeof e=="string"&&e.length>0?e:void 0}var Jm=new H("create").description("Create a versioned Markdown video storyboard").requiredOption("--file <path>","Markdown file path, or - for stdin").requiredOption("--duration <seconds>","Exact total duration in seconds").requiredOption("--aspect <ratio>","Output aspect: 9:16, 16:9, or 1:1").option("--title <text>","Artifact label").requiredOption("--idempotency-key <key>","Stable key to reuse when retrying this exact create").option("--media <binding...>",'One JSON binding per asset: {"handle":"actress-photo","path":"./actress.jpg","purpose":"identity"}').option("--team-id <id>","Workspace ID").action(async e=>{try{p(await y("createVideoStoryboard",{aspectRatio:e.aspect,durationSec:Number(e.duration),mediaBindings:await Ma(e.media,{uploadIdempotencyKey:e.idempotencyKey}),storyboardMarkdown:await qa(e.file),teamId:e.teamId,title:e.title},e.idempotencyKey))}catch(t){d(t instanceof Error?t.message:"Storyboard creation failed"),process.exit(c.GENERAL_ERROR)}}),zm=new H("revise").description("Append an immutable revision to a video storyboard").argument("<storyboard-id>","Storyboard UUID").requiredOption("--base-revision <id>","Revision UUID that was edited").requiredOption("--file <path>","Complete Markdown file path, or - for stdin").requiredOption("--duration <seconds>","Exact total duration in seconds").requiredOption("--aspect <ratio>","Output aspect: 9:16, 16:9, or 1:1").option("--title <text>","Replacement artifact label").requiredOption("--idempotency-key <key>","Stable key to reuse when retrying this exact revision").option("--change-summary <text>","Short description of this revision").option("--media <binding...>",'Replace media bindings with one JSON object per asset; use the JSON printed by "video reference analyze" for analyzed source video').option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await y("reviseVideoStoryboard",{aspectRatio:t.aspect,baseRevisionId:t.baseRevision,changeSummary:t.changeSummary,durationSec:Number(t.duration),mediaBindings:await Ma(t.media,{uploadIdempotencyKey:t.idempotencyKey}),storyboardId:e,storyboardMarkdown:await qa(t.file),teamId:t.teamId,title:t.title},t.idempotencyKey))}catch(n){d(n instanceof Error?n.message:"Storyboard revision failed"),process.exit(c.GENERAL_ERROR)}}),Xm=new H("show").description("Read a storyboard; print Markdown unless --json is used").argument("<storyboard-id>","Storyboard UUID").option("--revision <id>","Read one immutable revision UUID").option("--team-id <id>","Workspace ID").option("--json","Print the complete structured response").action(async(e,t)=>{try{let n=await y("readVideoStoryboard",{revisionId:t.revision,storyboardId:e,teamId:t.teamId});if(t.json){p(n);return}console.error(`${n.storyboard.title} \xB7 revision ${n.storyboard.revision.versionNumber} (${n.storyboard.revision.id})`),console.log(n.storyboard.revision.storyboardMarkdown)}catch(n){d(n instanceof Error?n.message:"Storyboard read failed"),process.exit(c.GENERAL_ERROR)}}),Hm=new H("storyboard").description("Create, revise, and read Markdown video storyboards").addCommand(Jm).addCommand(zm).addCommand(Xm),Ym=new H("analyze").description("Upload and analyze a reference video").requiredOption("--file <path>","Local reference video").requiredOption("--idempotency-key <key>","Stable key to reuse when retrying this exact analysis").option("--user-request <text>","What the analysis should focus on").option("--team-id <id>","Workspace ID").option("--no-wait","Return the durable run immediately").option("--json","Print the complete structured result").action(async e=>{try{let t=await se(pt(e.file),{idempotencyKey:`video-reference-analysis:${e.idempotencyKey}:source`});if(!t.type.startsWith("video/"))throw new Error(`Reference analysis requires a video, got ${t.type}`);let n=await xo({idempotencyKey:e.idempotencyKey,sourceUrl:t.url,teamId:e.teamId,userRequest:e.userRequest}),r={analysisId:n.runId,fileUrl:t.url,handle:"source-video",kind:"video",mime:t.type,name:t.name,purpose:"source",size:t.size};if(e.wait===!1){p({...n,binding:r,source:t});return}let o=await ko(n.runId,e.teamId);if(e.json){p({...o,binding:r,source:t});return}let i=o.output?.analysis??{};console.log(typeof i.promptContext=="string"?i.promptContext:JSON.stringify(o.output,null,2)),console.error(`Analysis run: ${n.runId}`),console.error(`Storyboard media JSON: ${JSON.stringify(r)}`)}catch(t){d(t instanceof Error?t.message:"Reference analysis failed"),process.exit(c.GENERAL_ERROR)}}),Qm=new H("status").description("Read a video-reference analysis run").argument("<run-id>","Analysis run UUID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await T("analyzeVideoReference",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status read failed"),process.exit(c.GENERAL_ERROR)}}),Zm=new H("reference").description("Upload and inspect reusable video references").addCommand(Ym).addCommand(Qm),ep=new H("status").description("Read video background status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{p(await T("createVideo",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),tp=new H("inject").description("Inject thumbnail into video (first frame + file icon)").requiredOption("-i, --video <path>","Input video file").requiredOption("-t, --thumbnail <path>","Thumbnail image").option("-o, --output <path>","Output video (default: video-with-thumb.mp4)").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.format,n=t==="human"?Ua("Injecting thumbnail...").start():null;try{let r=pt(e.video),o=pt(e.thumbnail),i=e.output?pt(e.output):r.replace(/\.mp4$/,"-with-thumb.mp4");await lr(r),await lr(o);let a=jm;if(a)try{await lr(a)}catch{a=null}if(!a)try{a=Ht("which ffmpeg",{encoding:"utf8"}).trim()}catch{throw new Error("ffmpeg not found. Install ffmpeg or ffmpeg-static.")}let s=Fm(a,["-i",r],{encoding:"utf8"});if(s.error)throw new Error(`Failed to probe video: ${s.error.message}`);let l=(s.stderr??"").match(/(\d{2,5})x(\d{2,5})/);if(!l)throw new Error("Could not detect video dimensions");let[,g,m]=l;n&&(n.text="Creating thumbnail frame...");let w="/tmp/cc-thumb-frame.mp4";Ht(`${a} -y -loop 1 -i "${o}" -vf "scale=${g}:${m}:force_original_aspect_ratio=decrease,pad=${g}:${m}:(ow-iw)/2:(oh-ih)/2,setsar=1" -t 0.033 -r 30 -c:v libx264 -pix_fmt yuv420p "${w}"`,{stdio:"pipe"}),n&&(n.text="Concatenating with video...");let v="/tmp/cc-concat-video.mp4";if(Ht(`${a} -y -i "${w}" -i "${r}" -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" -map "[v]" -map 1:a -c:v libx264 -preset ultrafast -crf 18 -c:a copy "${v}"`,{stdio:"pipe"}),n&&(n.text="Adding file icon thumbnail..."),Ht(`${a} -y -i "${v}" -i "${o}" -map 0 -map 1 -c copy -c:v:1 png -disposition:v:1 attached_pic "${i}"`,{stdio:"pipe"}),await Na(w,{force:!0}),await Na(v,{force:!0}),n?.stop(),t==="json"){p({success:!0,output:i});return}if(t==="quiet"){console.log(i);return}C(`Thumbnail injected: ${i}`)}catch(r){n?.stop(),d(r instanceof Error?r.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),np=new H("thumbnail").description("Thumbnail operations").addCommand(tp),Yt=new H("video").description("Build a video from scratch \u2014 brief or storyboard to stock and generated footage, translation, lipsync, analysis (for a finished deck, use presentation video)").addCommand(Wm).addCommand(np).addCommand(_a).addCommand(La).addCommand(Da).addCommand(ma).addCommand($a);Yt.addCommand(Km).addCommand(Hm).addCommand(Zm).addCommand(ep);Yt.addHelpText("after",`
|
|
152
|
-
${
|
|
153
|
-
${
|
|
170
|
+
`);if(t.output&&(await Pm(t.output,i,"utf-8"),n==="human"&&C(`Transcript saved to: ${t.output}`)),n==="json"){m(o);return}if(n==="quiet"){console.log(i);return}console.log(),console.log(`Title: ${o.title}`),o.channelName&&console.log(`Channel: ${o.channelName}`),o.durationFormatted&&console.log(`Duration: ${o.durationFormatted}`),console.log(`Language: ${o.language??"unknown"}${o.isAutoGenerated?" (auto-generated)":""}`),console.log(`Words: ${o.wordCount.toLocaleString()}`),console.log(`URL: ${o.url}`),o.truncated&&j("Transcript was truncated to fit the response budget."),t.output||(console.log(),console.log("--- Transcript ---"),console.log(i)),o.totalCost&&o.totalCost>0&&g(`Cost: $${o.totalCost.toFixed(6)}`)}catch(o){r?.stop(),d(o instanceof Error?o.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}});import{mkdir as Dm,writeFile as Oa}from"fs/promises";import{dirname as Nm}from"path";import{Command as Zt}from"commander";import La from"ora";var Pa="en-US-Neural2-C",_a="gemini",Um=new Zt("generate").description("Generate speech from text").requiredOption("-t, --text <text>","Text to convert to speech").requiredOption("-o, --output <path>","Output file path").option("--voice-id <voiceId>","Voice ID (e.g., ElevenLabs: 21m00Tcm4TlvDq8ikWAM)").option("--voice <voice>",`Voice name (default: ${Pa})`).option("-p, --provider <provider>",`Provider: gemini, elevenlabs, openai (default: ${_a})`).option("-m, --model <model>","Model (provider-specific)").option("-s, --speed <speed>","Speech speed 0.1-4.0 (default: 1.0)").option("-l, --lang <lang>","Language or locale hint (for example en-US)").option("--speakers <json>",`Multi-speaker (Gemini, max 2): '[{"name":"Joe","voice":"Kore"},{"name":"Jane","voice":"Puck"}]'`).option("-i, --instructions <text>","Style prompt (OpenAI gpt-4o-mini-tts): tone, accent, speed, emotion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.format,n=t==="human"?La("Generating speech...").start():null,r;e.speed&&(r=parseFloat(e.speed),(Number.isNaN(r)||r<.1||r>4)&&(n?.stop(),d("Speed must be between 0.1 and 4.0"),process.exit(c.INVALID_INPUT)));let o;if(e.speakers)try{o=JSON.parse(e.speakers),(!Array.isArray(o)||o.length===0||o.length>2||o.some(a=>!a||typeof a!="object"||typeof a.name!="string"||!a.name.trim()||typeof a.voice!="string"||!a.voice.trim()))&&(n?.stop(),d("Speakers must be an array with 1-2 name/voice items"),process.exit(c.INVALID_INPUT))}catch{n?.stop(),d(`Invalid --speakers JSON. Example: '[{"name":"Joe","voice":"Kore"}]'`),process.exit(c.INVALID_INPUT)}let i;try{let a=e.voiceId,s=e.voice||Pa,l=e.provider||_a,f={};o&&(f.gemini={speakers:o}),e.instructions&&(f.openai={instructions:e.instructions});let p=await fo({text:e.text,options:{language:e.lang,provider:l,voiceId:a,voice:s,model:e.model,speed:r,providerOptions:Object.keys(f).length>0?f:void 0}});i=p.requestId,n?.stop();let w=e.output.endsWith(`.${p.format}`)?e.output:`${e.output}.${p.format}`;await Dm(Nm(w),{recursive:!0}),await Oa(w,p.audioData);let v=w.replace(/\.[^.]+$/,".txt");if(await Oa(v,e.text,"utf-8"),t==="json"){m({status:"completed",output:w,audioUrl:p.audioUrl,duration:p.duration,provider:p.provider,format:p.format,voice_id:p.voiceId??null,voice:p.voice??s,model:p.model??e.model??null,speed:p.speed??r??1,lang:p.language??e.lang??null,langApplied:p.langApplied??!1,timestamps:p.timestamps??null,words:p.wordTimings??null});return}if(t==="quiet"){console.log(w);return}C(`Saved to: ${w}`),g(`Duration: ${p.duration.toFixed(2)}s`),g(`Provider: ${p.provider}`),g(`Cost: $${p.cost.toFixed(6)}`)}catch(a){n?.stop(),d(re(a,i),t),process.exit(c.GENERAL_ERROR)}}),qm=new Zt("voices").description("List available voices").option("-p, --provider <provider>","Filter by provider: gemini, elevenlabs, openai").option("-f, --format <format>","Output format: human, json","human").action(async e=>{let t=e.format==="human"?La("Fetching voices...").start():null;try{let n=await yo(e.provider);if(t?.stop(),e.format==="json"){m(n.voices);return}if(Array.isArray(n.voices)){let r=e.provider?.toUpperCase()||"VOICES";console.log(),console.log(`${r} Voices:`),console.log("-".repeat(50));for(let o of n.voices)console.log(` ${o.name} (${o.id})`),console.log(` ${o.description}`)}else for(let[r,o]of Object.entries(n.voices))if(!(!o||o.length===0)){console.log(),console.log(`${r.toUpperCase()} Voices:`),console.log("-".repeat(50));for(let i of o)console.log(` ${i.name} (${i.id})`),console.log(` ${i.description}`)}}catch(n){t?.stop(),d(n instanceof Error?n.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),jm=new Zt("status").description("Read speech generation status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").option("-f, --format <format>","Output format: json","json").action(async(e,t)=>{try{m(await T("generateSpeech",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),Da=new Zt("tts").description("Text-to-speech commands").addCommand(Um).addCommand(qm).addCommand(jm);import{execSync as rn,spawnSync as up}from"child_process";import{access as br,readFile as mp,rm as za}from"fs/promises";import{resolve as bt}from"path";import me from"chalk";import{Command as Q}from"commander";import pp from"ffmpeg-static";import Xa from"ora";import{Command as Mm}from"commander";import Fm from"ora";import{execSync as Vm,spawnSync as Be}from"child_process";import{mkdirSync as Na,existsSync as tn,readFileSync as qa,writeFileSync as Ua}from"fs";import{join as _e,basename as Gm}from"path";import{tmpdir as Bm}from"os";function nn(e,t){try{return Vm(t,{stdio:"ignore"}),!0}catch{return!1}}function en(e){let t=Math.floor(e/60),n=Math.floor(e%60),r=Math.round(e%1*10);return`${t}:${String(n).padStart(2,"0")}.${r}`}function Wm(e){let t=Be("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf-8"});return parseFloat(t.stdout.trim())}function Km(e,t){let n=Be("ffmpeg",["-i",e,"-vf",`select='gt(scene,${t})',showinfo`,"-vsync","vfr","-f","null","-"],{encoding:"utf-8",timeout:12e4}),r=[0],o=(n.stderr||"").split(`
|
|
171
|
+
`);for(let i of o){let a=i.match(/pts_time:([\d.]+)/);if(a){let s=parseFloat(a[1]);s-r[r.length-1]>=1.5&&r.push(s)}}return r}function Jm(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o]+.5,a=_e(n,`scene_${String(o+1).padStart(2,"0")}.jpg`);Be("ffmpeg",["-ss",String(i),"-i",e,"-vframes","1","-q:v","2","-y",a],{stdio:"ignore",timeout:3e4}),r.push(a)}return r}function zm(e,t){let n=_e(t,"audio.wav");if(Be("ffmpeg",["-i",e,"-vn","-acodec","pcm_s16le","-ar","16000","-ac","1","-y",n],{stdio:"ignore",timeout:6e4}),!tn(n)||!nn("whisper","which whisper")&&!nn("whisper-cpp","which whisper-cpp"))return null;let o=Be("whisper",[n,"--model","base","--output_format","json","--output_dir",t,"--language","en"],{encoding:"utf-8",timeout:3e5}),i=_e(t,"audio.json");if(!tn(i))return null;try{let a=JSON.parse(qa(i,"utf-8"));return{text:a.text||"",segments:(a.segments||[]).map(s=>({start:s.start,end:s.end,text:s.text?.trim()||""}))}}catch{return null}}function Xm(e,t){let n=qa(e).toString("base64"),r=JSON.stringify({model:t,prompt:"Describe this image in one short sentence (max 15 words). Focus on: what is shown, the setting, key objects or people.",images:[n],stream:!1}),o=Be("curl",["-s","-X","POST","http://localhost:11434/api/generate","-H","Content-Type: application/json","-d",r],{encoding:"utf-8",timeout:6e4});try{return(JSON.parse(o.stdout).response||"").replace(/!!!IMAGE!!!/gi,"").replace(/\[image[^\]]*\]/gi,"").trim()||"Unable to describe frame"}catch{return"Unable to describe frame"}}var ja=new Mm("analyze").description("Analyze a video file: detect scenes, transcribe audio, describe frames").argument("<file>","Path to video file").option("-o, --output <path>","Output directory for analysis results").option("-t, --threshold <number>","Scene detection threshold (0-1, lower = more scenes)","0.3").option("-m, --model <name>","Ollama vision model","moondream").option("--no-vision","Skip frame description (faster)").option("--no-transcribe","Skip audio transcription").option("-f, --output-format <format>","Output format: human, json","human").action(async(e,t)=>{let n=Fm();tn(e)||(console.error(`File not found: ${e}`),process.exit(1)),nn("ffmpeg","which ffmpeg")||(console.error("ffmpeg is required. Install: brew install ffmpeg"),process.exit(1)),t.vision!==!1&&!nn("ollama","which ollama")&&(console.error("ollama is required for vision. Install: brew install ollama"),process.exit(1));let r=t.output||_e(Bm(),`video-analyze-${Date.now()}`);Na(r,{recursive:!0});let o=_e(r,"frames");Na(o,{recursive:!0});let i=parseFloat(t.threshold),a=t.model;n.start("Reading video metadata...");let s=Wm(e);n.succeed(`Video: ${en(s)} (${s.toFixed(1)}s)`),n.start("Detecting scenes...");let l=Km(e,i);n.succeed(`Detected ${l.length} scenes`),n.start("Extracting key frames...");let f=Jm(e,l,o);n.succeed(`Extracted ${f.length} key frames`);let p=null;t.transcribe!==!1&&(n.start("Transcribing audio..."),p=zm(e,r),p?n.succeed(`Transcribed: ${p.segments.length} segments`):n.warn("Transcription skipped (whisper not installed: pip install openai-whisper)"));let w=[];for(let b=0;b<l.length;b++){let $=l[b],x=b<l.length-1?l[b+1]:s,k="";t.vision!==!1&&tn(f[b])&&(n.start(`Describing scene ${b+1}/${l.length}...`),k=Xm(f[b],a),n.succeed(`Scene ${b+1}: ${k}`)),w.push({id:b+1,startTime:$,endTime:x,duration:x-$,framePath:f[b],description:k})}let v={source:e,duration:s,scenes:w,transcript:p};if(t.outputFormat==="json"){let b=JSON.stringify(v,null,2),$=_e(r,"analysis.json");Ua($,b),console.log(b)}else{let b=["# Video Analysis","",`**Source:** ${Gm(e)}`,`**Duration:** ${en(s)} (${s.toFixed(1)}s)`,`**Scenes:** ${w.length}`,"","## Scenes",""];for(let k of w){if(b.push(`### Scene ${k.id} (${en(k.startTime)} - ${en(k.endTime)}) [${k.duration.toFixed(1)}s]`),k.description&&b.push(`**Visual:** ${k.description}`),p?.segments){let R=p.segments.filter(N=>N.end>k.startTime&&N.start<k.endTime);R.length>0&&b.push(`**Audio:** ${R.map(N=>N.text).join(" ").trim()}`)}b.push(`**Frame:** ${k.framePath}`),b.push("")}p?.text&&(b.push("## Full Transcript"),b.push(""),b.push(p.text.trim()),b.push(""));let $=b.join(`
|
|
172
|
+
`),x=_e(r,"analysis.md");Ua(x,$),console.log($),console.log(`
|
|
173
|
+
Results saved to: ${r}`)}});import{mkdir as Hm}from"fs/promises";import{join as Ym}from"path";import{Command as yt}from"commander";import Fa from"ora";var Qm=5e3,Zm=120,Ma=5;function ep(e,t){return[...t,e]}function tp(e,t){try{let n=new URL(e);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error;return n.toString()}catch{throw new Error(`${t} must be a public HTTP(S) URL`)}}function Va(e){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))throw new Error("Source video id must be a UUID");return e}function np(e){if(e.mode&&!["speed","precision"].includes(e.mode))throw new Error("Lip-sync mode must be speed or precision");return{audioUrl:tp(e.audioUrl,"Audio URL"),...e.mode?{mode:e.mode}:{},sourceVideoId:Va(e.sourceVideoId)}}function rp(e){let t=[],n=new Set;for(let o of e.targetLanguage){let i=o.trim(),a=i.toLocaleLowerCase("en-US");!i||n.has(a)||(n.add(a),t.push(i))}if(t.length===0)throw new Error("Provide at least one target language");if(t.length>Ma)throw new Error(`Provide at most ${Ma} target languages`);if(t.find(o=>o.length<2||o.length>40))throw new Error("Target languages must be between 2 and 40 characters");return{...e.captions?{captions:!0}:{},sourceVideoId:Va(e.sourceVideoId),targetLanguages:t}}function op(e){return e.error||e.status==="failed"||e.status==="cancelled"?"failed":e.done||e.status==="completed"?"completed":e.status==="in_progress"||e.status==="processing"?"processing":"pending"}function yr(e){return{requestId:e.runId,status:op(e),...e.entity?.url?{videoUrl:e.entity.url}:{},...e.output?{output:e.output}:{},...e.error?{error:oe(e.error)}:{}}}function Ga(e){return{requestId:e.runId,status:"pending"}}async function Ba(e,t){return Z(async()=>yr(await T(e,t)),Zm,Qm)}function We(e,t){if(t==="json"){m(e);return}if(t==="quiet"){console.log(e.videoUrl??e.requestId);return}g(`Request ID: ${e.requestId}`),g(`Status: ${e.status}`),e.videoUrl&&C(`Video URL: ${e.videoUrl}`),e.error&&d(`Error: ${e.error}`)}function ip(e){return Array.isArray(e?.languages)?e.languages.filter(t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t;return typeof n.language=="string"&&(n.status==="completed"||n.status==="failed")&&typeof n.videoId=="string"&&(n.videoUrl===null||typeof n.videoUrl=="string")}):[]}function ap(e){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"translation"}.mp4`}function sp(e,t){let n=ap(e);if(!t.has(n))return t.add(n),n;let r=n.slice(0,-4),o=2;for(;t.has(`${r}-${o}.mp4`);)o+=1;let i=`${r}-${o}.mp4`;return t.add(i),i}async function dp(e,t){let n=ip(e.output).filter(i=>i.status==="completed"&&!!i.videoUrl);if(n.length===0)throw new Error("Video translation completed without downloadable results");await Hm(t,{recursive:!0});let r=[],o=new Set;for(let i of n){let a=Ym(t,sp(i.language,o));await H(i.videoUrl,a),r.push({language:i.language,path:a})}return r}var cp=new yt("status").description("Check a video lip-sync request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet").action(async function(e,t){let r=F(this,t).format??"human";try{We(yr(await T("lipsyncVideo",e)),r)}catch(o){d(o instanceof Error?o.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Wa=new yt("lipsync").description("Re-voice a ready workspace video with a public audio URL").requiredOption("--source-video-id <uuid>","READY workspace video UUID").requiredOption("--audio-url <url>","Public replacement voice audio URL").option("--mode <mode>","Quality mode: speed or precision","speed").requiredOption("-o, --output <path>","Local output video path").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.format==="human"?Fa("Starting video lip-sync...").start():null,n;try{let r=await $o(np(e));if(n=r.runId,!e.wait){t?.stop(),We(Ga(r),e.format);return}t&&(t.text="Waiting for video lip-sync...");let o=await Ba("lipsyncVideo",r.runId);if(o.status==="failed")throw new Error(o.error??"Video lip-sync failed");if(!o.videoUrl)throw new Error("Video lip-sync completed without a video URL");t&&(t.text="Downloading lip-synced video..."),await H(o.videoUrl,e.output),t?.stop(),We(o,e.format),e.format==="human"&&C(`Saved to: ${e.output}`)}catch(r){t?.stop(),d(re(r,n),e.format),process.exit(c.GENERAL_ERROR)}}).addCommand(cp),Ka=new yt("translate-languages").description("List supported video translation target languages").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{try{let t=await To();if(e.format==="json")m({languages:t});else for(let n of t)console.log(n)}catch(t){d(t instanceof Error?t.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),lp=new yt("status").description("Check a video translation request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet").action(async function(e,t){let r=F(this,t).format??"human";try{We(yr(await T("translateVideo",e)),r)}catch(o){d(o instanceof Error?o.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),Ja=new yt("translate").description("Translate a ready workspace video into one or more languages").requiredOption("--source-video-id <uuid>","READY workspace video UUID").option("--target-language <language>","Target language (repeatable)",ep,[]).option("--captions","Burn provider-generated captions into translated videos").requiredOption("--output-dir <path>","Directory for translated videos").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.format==="human"?Fa("Starting video translation...").start():null,n;try{let r=await Eo(rp(e));if(n=r.runId,!e.wait){t?.stop(),We(Ga(r),e.format);return}t&&(t.text="Waiting for video translations...");let o=await Ba("translateVideo",r.runId);if(o.status==="failed")throw new Error(o.error??"Video translation failed");t&&(t.text="Downloading translated videos...");let i=await dp(o,e.outputDir);if(t?.stop(),e.format==="json")m({...o,downloads:i});else if(e.format==="quiet")for(let a of i)console.log(a.path);else{We(o,e.format);for(let a of i)C(`${a.language}: ${a.path}`)}}catch(r){t?.stop(),d(re(r,n),e.format),process.exit(c.GENERAL_ERROR)}}).addCommand(lp);async function gp(){return process.stdin.isTTY?null:new Promise(e=>{let t="",n=!1;process.stdin.setEncoding("utf-8"),process.stdin.on("data",r=>{t+=r}),process.stdin.on("end",()=>{n||(n=!0,e(t.trim()||null))}),process.stdin.on("error",()=>{n||(n=!0,e(null))}),setTimeout(()=>{!n&&!t&&(n=!0,e(null))},500)})}function fp(e){let t=e?.trim().toLowerCase();if(!(!t||t==="any"||t==="all"))return t==="web"||t==="stock"?[t]:void 0}var hp=new Q("find").description("Find video clips across the web and licensed stock").argument("<query>","Search query").option("-n, --max-results <count>","Maximum number of results","10").option("-o, --orientation <type>","Video orientation: landscape, portrait, square, any","any").option("-l, --license <type>","License type: free, premium, any","free").option("--source <source>","Catalog: web, stock, or any (default: any)","any").option("-f, --format <format>","Output format: human, json, quiet","human").action(async(e,t)=>{let{maxResults:n,orientation:r,license:o,format:i}=t,a=i==="human"?Xa("Finding videos...").start():null;try{let s=await xo({query:e,options:{maxResults:parseInt(n,10),orientation:r,license:o,sources:fp(t.source)}});a?.stop();let l=s.data.results.flatMap(f=>f.results);if(i==="json"){let{totalCost:f,...p}=s.data;m({...s,data:p});return}if(i==="quiet"){l.forEach(f=>{console.log(f.embedUrl||f.previewUrl||f.thumbnailUrl)});return}if(l.length===0){g("No videos found");return}C(`Found ${l.length} videos for "${e}"`),console.log(),l.forEach((f,p)=>{let w=f.kind==="embed";console.log(`[${p+1}] ${f.title}`),console.log(` ${w?"Embed":"URL"}: ${f.embedUrl||f.previewUrl||f.thumbnailUrl}`),console.log(w?` Duration: ${f.duration}s | Embed only \u2014 plays in the host player, do not download`:` Duration: ${f.duration}s | Size: ${f.width}x${f.height}`),console.log(` Provider: ${f.provider}`),console.log()}),g(`Total cost: $${s.data.totalCost.toFixed(4)}`)}catch(s){a?.stop(),d(s instanceof Error?s.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),yp=new Q("create").description("Generate one video from a pinned storyboard revision").requiredOption("--storyboard-revision <id>","Immutable storyboard revision UUID").option("--source-video <id>","Ready video from an earlier create call to use as base footage").option("--draft","Generate at 480p for a faster draft").option("--team-id <id>","Workspace ID").option("--approval-receipt <receipt>","Receipt returned by the browser confirmation URL; omit on the first call to get that URL").requiredOption("--idempotency-key <key>","Stable invocation key bound into the approval receipt").option("--yes","Approve paid video generation").action(async e=>{if(!e.yes)return d("Pass --yes to approve video generation");try{m(await Ao({quality:e.draft?"draft":void 0,sourceVideoId:e.sourceVideo,storyboardRevisionId:e.storyboardRevision,teamId:e.teamId},e.approvalReceipt,e.idempotencyKey))}catch(t){d(t instanceof Error?t.message:"Generation failed"),process.exit(c.GENERAL_ERROR)}});async function Ha(e){let t=e==="-"?await gp():await mp(e,"utf-8");if(!t?.trim())throw new Error(e==="-"?"No storyboard Markdown was received on stdin":`Storyboard file is empty: ${e}`);return t}async function Ya(e,t={}){if(e)return e.length===1&&e[0]==="none"?[]:Promise.all(e.map(async n=>{let r;try{let v=JSON.parse(n);if(!v||typeof v!="object"||Array.isArray(v))throw new Error("Media binding must be a JSON object");r=v}catch(v){throw new Error(`Invalid --media binding. Pass one JSON object per binding, for example '{"handle":"actress-photo","path":"./actress.jpg","purpose":"identity"}'.`,{cause:v})}let o=pe(r.handle),i=pe(r.path),a=pe(r.fileUrl)??pe(r.url),s=pe(r.purpose),l=pe(r.videoRole),f=pe(r.analysisId)??pe(r.analysis);if(!o||!i&&!a||!s)throw new Error("Invalid --media binding. handle, purpose, and either path or url are required strings.");if(i&&a)throw new Error("A media binding cannot contain both path and url.");if(i&&s==="source"&&f)throw new Error("A source analysis is bound to the original uploaded URL. Reuse the url/name/mime/size binding printed by 'video reference analyze' instead of uploading path again.");if(i&&!t.uploadIdempotencyKey)throw new Error("Local storyboard media requires the command idempotency key.");let p=i?await ue(bt(i),{idempotencyKey:`${t.uploadIdempotencyKey}:media:${o}`}):{name:pe(r.name),size:Number(r.size),type:pe(r.mime),url:a};if(!p.name||!p.type||!p.url||!Number.isSafeInteger(p.size)||p.size<=0)throw new Error(`URL media binding "${n}" requires name, mime, and positive integer size.`);let w=p.type.startsWith("video/")?"video":p.type.startsWith("audio/")?"audio":p.type.startsWith("image/")?"image":null;if(!w)throw new Error(`Unsupported media type for ${i??a}: ${p.type}`);if(!["source","style","identity","required"].includes(s))throw new Error(`Invalid media purpose: ${s}`);if(l&&!["reference","first-frame","last-frame"].includes(l))throw new Error(`Invalid videoRole: ${l}`);if(l&&w!=="image")throw new Error("videoRole is supported only for image bindings.");return{...f?{analysisId:f}:{},fileUrl:p.url,handle:o,kind:w,mime:p.type,name:p.name,purpose:s,size:p.size,...l?{videoRole:l}:{}}}))}function pe(e){return typeof e=="string"&&e.length>0?e:void 0}var bp=new Q("create").description("Create a versioned Markdown video storyboard").requiredOption("--file <path>","Markdown file path, or - for stdin").requiredOption("--duration <seconds>","Exact total duration in seconds").requiredOption("--aspect <ratio>","Output aspect: 9:16, 16:9, or 1:1").option("--title <text>","Artifact label").requiredOption("--idempotency-key <key>","Stable key to reuse when retrying this exact create").option("--media <binding...>",'One JSON binding per asset: {"handle":"actress-photo","path":"./actress.jpg","purpose":"identity"}').option("--team-id <id>","Workspace ID").action(async e=>{try{m(await y("createVideoStoryboard",{aspectRatio:e.aspect,durationSec:Number(e.duration),mediaBindings:await Ya(e.media,{uploadIdempotencyKey:e.idempotencyKey}),storyboardMarkdown:await Ha(e.file),teamId:e.teamId,title:e.title},e.idempotencyKey))}catch(t){d(t instanceof Error?t.message:"Storyboard creation failed"),process.exit(c.GENERAL_ERROR)}}),wp=new Q("revise").description("Append an immutable revision to a video storyboard").argument("<storyboard-id>","Storyboard UUID").requiredOption("--base-revision <id>","Revision UUID that was edited").requiredOption("--file <path>","Complete Markdown file path, or - for stdin").requiredOption("--duration <seconds>","Exact total duration in seconds").requiredOption("--aspect <ratio>","Output aspect: 9:16, 16:9, or 1:1").option("--title <text>","Replacement artifact label").requiredOption("--idempotency-key <key>","Stable key to reuse when retrying this exact revision").option("--change-summary <text>","Short description of this revision").option("--media <binding...>",'Replace media bindings with one JSON object per asset; use the JSON printed by "video reference analyze" for analyzed source video').option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await y("reviseVideoStoryboard",{aspectRatio:t.aspect,baseRevisionId:t.baseRevision,changeSummary:t.changeSummary,durationSec:Number(t.duration),mediaBindings:await Ya(t.media,{uploadIdempotencyKey:t.idempotencyKey}),storyboardId:e,storyboardMarkdown:await Ha(t.file),teamId:t.teamId,title:t.title},t.idempotencyKey))}catch(n){d(n instanceof Error?n.message:"Storyboard revision failed"),process.exit(c.GENERAL_ERROR)}}),vp=new Q("show").description("Read a storyboard; print Markdown unless --json is used").argument("<storyboard-id>","Storyboard UUID").option("--revision <id>","Read one immutable revision UUID").option("--team-id <id>","Workspace ID").option("--json","Print the complete structured response").action(async(e,t)=>{try{let n=await y("readVideoStoryboard",{revisionId:t.revision,storyboardId:e,teamId:t.teamId});if(t.json){m(n);return}console.error(`${n.storyboard.title} \xB7 revision ${n.storyboard.revision.versionNumber} (${n.storyboard.revision.id})`),console.log(n.storyboard.revision.storyboardMarkdown)}catch(n){d(n instanceof Error?n.message:"Storyboard read failed"),process.exit(c.GENERAL_ERROR)}}),xp=new Q("storyboard").description("Create, revise, and read Markdown video storyboards").addCommand(bp).addCommand(wp).addCommand(vp),kp=new Q("analyze").description("Upload and analyze a reference video").requiredOption("--file <path>","Local reference video").requiredOption("--idempotency-key <key>","Stable key to reuse when retrying this exact analysis").option("--user-request <text>","What the analysis should focus on").option("--team-id <id>","Workspace ID").option("--no-wait","Return the durable run immediately").option("--json","Print the complete structured result").action(async e=>{try{let t=await ue(bt(e.file),{idempotencyKey:`video-reference-analysis:${e.idempotencyKey}:source`});if(!t.type.startsWith("video/"))throw new Error(`Reference analysis requires a video, got ${t.type}`);let n=await Oo({idempotencyKey:e.idempotencyKey,sourceUrl:t.url,teamId:e.teamId,userRequest:e.userRequest}),r={analysisId:n.runId,fileUrl:t.url,handle:"source-video",kind:"video",mime:t.type,name:t.name,purpose:"source",size:t.size};if(e.wait===!1){m({...n,binding:r,source:t});return}let o=await Po(n.runId,e.teamId);if(e.json){m({...o,binding:r,source:t});return}let i=o.output?.analysis??{};console.log(typeof i.promptContext=="string"?i.promptContext:JSON.stringify(o.output,null,2)),console.error(`Analysis run: ${n.runId}`),console.error(`Storyboard media JSON: ${JSON.stringify(r)}`)}catch(t){d(t instanceof Error?t.message:"Reference analysis failed"),process.exit(c.GENERAL_ERROR)}}),Cp=new Q("status").description("Read a video-reference analysis run").argument("<run-id>","Analysis run UUID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await T("analyzeVideoReference",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status read failed"),process.exit(c.GENERAL_ERROR)}}),Ip=new Q("reference").description("Upload and inspect reusable video references").addCommand(kp).addCommand(Cp),Rp=new Q("status").description("Read video background status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await T("createVideo",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),Sp=new Q("inject").description("Inject thumbnail into video (first frame + file icon)").requiredOption("-i, --video <path>","Input video file").requiredOption("-t, --thumbnail <path>","Thumbnail image").option("-o, --output <path>","Output video (default: video-with-thumb.mp4)").option("-f, --format <format>","Output format: human, json, quiet","human").action(async e=>{let t=e.format,n=t==="human"?Xa("Injecting thumbnail...").start():null;try{let r=bt(e.video),o=bt(e.thumbnail),i=e.output?bt(e.output):r.replace(/\.mp4$/,"-with-thumb.mp4");await br(r),await br(o);let a=pp;if(a)try{await br(a)}catch{a=null}if(!a)try{a=rn("which ffmpeg",{encoding:"utf8"}).trim()}catch{throw new Error("ffmpeg not found. Install ffmpeg or ffmpeg-static.")}let s=up(a,["-i",r],{encoding:"utf8"});if(s.error)throw new Error(`Failed to probe video: ${s.error.message}`);let l=(s.stderr??"").match(/(\d{2,5})x(\d{2,5})/);if(!l)throw new Error("Could not detect video dimensions");let[,f,p]=l;n&&(n.text="Creating thumbnail frame...");let w="/tmp/cc-thumb-frame.mp4";rn(`${a} -y -loop 1 -i "${o}" -vf "scale=${f}:${p}:force_original_aspect_ratio=decrease,pad=${f}:${p}:(ow-iw)/2:(oh-ih)/2,setsar=1" -t 0.033 -r 30 -c:v libx264 -pix_fmt yuv420p "${w}"`,{stdio:"pipe"}),n&&(n.text="Concatenating with video...");let v="/tmp/cc-concat-video.mp4";if(rn(`${a} -y -i "${w}" -i "${r}" -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" -map "[v]" -map 1:a -c:v libx264 -preset ultrafast -crf 18 -c:a copy "${v}"`,{stdio:"pipe"}),n&&(n.text="Adding file icon thumbnail..."),rn(`${a} -y -i "${v}" -i "${o}" -map 0 -map 1 -c copy -c:v:1 png -disposition:v:1 attached_pic "${i}"`,{stdio:"pipe"}),await za(w,{force:!0}),await za(v,{force:!0}),n?.stop(),t==="json"){m({success:!0,output:i});return}if(t==="quiet"){console.log(i);return}C(`Thumbnail injected: ${i}`)}catch(r){n?.stop(),d(r instanceof Error?r.message:"Unknown error"),process.exit(c.GENERAL_ERROR)}}),$p=new Q("thumbnail").description("Thumbnail operations").addCommand(Sp),on=new Q("video").description("Build a video from scratch \u2014 brief or storyboard to stock and generated footage, translation, lipsync, analysis (for a finished deck, use presentation video)").addCommand(hp).addCommand($p).addCommand(Wa).addCommand(Ka).addCommand(Ja).addCommand(Ra).addCommand(ja);on.addCommand(yp).addCommand(xp).addCommand(Ip).addCommand(Rp);on.addHelpText("after",`
|
|
174
|
+
${me.bold("Examples:")}
|
|
175
|
+
${me.gray("# Storyboard-first video from a brief")}
|
|
154
176
|
$ ${u.commands[0]} video storyboard create --file brief.md --duration 60 --aspect 16:9 --idempotency-key launch-1
|
|
155
177
|
|
|
156
|
-
${
|
|
178
|
+
${me.gray("# Find licensed stock footage")}
|
|
157
179
|
$ ${u.commands[0]} video find "city timelapse"
|
|
158
180
|
|
|
159
|
-
${
|
|
160
|
-
${
|
|
181
|
+
${me.bold("Before generating:")}
|
|
182
|
+
${me.gray("# video create costs credits and is what the user will share; the")}
|
|
183
|
+
${me.gray("# storyboard is the free, append-only part. Show it, take edits, and get")}
|
|
184
|
+
${me.gray("# an explicit yes before pinning a revision. --yes is your intent, not")}
|
|
185
|
+
${me.gray("# the user's consent.")}
|
|
186
|
+
$ ${u.commands[0]} video storyboard show <storyboard-id>
|
|
187
|
+
$ ${u.commands[0]} video storyboard revise <storyboard-id> --base-revision <revision-id> --file brief-v2.md --idempotency-key launch-2
|
|
188
|
+
|
|
189
|
+
${me.bold("See also:")}
|
|
190
|
+
${me.gray("# Already have a deck? Render it to MP4 (narration, avatar, captions)")}
|
|
161
191
|
$ ${u.commands[0]} presentation video <slug>
|
|
162
|
-
`);import{Command as
|
|
163
|
-
`)}function
|
|
164
|
-
`)}var
|
|
192
|
+
`);import{Command as wr}from"commander";var Tp=new wr("create").description("Start background visual-abstract generation").argument("<brief>","Dense source brief").option("--title <title>","Artifact title").option("--aspect <ratio>","1:1, 16:9, 9:16, 4:3, or 3:4","1:1").option("--quality <tier>","fast, best, or enterprise","best").option("--preset <preset>","Output preset","executive-one-pager").option("--output <type>","raster or vector","raster").option("--branding-id <id>","Branding ID").option("--reference-url <url...>","Up to three image URLs to use as visual references").option("--team-id <id>","Workspace ID").option("--yes","Approve generation").action(async(e,t)=>{if(!t.yes)return d("Pass --yes to approve visual-abstract generation");try{let n=Array.isArray(t.referenceUrl)?t.referenceUrl.slice(0,3).map((r,o)=>({label:`visual-reference-${o+1}`,url:r})):void 0;m(await y("createVisualAbstract",{approvalReceipt:"cli:--yes",aspectRatio:t.aspect,brandingId:t.brandingId,brief:e,outputPreset:t.preset,outputType:t.output,qualityTier:t.quality,referenceImages:n,teamId:t.teamId,title:t.title}))}catch(n){d(n instanceof Error?n.message:"Generation failed"),process.exit(c.GENERAL_ERROR)}}),Ep=new wr("status").description("Read visual-abstract generation status").argument("<run-id>","Run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await T("createVisualAbstract",e,t.teamId))}catch(n){d(n instanceof Error?n.message:"Status failed"),process.exit(c.GENERAL_ERROR)}}),Qa=new wr("visual-abstract").description("Generate a one-page visual abstract graphic (raster or vector) from a dense brief").addCommand(Tp).addCommand(Ep);var vr=[Wi,Yi,Mi,Da,ha,ia,Zi,on,mr,Aa,Ea,ur,gr,Jn,ea,Qn,ba,Ei,Qa,oa,Si,Wn,ra,Kn,Ji,zi];function Za(e){for(let t of vr)e.addCommand(t)}function es(e,t,n){let r=t?`${t} ${e.name()}`:e.name();n.set(r,{arguments:e.registeredArguments.filter(o=>o.required).map(o=>`<${o.name()}>`),requiredOptions:e.options.filter(o=>o.mandatory).map(o=>o.long).filter(o=>!!o)});for(let o of e.commands)es(o,r,n)}var an;function Ap(){if(!an){an=new Map;for(let e of vr)es(e,"",an)}return an}function ts(e){let t=Ap().get(e);return t?[...t.arguments,...t.requiredOptions.map(n=>`${n} \u2026`)].join(" "):""}var ns=["presentations","media","branding","knowledge","research","artifacts","agents"],xr={agents:"Scheduled agents and agent memory",artifacts:"Polls, microsites, ad sets and visual abstracts",branding:"Brand profiles, tokens, logos and competitors",knowledge:"Library documents, folders and the Knowledge Hub",media:"Voiceover, music, SFX, images, stock footage, avatars and video",presentations:"Decks, PowerPoint import, speaker notes and deck\u2192MP4",research:"Scraping, transcripts, web/news/image search and extraction"},Op="other";function Pp(e){let t=e.category?.trim();return t&&t.length>0?t:Op}function rs(e){let t=ns.indexOf(e);return t===-1?ns.length:t}function wt(e){let t=new Map;for(let n of e){let r=Pp(n),o=t.get(r);o?o.push(n):t.set(r,[n])}return[...t.entries()].sort(([n],[r])=>rs(n)-rs(r)||n.localeCompare(r)).map(([n,r])=>({capabilities:[...r].sort((o,i)=>o.name.localeCompare(i.name)),category:n}))}function kr(e){return e.lifecycle?.mode==="background"}function Cr(e,t){let n=e.lifecycle?.status?.cliCommand?.trim();if(!(!kr(e)||!n))return`${t} ${n} <run-id>`}function _p(e){switch(e.billing){case"free":return"free";case"quota":return"plan quota";case"fixed":return"credits (fixed)";case"dynamic":return"credits (usage-based)";case"delegated":return"credits (on completion)";default:return"unknown \u2014 check `capabilities`"}}function sn(e){return e.replace(/\|/g,"\\|").replace(/\r?\n/g," ").trim()}function Lp(e,t){let n=Cr(e,t);return n?`run id \u2014 poll \`${n}\``:`immediate (${e.operation??"call"})`}function Ke(e,t){let n=["| Command | What it does | Takes | Returns | Cost | Scopes |","|---|---|---|---|---|---|"],r=e.map(o=>{let i=ts(o.name),a=o.scopes?.length?o.scopes.map(s=>`\`${s}\``).join(", "):"\u2014";return`| \`${t} ${sn(o.name)}\` | ${sn(o.description??"")} | ${i?`\`${sn(i)}\``:"\u2014"} | ${Lp(o,t)} | ${_p(o)} | ${a} |`});return[...n,...r].join(`
|
|
193
|
+
`)}function ge(e,t){if(e.source==="live")return`<!-- Generated from the live ${t.name} capability catalog (v${e.catalogVersion}, ${e.capabilities.length} capabilities) at install time. Re-run \`${t.cmd} skill install\` to refresh. -->`;let n=e.reason?` Reason: ${sn(e.reason).replace(/\.+$/,"")}.`:"";return`<!-- STALE-RISK: the live catalog could not be read at install time, so this was rendered from the snapshot baked into the installed CLI (v${e.catalogVersion}, ${e.capabilities.length} capabilities).${n} Run \`${t.cmd} login\` then \`${t.cmd} skill install --force\` to regenerate from the live catalog, and treat \`${t.cmd} capabilities\` as authoritative over this file. -->`}function os(e){return e.map(t=>`- [${t}](#${t.toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/ /g,"-")})`).join(`
|
|
194
|
+
`)}var Dp=["presentation video prepare","presentation video inspect","presentation video settings","presentation video edit","presentation video presenter","presentation video","presentation video versions","presentation video restore","presentation video refresh","presentation video-narration","presentation speaker-notes","video library list","avatar options"];function Np(e){let t=new Map(e.map(n=>[n.name,n]));return Dp.map(n=>t.get(n)).filter(n=>n!==void 0)}function dn(e,t){let{cmd:n}=e,r=Np(t.capabilities),o=t.capabilities.find(a=>a.name==="presentation video"),i=o?Cr(o,n)??`${n} presentation video status <run-id>`:`${n} presentation video status <run-id>`;return`${ge(t,e)}
|
|
165
195
|
|
|
166
196
|
# Deck \u2192 MP4 (\`${n} presentation video\`)
|
|
167
197
|
|
|
@@ -175,6 +205,7 @@ For a video that is not built from a deck, read
|
|
|
175
205
|
## Contents
|
|
176
206
|
|
|
177
207
|
- [The lifecycle](#the-lifecycle)
|
|
208
|
+
- [Before you render](#before-you-render)
|
|
178
209
|
- [Render settings](#render-settings)
|
|
179
210
|
- [Draft editing, versions and presenters](#draft-editing-versions-and-presenters)
|
|
180
211
|
- [Narration and speaker notes](#narration-and-speaker-notes)
|
|
@@ -183,19 +214,27 @@ For a video that is not built from a deck, read
|
|
|
183
214
|
## The lifecycle
|
|
184
215
|
|
|
185
216
|
\`\`\`bash
|
|
186
|
-
#
|
|
217
|
+
# 0) No deck yet? Make one first.
|
|
218
|
+
${n} create "\u2026"
|
|
219
|
+
|
|
220
|
+
# 1) Create or reuse the version-pinned video project for the deck.
|
|
221
|
+
# Picks the narration voice for you and reports it, plus the narration
|
|
222
|
+
# state. No presenter is chosen \u2014 that is the default, not a gap.
|
|
187
223
|
${n} presentation video prepare <presentation-id> --yes
|
|
188
224
|
|
|
189
|
-
# 2)
|
|
225
|
+
# 2) Fill in narration when prepare reported it missing (costs credits)
|
|
226
|
+
${n} presentation video narrate <project-id> --yes
|
|
227
|
+
|
|
228
|
+
# 3) Read the project back and SHOW the user what will be produced
|
|
190
229
|
${n} presentation video inspect <project-id>
|
|
191
230
|
|
|
192
|
-
#
|
|
231
|
+
# 4) Optional: change what they asked to change
|
|
193
232
|
${n} presentation video settings <project-id> --settings ./settings.json --yes
|
|
194
233
|
|
|
195
|
-
#
|
|
234
|
+
# 5) Only after they say yes: render the MP4 \u2014 paid, background, requires --yes
|
|
196
235
|
${n} presentation video <presentation-id> --render-engine remotion --yes
|
|
197
236
|
|
|
198
|
-
#
|
|
237
|
+
# 6) Poll until done
|
|
199
238
|
${i}
|
|
200
239
|
\`\`\`
|
|
201
240
|
|
|
@@ -209,6 +248,79 @@ The render takes **either** a \`<presentation-id>\` argument **or**
|
|
|
209
248
|
\`--render-engine\` applies to that one run only. It does not change narration,
|
|
210
249
|
voice, presenter, music, captions, or the saved project setup.
|
|
211
250
|
|
|
251
|
+
## Before you render
|
|
252
|
+
|
|
253
|
+
Everything before the render is repeatable, and only narration (step 2) costs
|
|
254
|
+
anything. Step 5 spends credits, runs for minutes and produces the file the
|
|
255
|
+
user will send to other people. Treat it as the user's approval step: do not
|
|
256
|
+
start a render until you have shown what it will produce and heard an explicit
|
|
257
|
+
yes.
|
|
258
|
+
|
|
259
|
+
\`${n} presentation video inspect <project-id>\` is what you show from. Per
|
|
260
|
+
scene it returns \`narration.text\` \u2014 the exact script that will be spoken, and
|
|
261
|
+
the thing the user is most likely to want to rewrite \u2014 plus \`title\`,
|
|
262
|
+
\`durationSec\`, \`presenter\` (the avatar on that scene, or \`null\`),
|
|
263
|
+
\`excluded\` and \`imageReady\`. At project level it returns
|
|
264
|
+
\`renderSettings\`: \`voice\`, \`presenter\`, \`music\`, \`captions\`,
|
|
265
|
+
\`format\`, \`narrationDensity\` and \`renderEngine\` \u2014 the whole list of things
|
|
266
|
+
a person confirms before paying. \`presenter: null\` means "slides only", which
|
|
267
|
+
is the normal answer. Read the narration back first; it is what they will want
|
|
268
|
+
to change.
|
|
269
|
+
|
|
270
|
+
### The voice is already chosen \u2014 show it, do not interview for it
|
|
271
|
+
|
|
272
|
+
\`prepare\` picks the narration voice the way the studio does: the voice this
|
|
273
|
+
user last chose if it is still ready, otherwise the workspace's first ready
|
|
274
|
+
voice. It reports the choice as \`voice\`:
|
|
275
|
+
|
|
276
|
+
\`\`\`json
|
|
277
|
+
{ "voice": { "status": "selected", "source": "preference",
|
|
278
|
+
"voice": { "id": "\u2026", "label": "Ava" } } }
|
|
279
|
+
\`\`\`
|
|
280
|
+
|
|
281
|
+
So do not open with "which voice would you like?" \u2014 say which voice was
|
|
282
|
+
selected and offer to change it. \`status: "unavailable"\` is the only case
|
|
283
|
+
that needs a question: it means the workspace has no ready voice, or the voice
|
|
284
|
+
catalog is down, and the render will refuse until one is set.
|
|
285
|
+
|
|
286
|
+
To change it, \`${n} avatar options\` lists the real ids: stock avatars (with
|
|
287
|
+
render tiers), the workspace's own trained \`pp_*\` presenters, and the voices
|
|
288
|
+
(\`--language <lang>\` filters them; \`--format json\` adds gender and avatar
|
|
289
|
+
preview images). Every voice carries a \`previewUrl\` \u2014 an audio sample, so the
|
|
290
|
+
user can HEAR a shortlist instead of choosing a name blind. Then:
|
|
291
|
+
|
|
292
|
+
\`\`\`bash
|
|
293
|
+
${n} presentation video settings <project-id> --yes --settings '{"voiceId":"<id>"}'
|
|
294
|
+
\`\`\`
|
|
295
|
+
|
|
296
|
+
### No avatar is the default, on purpose
|
|
297
|
+
|
|
298
|
+
"Slides with a voiceover" is the normal product outcome, so \`presenter: null\`
|
|
299
|
+
is a finished setup, not a missing setting. Ask whether they want a presenter
|
|
300
|
+
on screen; never treat its absence as a misconfiguration to repair. If they do
|
|
301
|
+
want one:
|
|
302
|
+
|
|
303
|
+
\`\`\`bash
|
|
304
|
+
${n} presentation video settings <project-id> --yes --settings '{"avatarId":"<id>"}'
|
|
305
|
+
${n} presentation video presenter <project-id> <slide-id> --avatar-id <id> # one scene only
|
|
306
|
+
\`\`\`
|
|
307
|
+
|
|
308
|
+
To take the presenter back off, \`--settings '{"presenter":null}'\`.
|
|
309
|
+
|
|
310
|
+
Iterating is the cheap part, so iterate:
|
|
311
|
+
|
|
312
|
+
\`\`\`bash
|
|
313
|
+
${n} presentation video-narration <project-id> --slide-id <id> --instructions "shorter, warmer"
|
|
314
|
+
${n} presentation video edit <project-id> --edit ./edit.json # patch, move or remove a scene
|
|
315
|
+
${n} presentation video settings <project-id> --settings \u2026 --yes # voice, presenter, music, format, captions
|
|
316
|
+
${n} presentation video refresh <project-id> # re-pull slides after the deck changed
|
|
317
|
+
${n} presentation video versions <project-id> # drafts are append-only; nothing is lost
|
|
318
|
+
\`\`\`
|
|
319
|
+
|
|
320
|
+
Only once the user has approved that draft:
|
|
321
|
+
\`${n} presentation video <presentation-id> --yes\`. \`--yes\` is your
|
|
322
|
+
statement of intent; it is not their consent and never replaces asking.
|
|
323
|
+
|
|
212
324
|
## Render settings
|
|
213
325
|
|
|
214
326
|
Both \`presentation video settings --settings\` and the render's own
|
|
@@ -222,8 +334,11 @@ file. At least one key is required.
|
|
|
222
334
|
| \`music\` | object (see below) | Background music settings to merge into the saved project. |
|
|
223
335
|
| \`narrationDensity\` | \`brief\` \\| \`balanced\` \\| \`deep\` | How much narration to generate per slide. |
|
|
224
336
|
| \`presenter\` | object or \`null\` | Selected avatar/presenter, or null to remove it. |
|
|
337
|
+
| \`avatarId\` | string | Avatar/look id from \`avatar options\`; the server resolves the presenter identity. Alternative to \`presenter\`. |
|
|
338
|
+
| \`renderTier\` | \`basic\` \\| \`standard\` \\| \`premium\` | Render tier for \`avatarId\`. Only valid with \`avatarId\`. |
|
|
225
339
|
| \`renderEngine\` | \`remotion\` \\| \`hyperframes\` | Terminal renderer for the MP4. |
|
|
226
340
|
| \`voice\` | object or \`null\` | Selected narration voice, or null to clear it. |
|
|
341
|
+
| \`voiceId\` | string | Voice id from \`avatar options\`; the server resolves its label. Alternative to \`voice\`. |
|
|
227
342
|
|
|
228
343
|
\`music\` keys: \`mode\` (\`basic\` \\| \`standard\` \\| \`stock\` \\| \`upload\` \\| \`off\`,
|
|
229
344
|
default \`basic\`), \`volume\` (0\u20131), \`prompt\`, \`audioUrl\`, \`fileName\`,
|
|
@@ -236,6 +351,12 @@ default \`basic\`), \`volume\` (0\u20131), \`prompt\`, \`audioUrl\`, \`fileName\
|
|
|
236
351
|
\`previewImageUrl\`, \`source\`) plus \`perSlideEnabled\` / \`perSlidePlacements\`
|
|
237
352
|
maps keyed by slide id. Get real ids from \`${n} avatar options\`.
|
|
238
353
|
|
|
354
|
+
Because that roster reports ids, not those objects, \`voiceId\` and
|
|
355
|
+
\`avatarId\` accept what you can actually list and the server resolves the
|
|
356
|
+
rest. Passing both forms of one setting (\`voice\` and \`voiceId\`, or
|
|
357
|
+
\`presenter\` and \`avatarId\`) is refused rather than silently ranked;
|
|
358
|
+
\`presenter: null\` remains how a presenter is removed.
|
|
359
|
+
|
|
239
360
|
Example:
|
|
240
361
|
|
|
241
362
|
\`\`\`bash
|
|
@@ -291,11 +412,11 @@ not maintain a second copy.
|
|
|
291
412
|
|
|
292
413
|
## Every capability in this flow
|
|
293
414
|
|
|
294
|
-
${
|
|
415
|
+
${Ke(r,n)}
|
|
295
416
|
|
|
296
417
|
If something you need is not in this table, do not conclude it is missing \u2014
|
|
297
418
|
run \`${n} capabilities --search video\`.
|
|
298
|
-
`}var
|
|
419
|
+
`}var Up=["video reference analyze","video storyboard create","video storyboard revise","video storyboard show","video create","search video","video translate-languages","video translate","video lipsync","media analyze","media import","video library list"];function Ir(e){let t=new Map(e.map(n=>[n.name,n]));return Up.map(n=>t.get(n)).filter(n=>n!==void 0)}function cn(e,t){let{cmd:n}=e,r=Ir(t.capabilities);return`${ge(t,e)}
|
|
299
420
|
|
|
300
421
|
# Video from scratch (\`${n} video\`)
|
|
301
422
|
|
|
@@ -309,6 +430,7 @@ There is no \`video export\` subcommand.
|
|
|
309
430
|
## Contents
|
|
310
431
|
|
|
311
432
|
- [The hosted pipeline](#the-hosted-pipeline)
|
|
433
|
+
- [Before you generate](#before-you-generate)
|
|
312
434
|
- [Storyboards](#storyboards)
|
|
313
435
|
- [Other video operations](#other-video-operations)
|
|
314
436
|
- [Every capability in this flow](#every-capability-in-this-flow)
|
|
@@ -344,6 +466,28 @@ browser confirmation URL, then repeat the **exact** invocation with
|
|
|
344
466
|
never substitutes for one. \`--draft\` renders at 480p for a faster look;
|
|
345
467
|
\`--source-video <id>\` reuses a finished video as base footage.
|
|
346
468
|
|
|
469
|
+
## Before you generate
|
|
470
|
+
|
|
471
|
+
Steps 0-2 are cheap and repeatable. \`video create\` spends credits, runs for
|
|
472
|
+
minutes and produces the file the user will send to other people. The
|
|
473
|
+
generation is the user's approval step: show the storyboard and get an explicit
|
|
474
|
+
yes before you pin a revision and spend.
|
|
475
|
+
|
|
476
|
+
\`${n} video storyboard show <storyboard-id>\` prints the storyboard Markdown
|
|
477
|
+
the user should actually read \u2014 the script, the shots, the pacing \u2014 and
|
|
478
|
+
\`--json\` adds the structured response with the revision ids. Show it, take
|
|
479
|
+
their edits, and fold them back in with \`${n} video storyboard revise\`.
|
|
480
|
+
Revisions are appended, never overwritten, so iterating costs nothing and
|
|
481
|
+
loses nothing.
|
|
482
|
+
|
|
483
|
+
Then confirm out loud what the run is pinned to before you start it: which
|
|
484
|
+
revision, the \`--duration\` and \`--aspect\` it was created with, whether this
|
|
485
|
+
is a \`--draft\` look or the full-quality run, and any \`--media\` binding with
|
|
486
|
+
\`purpose\` \`identity\` \u2014 who appears in the shot is not something to guess.
|
|
487
|
+
|
|
488
|
+
The approval receipt is that same moment, not a formality: the confirmation URL
|
|
489
|
+
goes to a person. \`--yes\` states your intent and is not their consent.
|
|
490
|
+
|
|
347
491
|
## Storyboards
|
|
348
492
|
|
|
349
493
|
\`storyboard create\` requires \`--file <path|->\`, \`--duration <seconds>\`,
|
|
@@ -405,42 +549,42 @@ ${n} video analyze \u2026 # analyze a video y
|
|
|
405
549
|
|
|
406
550
|
## Every capability in this flow
|
|
407
551
|
|
|
408
|
-
${
|
|
552
|
+
${Ke(r,n)}
|
|
409
553
|
|
|
410
554
|
If something you need is not in this table, do not conclude it is missing \u2014
|
|
411
555
|
run \`${n} capabilities --search video\`.
|
|
412
|
-
`}var
|
|
556
|
+
`}var qp=12,jp={media:"video.md",presentations:"deck-to-video.md"};function Mp(e,t,n,r){let{cmd:o}=e,i=xr[n]??n,a=r.filter(kr),s=r.filter(p=>p.billing!==void 0&&p.billing!=="free"),l=jp[n],f=["Every capability",...a.length>0?["Background operations"]:[]];return`${ge(t,e)}
|
|
413
557
|
|
|
414
558
|
# ${n} \u2014 ${i}
|
|
415
559
|
|
|
416
560
|
${r.length} capabilit${r.length===1?"y":"ies"} in this category${s.length>0?`, ${s.length} of which ${s.length===1?"costs":"cost"} credits or ${s.length===1?"counts":"count"} against a plan quota`:", all free"}.${l?`
|
|
417
561
|
|
|
418
562
|
Step-by-step flow: [${l}](${l}).`:""}
|
|
419
|
-
${r.length>
|
|
563
|
+
${r.length>qp?`
|
|
420
564
|
## Contents
|
|
421
565
|
|
|
422
|
-
${
|
|
566
|
+
${os(f)}
|
|
423
567
|
`:""}
|
|
424
568
|
## Every capability
|
|
425
569
|
|
|
426
|
-
${
|
|
570
|
+
${Ke(r,o)}
|
|
427
571
|
${a.length>0?`
|
|
428
572
|
## Background operations
|
|
429
573
|
|
|
430
574
|
These return a run id immediately and keep working. Poll the status command
|
|
431
575
|
until it reports done \u2014 do not assume success from the accept response.
|
|
432
576
|
|
|
433
|
-
${a.map(
|
|
577
|
+
${a.map(p=>`- \`${o} ${p.name}\` \u2192 \`${o} ${p.lifecycle?.status?.cliCommand??""} <run-id>\`${p.lifecycle?.status?.pollAfterSeconds?` (first poll after ~${p.lifecycle.status.pollAfterSeconds}s)`:""}`).join(`
|
|
434
578
|
`)}
|
|
435
579
|
`:""}
|
|
436
580
|
Anything missing here? Run \`${o} capabilities --category ${n}\` \u2014 the
|
|
437
581
|
catalog is authoritative and always current; this file is a snapshot of it.
|
|
438
|
-
`}function
|
|
582
|
+
`}function is(e,t,n={}){let r=[{content:dn(e,t),name:"deck-to-video"},{content:cn(e,t),name:"video"}];for(let{capabilities:o,category:i}of wt(t.capabilities)){let a=n[i];r.push({content:Mp(e,t,i,o)+(a?`
|
|
439
583
|
---
|
|
440
584
|
|
|
441
|
-
${a}`:""),name:i})}return r}function
|
|
442
|
-
`),
|
|
443
|
-
`),w=[...new Set([...t.capabilities.map(v=>v.name.split(" ")[0]),...
|
|
585
|
+
${a}`:""),name:i})}return r}function as(e){let t=[{file:"deck-to-video.md",when:"An existing deck must become an MP4 \u2014 narration, voice, avatar, music, captions."},{file:"video.md",when:"A video is being built from a brief or storyboard, with no deck involved."}];for(let{capabilities:n,category:r}of wt(e.capabilities))t.push({file:`${r}.md`,when:`${xr[r]??r} (${n.length} commands).`});return t}var Fp=[{capability:"create",intent:'"Make me a presentation / deck / slides about X"',reference:"presentations.md",suffix:' "Topic" --context "\u2026"'},{capability:"presentation video prepare",intent:'"Turn my deck into a video / MP4 / narrated video"',reference:"deck-to-video.md",suffix:" <presentation-id> --yes"},{capability:"video storyboard create",intent:'"Make me a video about X" (no deck exists)',reference:"video.md",suffix:" --file ./storyboard.md \u2026"},{capability:"presentation import",intent:'"Import this PowerPoint / .pptx"',reference:"presentations.md",suffix:" --file deck.pptx --mode preserve"},{capability:"presentation speaker-notes",intent:'"Write speaker notes for this deck"',reference:"deck-to-video.md",suffix:" <presentation-id>"},{capability:"presentation video-narration",intent:'"Rewrite the narration on one slide"',reference:"deck-to-video.md",suffix:" <project-id> --slide-id <id>"},{capability:"tts generate",intent:'"Voiceover / narration / read this aloud / TTS"',reference:"media.md",suffix:' -t "Text" -o out.mp3'},{capability:"music generate",intent:'"Background music / a soundtrack"',reference:"media.md"},{capability:"sfx generate",intent:'"Sound effects"',reference:"media.md"},{capability:"mix create",intent:'"Mix this voiceover and music into the video"',reference:"media.md"},{capability:"image generate",intent:'"Generate an image"',reference:"media.md"},{capability:"search images",intent:'"Find a stock photo"',reference:"research.md",suffix:' -q "\u2026"'},{capability:"search video",intent:'"Find stock footage / b-roll"',reference:"video.md",suffix:' "ocean waves"'},{capability:"avatar options",intent:'"Which avatars / presenters / voices can I use?"',reference:"media.md"},{capability:"avatar generate",intent:'"Make a talking-head / avatar clip"',reference:"media.md"},{capability:"video translate",intent:'"Dub / translate this video"',reference:"video.md"},{capability:"video lipsync",intent:'"Re-sync the lips to this new audio"',reference:"video.md"},{capability:"branding extract",intent:'"Match my brand" / "pull branding from this site"',reference:"branding.md",suffix:" <url>"},{capability:"scrape",intent:'"Read this web page"',reference:"research.md",suffix:" https://example.com"},{capability:"transcript",intent:'"Get the transcript of this YouTube video"',reference:"research.md",suffix:" <url>"},{capability:"search web",intent:'"Search the web / find news about X"',reference:"research.md",suffix:' "query"'},{capability:"knowledge search",intent:'"What do we already have on X?"',reference:"knowledge.md"},{capability:"document create",intent:'"Save this as a document" / library filing',reference:"knowledge.md"},{capability:"microsite create",intent:'"Build a landing page / microsite"',reference:"artifacts.md"},{capability:"poll create",intent:'"Make a poll"',reference:"artifacts.md"},{capability:"visual-abstract create",intent:'"One-page visual summary"',reference:"artifacts.md"},{capability:"ad-set create",intent:'"Ad creatives for this campaign"',reference:"artifacts.md"},{capability:"agent create",intent:'"Schedule this to run every week"',reference:"agents.md"}],Vp=["capabilities","config","delete","derive","export","footage","ideas","import","list","login","logout","runner","skill","templates","whoami"];function ln(e,t=At("rendered without a catalog fetch")){let{name:n,cmd:r,pkg:o}=e,i=n.toUpperCase().replace(/[^A-Z0-9]/g,"_"),a=new Map(t.capabilities.map(v=>[v.name,v])),s=Fp.filter(v=>a.has(v.capability)).map(v=>`| ${v.intent} | \`${r} ${v.capability}${v.suffix??""}\` | [${v.reference}](references/${v.reference}) |`).join(`
|
|
586
|
+
`),f=wt(t.capabilities).map(({capabilities:v,category:b})=>`${b} (${v.length})`).join(", "),p=as(t).map(({file:v,when:b})=>`| [references/${v}](references/${v}) | ${b} |`).join(`
|
|
587
|
+
`),w=[...new Set([...t.capabilities.map(v=>v.name.split(" ")[0]),...Vp])].sort().map(v=>`\`${v}\``).join(", ");return`---
|
|
444
588
|
name: ${n}
|
|
445
589
|
description: >-
|
|
446
590
|
Use for ANY request involving presentations, decks, slides, pitch decks, PowerPoint,
|
|
@@ -453,7 +597,7 @@ description: >-
|
|
|
453
597
|
${t.capabilities.length} CLI capabilities, listed in references/.
|
|
454
598
|
---
|
|
455
599
|
|
|
456
|
-
${
|
|
600
|
+
${ge(t,e)}
|
|
457
601
|
|
|
458
602
|
# ${n} CLI
|
|
459
603
|
|
|
@@ -485,6 +629,35 @@ no \`video export\` subcommand.
|
|
|
485
629
|
|
|
486
630
|
---
|
|
487
631
|
|
|
632
|
+
## A render is a purchase
|
|
633
|
+
|
|
634
|
+
\`${r} presentation video\` and \`${r} video create\` cost credits, take
|
|
635
|
+
minutes, and produce the file the user will show other people. Everything
|
|
636
|
+
before them \u2014 preparing the project, inspecting it, generating narration,
|
|
637
|
+
revising a storyboard, changing settings \u2014 is free or cheap and undoable. So
|
|
638
|
+
spend the cheap phase getting it right instead of rushing past it.
|
|
639
|
+
|
|
640
|
+
**The render is the user's approval step, not yours.** Before starting one,
|
|
641
|
+
show what it will produce and get an explicit yes. At minimum: the narration
|
|
642
|
+
text per scene (the script they may want to rewrite), the voice, whether a
|
|
643
|
+
presenter/avatar appears at all, music, format and captions.
|
|
644
|
+
|
|
645
|
+
Where a choice comes from a list, offer the list. \`${r} avatar options\`
|
|
646
|
+
prints the real avatar, personal-presenter and voice ids \u2014 shortlist a few and
|
|
647
|
+
let the user pick rather than silently choosing one. "No presenter, slides
|
|
648
|
+
only" is a common and legitimate answer, so ask instead of assuming either way.
|
|
649
|
+
|
|
650
|
+
\`--yes\` is your statement of intent, not the user's consent. Only a person
|
|
651
|
+
can give that.
|
|
652
|
+
|
|
653
|
+
Everything free and reversible stays fluent \u2014 never ask permission to inspect a
|
|
654
|
+
project or reread a storyboard. The gate is spending and irreversibility.
|
|
655
|
+
|
|
656
|
+
Per-pipeline detail: [deck-to-video.md](references/deck-to-video.md),
|
|
657
|
+
[video.md](references/video.md).
|
|
658
|
+
|
|
659
|
+
---
|
|
660
|
+
|
|
488
661
|
## Composing commands
|
|
489
662
|
|
|
490
663
|
Every table in \`references/\` carries a **Takes** and a **Returns** column. That
|
|
@@ -499,6 +672,14 @@ is enough to build a chain nobody wrote down. Derive the steps from the data:
|
|
|
499
672
|
the optional ones, run \`${r} <group> <sub> --help\`.
|
|
500
673
|
- If you cannot find a step, \`${r} capabilities --search <topic>\` is
|
|
501
674
|
authoritative \u2014 not this file.
|
|
675
|
+
- Poll; do not wait. Options that block until a long generation finishes
|
|
676
|
+
(\`${r} create --wait\`, the default follow mode on
|
|
677
|
+
\`${r} presentation speaker-notes\`) stream progress to a TTY a
|
|
678
|
+
non-interactive shell does not have, and the command routinely outlives the
|
|
679
|
+
tool timeout. Take the run id and poll instead \u2014
|
|
680
|
+
\`${r} presentation status <run-id>\`,
|
|
681
|
+
\`${r} presentation speaker-notes-status <run-id>\`,
|
|
682
|
+
\`${r} presentation video status <run-id>\`.
|
|
502
683
|
|
|
503
684
|
---
|
|
504
685
|
|
|
@@ -529,7 +710,7 @@ Two things it does not cover: commands gated behind account feature flags (the
|
|
|
529
710
|
\`${r} config refresh\`, and commands the CLI owns without a catalog entry are
|
|
530
711
|
listed by \`${r} --help\`.
|
|
531
712
|
|
|
532
|
-
Categories: ${
|
|
713
|
+
Categories: ${f}.
|
|
533
714
|
|
|
534
715
|
---
|
|
535
716
|
|
|
@@ -537,7 +718,7 @@ Categories: ${g}.
|
|
|
537
718
|
|
|
538
719
|
| File | Read it when |
|
|
539
720
|
|---|---|
|
|
540
|
-
${
|
|
721
|
+
${p}
|
|
541
722
|
|
|
542
723
|
---
|
|
543
724
|
|
|
@@ -582,7 +763,7 @@ CLI-local and never appear in \`${r} capabilities\`: auth and config
|
|
|
582
763
|
- \`${r} create "Topic"\` \u2192 load the \`${n}-presentation\` skill
|
|
583
764
|
- editing an existing deck \u2192 load the \`${n}-presentation-edit\` skill
|
|
584
765
|
- building a video from a brief or storyboard, with no deck \u2192 load the \`${n}-video\` skill
|
|
585
|
-
`}function
|
|
766
|
+
`}function un(e){let{name:t,cmd:n}=e;return`---
|
|
586
767
|
name: ${t}-presentation-edit
|
|
587
768
|
description: >
|
|
588
769
|
Use ONLY when editing an already-created presentation that has real slides:
|
|
@@ -867,7 +1048,7 @@ Do NOT render or export the presentation \u2014 that's handled by the app.
|
|
|
867
1048
|
| Create brand-new presentation (5+ slides, new topic) | \`${n} create ...\` via CLI |
|
|
868
1049
|
| Redesign the whole deck | \`${n} create ...\` via CLI, then sync |
|
|
869
1050
|
| User provides a URL to base the presentation on | \`${n} scrape <url>\` \u2192 \`${n} create ...\` |
|
|
870
|
-
`}function
|
|
1051
|
+
`}function mn(e){let{name:t,cmd:n}=e;return`---
|
|
871
1052
|
name: ${t}-presentation
|
|
872
1053
|
description: Use when user asks to create presentations, slides, decks, pitch decks.
|
|
873
1054
|
Researches the topic, gathers context, and generates AI-powered presentations via CLI.
|
|
@@ -1087,8 +1268,8 @@ ${n} import ./presentation.zip
|
|
|
1087
1268
|
- **Auth fails** \u2192 \`${n} logout && ${n} login\` (browser required)
|
|
1088
1269
|
- **"Context required"** \u2192 add \`--context\`, \`--file\`, or \`--context-file\`
|
|
1089
1270
|
- **Rate limit (429)** \u2192 check plan with \`${n} whoami\`
|
|
1090
|
-
`}var
|
|
1091
|
-
`),s=
|
|
1271
|
+
`}var Gp=[{capability:"video reference analyze",when:"Optional \u2014 match the style of a reference video."},{capability:"video storyboard create",when:"Write the storyboard. Markdown in, immutable revision out."},{capability:"video storyboard revise",when:"Iterate. Each revision is appended, never rewritten."},{capability:"video create",when:"Render a pinned revision. Paid, approval-gated, background."}];function pn(e,t){let{cmd:n,name:r,pkg:o}=e,i=new Set(t.capabilities.map(l=>l.name)),a=Gp.filter(l=>i.has(l.capability)).map((l,f)=>`${f+1}. \`${n} ${l.capability}\` \u2014 ${l.when}`).join(`
|
|
1272
|
+
`),s=Ir(t.capabilities).length;return`---
|
|
1092
1273
|
name: ${r}-video
|
|
1093
1274
|
description: >-
|
|
1094
1275
|
Use when a video must be built from scratch \u2014 a brief, a script, a storyboard,
|
|
@@ -1099,7 +1280,7 @@ description: >-
|
|
|
1099
1280
|
deck\u2192MP4 flow instead. ${s} CLI capabilities, listed in references/video.md.
|
|
1100
1281
|
---
|
|
1101
1282
|
|
|
1102
|
-
${
|
|
1283
|
+
${ge(t,e)}
|
|
1103
1284
|
|
|
1104
1285
|
# ${r} video
|
|
1105
1286
|
|
|
@@ -1153,12 +1334,12 @@ ${n} video <sub> --help
|
|
|
1153
1334
|
\`\`\`
|
|
1154
1335
|
|
|
1155
1336
|
The catalog is authoritative and always current; this file is a snapshot of it.
|
|
1156
|
-
`}function
|
|
1337
|
+
`}function ss(e,t){return[{content:cn(e,t),name:"video"},{content:dn(e,t),name:"deck-to-video"}]}import{existsSync as Rr,mkdirSync as ds,rmSync as Bp,writeFileSync as cs}from"fs";import{homedir as ms}from"os";import{basename as Wp,join as Re,relative as Kp,resolve as vt}from"path";var Le=[{name:"Claude Code",dir:".claude",provider:"claude"},{name:"GitHub Copilot",dir:".github",agentSuffix:".agent.md",provider:"copilot"},{name:"Cursor",dir:".cursor"},{name:"Codex",dir:".codex",agentSuffix:".toml",provider:"codex"},{name:"OpenCode",dir:".opencode"},{name:"Windsurf",dir:".windsurf"},{name:"Agent",dir:".agent"}];var Jp={sonnet:"claude-sonnet-4.6",haiku:"claude-haiku-4.5",opus:"claude-opus-4.6"},zp=["permissionMode","skills","subagentType"];function Xp(e,t){if(t!=="copilot")return e;let n=e.match(/^---\n([\s\S]*?)\n---\n/);if(!n)return ls(e);let r=n[1],o=e.slice((n.index??0)+n[0].length);r=r.replace(/^(model:\s*)(\S+)([ \t]*)$/m,(a,s,l,f)=>`${s}${Jp[l]??l}${f}`);for(let a of zp)r=r.replace(new RegExp(`^${a}:[^
|
|
1157
1338
|
]*
|
|
1158
|
-
?`,"m"),"");r=r.replace(/\n+$/,"");let i=
|
|
1339
|
+
?`,"m"),"");r=r.replace(/\n+$/,"");let i=ls(o);return`---
|
|
1159
1340
|
${r}
|
|
1160
1341
|
---
|
|
1161
|
-
${i}`}function
|
|
1342
|
+
${i}`}function ls(e){return e.replace(/\bAskUserQuestion\b/g,"ask the user directly in your response").replace(/\*\*Construct the Task prompt:\*\*/g,"**Construct the Task prompt (must be fully self-contained \u2014 sub-agents cannot read this conversation's history):**").replace(/\*\*Wait for all agents to complete\*\*/g,"**Wait for all agents to complete** (monitor with `/tasks` in Copilot CLI)").replace("**Launch ALL scene agents in parallel**","**Launch ALL scene agents in parallel** \u2014 each agent must write to its own `Scene[NN][Name].tsx` file. Two agents writing to the same file will silently overwrite each other (no error). Verify unique filenames before spawning.")}function Hp(e,t){let n=vt(e),r=vt(e,t);if(Kp(n,r).startsWith("..")||vt(r)!==r.replace(/\.\./g,""))throw new Error(`Invalid path: "${t}" would escape base directory`);return r}function us(e,t,n,r){let o=Re(e,"SKILL.md");if(ds(e,{recursive:!0}),cs(o,Xp(t,r),"utf-8"),n&&n.length>0){let i=Re(e,"references");ds(i,{recursive:!0});for(let a of n){let s=Re(i,`${a.name}.md`);cs(s,a.content,"utf-8")}}}function gn(e,t,n={},r){let o={installed:[],skipped:[],errors:[]},i=n.local?process.cwd():ms();if(n.dir){let a=Wp(vt(n.dir)),s=Le.find(l=>l.dir===a)?.provider;try{let l=vt(n.dir),f=Hp(l,Re("skills",e));us(f,t,r,s),o.installed.push(n.dir)}catch(l){o.errors.push(`${n.dir}: ${l instanceof Error?l.message:String(l)}`)}}else for(let a of Le){let s=Re(i,a.dir),l=Re(s,"skills",e),f=Re(l,"SKILL.md");if(Rr(s)){if(Rr(f)&&!n.force){o.skipped.push(a.name);continue}try{us(l,t,r,a.provider),o.installed.push(a.name)}catch(p){o.errors.push(`${a.name}: ${p instanceof Error?p.message:String(p)}`)}}}return o}function fn(e,t={}){let n={removed:[],errors:[]},r=t.local?process.cwd():ms();for(let o of Le){let i=Re(r,o.dir,"skills",e);if(Rr(i))try{Bp(i,{recursive:!0}),n.removed.push(o.name)}catch(a){n.errors.push(`${o.name}: ${a instanceof Error?a.message:String(a)}`)}}return n}function ps(){return Le.map(e=>e.name)}function Je(e){let{name:t,cmd:n}=e;return`---
|
|
1162
1343
|
name: ${t}-tts
|
|
1163
1344
|
description: Text-to-speech generation. Convert text to natural speech with multiple providers (Gemini, ElevenLabs, OpenAI) and voices. Use for voiceovers, narration, accessibility.
|
|
1164
1345
|
---
|
|
@@ -1358,7 +1539,7 @@ ${n} tts generate \\
|
|
|
1358
1539
|
2. **Voice matching** - Match voice style to content: Puck for upbeat, Charon for serious
|
|
1359
1540
|
3. **Speed adjustment** - Use 0.9-0.95 for narration, 1.0-1.1 for casual
|
|
1360
1541
|
4. **Multiple voiceovers** - Run \`${n} tts generate\` once per line and poll each run with \`${n} tts status <run-id>\`
|
|
1361
|
-
`}function
|
|
1542
|
+
`}function ze(e){let{name:t,cmd:n}=e;return`---
|
|
1362
1543
|
name: ${t}-music
|
|
1363
1544
|
description: Generate music that follows a video's narration and final timing. Gemini plans the provider prompt on the backend.
|
|
1364
1545
|
---
|
|
@@ -1384,7 +1565,7 @@ ${n} music status <request-id>
|
|
|
1384
1565
|
\`\`\`
|
|
1385
1566
|
|
|
1386
1567
|
The backend sends these facts to Gemini, receives the provider-ready musical direction, and makes the paid music-provider request. Retrying the same unchanged request is idempotent.
|
|
1387
|
-
`}function
|
|
1568
|
+
`}function Xe(e){let{name:t,cmd:n}=e;return`---
|
|
1388
1569
|
name: ${t}-sfx
|
|
1389
1570
|
description: Generate one sound effect aligned with a final visual event and narration. Gemini plans the provider prompt on the backend.
|
|
1390
1571
|
---
|
|
@@ -1422,7 +1603,7 @@ ${n} sfx status <request-id>
|
|
|
1422
1603
|
\`\`\`
|
|
1423
1604
|
|
|
1424
1605
|
The backend sends these facts to Gemini, receives one provider-ready SFX description, and makes the paid SFX-provider request. Retrying the same unchanged request is idempotent.
|
|
1425
|
-
`}function
|
|
1606
|
+
`}function He(e){let{name:t,cmd:n}=e;return`---
|
|
1426
1607
|
name: ${t}-mix
|
|
1427
1608
|
description: Audio mixing for video production. Combine video with voiceover and background music. Supports volume control, fade effects, and multiple audio tracks.
|
|
1428
1609
|
---
|
|
@@ -1572,7 +1753,7 @@ ${n} mix status <request-id>
|
|
|
1572
1753
|
2. **Music selection** - Choose music that doesn't compete with voice frequency.
|
|
1573
1754
|
3. **Consistent levels** - Keep voice at 100%, adjust music only.
|
|
1574
1755
|
4. **File sizes** - Use \`--no-wait\` for large files to avoid timeout.
|
|
1575
|
-
`}function
|
|
1756
|
+
`}function Ye(e){let{name:t,cmd:n}=e;return`---
|
|
1576
1757
|
name: ${t}-image
|
|
1577
1758
|
description: Image search across the web and licensed stock, plus AI image generation. Find licensed photos to publish, web images for specific real-world subjects, or generate a custom image. For videos, presentations, marketing.
|
|
1578
1759
|
---
|
|
@@ -1769,7 +1950,7 @@ Found 10 images for "mountain landscape"
|
|
|
1769
1950
|
3. **Size matters** - Use \`--size large\` for hero images
|
|
1770
1951
|
4. **JSON for automation** - Parse results programmatically
|
|
1771
1952
|
5. **Generation prompts** - Be detailed, describe style, lighting, composition
|
|
1772
|
-
`}function
|
|
1953
|
+
`}function Qe(e){let{name:t,cmd:n}=e;return`---
|
|
1773
1954
|
name: ${t}-video-search
|
|
1774
1955
|
description: Video search across the web and licensed stock. Find downloadable stock clips for b-roll and backgrounds, or web videos (YouTube, Vimeo) to embed in a slide or microsite.
|
|
1775
1956
|
---
|
|
@@ -1967,7 +2148,7 @@ ${n} video find "city timelapse" --orientation landscape -n 10
|
|
|
1967
2148
|
3. **Preview first** - Use preview URLs to check quality
|
|
1968
2149
|
4. **License** - Verify license for commercial use
|
|
1969
2150
|
5. **JSON export** - Save searches for batch processing
|
|
1970
|
-
`}function
|
|
2151
|
+
`}function Ze(e){let{name:t,cmd:n}=e;return`---
|
|
1971
2152
|
name: ${t}-scrape
|
|
1972
2153
|
description: Scrape any URL the user provides. Use when user says "check this site", "look at this URL", "use this website", "here's the link", or shares any URL for context. Supports websites, YouTube, Twitter/X.
|
|
1973
2154
|
---
|
|
@@ -2157,7 +2338,7 @@ ${n} scrape https://blog.example.com -f quiet | ${n} create "Blog Summary"
|
|
|
2157
2338
|
3. **Use JSON** - For programmatic processing of results
|
|
2158
2339
|
4. **Combine sources** - Scrape multiple URLs for comprehensive context
|
|
2159
2340
|
5. **Token count** - Check token usage for large documents
|
|
2160
|
-
`}function
|
|
2341
|
+
`}function et(e){let{name:t,cmd:n}=e;return`---
|
|
2161
2342
|
name: ${t}-branding
|
|
2162
2343
|
description: Brand profile management. Extract branding from websites, manage saved brands, apply consistent styling to presentations.
|
|
2163
2344
|
---
|
|
@@ -2267,7 +2448,7 @@ ${n} branding set-default abc123
|
|
|
2267
2448
|
2. **If extraction fails** \u2014 Proceed without branding. Do not manually create brand assets.
|
|
2268
2449
|
3. **Set default** \u2014 If you mostly work with one brand, set it as default.
|
|
2269
2450
|
4. **Override** \u2014 Use \`--brand\` flag to override default for specific presentations.
|
|
2270
|
-
`}function
|
|
2451
|
+
`}function tt(e){let{name:t,cmd:n}=e,r=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");return`---
|
|
2271
2452
|
name: ${t}-config
|
|
2272
2453
|
description: CLI configuration management. Set API keys, team IDs, custom API URLs. Verify authentication status.
|
|
2273
2454
|
---
|
|
@@ -2428,7 +2609,7 @@ ${n} config show --verify # Test API key
|
|
|
2428
2609
|
\`\`\`bash
|
|
2429
2610
|
${n} config set team-id <correct-team-id>
|
|
2430
2611
|
\`\`\`
|
|
2431
|
-
`}var
|
|
2612
|
+
`}var nt=["main","video","presentation","presentation-edit","tts","music","sfx","mix","image","video-search","scrape","branding","config"],hn=["standalone","studio"],gs={cmd:u.commands[0],pkg:u.packageName,url:u.apiUrl,name:u.name},rt=new Yp("skill").description(`Manage ${u.displayName} skills for AI coding assistants`).addHelpText("after",`
|
|
2432
2613
|
${q.bold("Skill Types:")}
|
|
2433
2614
|
${q.cyan("main")} Main CLI skill with all capabilities overview
|
|
2434
2615
|
${q.cyan("video")} Video-from-scratch pipeline (storyboard \u2192 render)
|
|
@@ -2464,51 +2645,51 @@ ${q.bold("Examples:")}
|
|
|
2464
2645
|
|
|
2465
2646
|
${q.gray("# Show skill content")}
|
|
2466
2647
|
$ ${u.commands[0]} skill show main
|
|
2467
|
-
`);
|
|
2468
|
-
${
|
|
2469
|
-
${
|
|
2470
|
-
$ ${
|
|
2471
|
-
$ ${
|
|
2472
|
-
|
|
2473
|
-
${
|
|
2474
|
-
${
|
|
2475
|
-
$ ${
|
|
2476
|
-
${
|
|
2477
|
-
$ ${
|
|
2478
|
-
${
|
|
2479
|
-
$ ${
|
|
2480
|
-
${
|
|
2481
|
-
$ ${
|
|
2482
|
-
${
|
|
2483
|
-
$ ${
|
|
2484
|
-
${
|
|
2485
|
-
$ ${
|
|
2486
|
-
${
|
|
2487
|
-
$ ${
|
|
2488
|
-
${
|
|
2489
|
-
$ ${
|
|
2490
|
-
${
|
|
2491
|
-
$ ${
|
|
2492
|
-
${
|
|
2493
|
-
$ ${
|
|
2494
|
-
${
|
|
2495
|
-
$ ${
|
|
2496
|
-
|
|
2497
|
-
${
|
|
2498
|
-
'${
|
|
2499
|
-
'${
|
|
2648
|
+
`);rt.command("install").description(`Install ${u.displayName} skills for AI coding assistants`).argument("[type]","Skill type: main, video, presentation, or omit for all").option("-d, --dir <path>","Install to specific directory").option("-g, --global","Install globally (to home directory)",!0).option("-l, --local","Install locally (to current directory)").option("-f, --force","Overwrite existing skill files").option("-m, --mode <mode>","Skill mode: standalone (render to file) or studio (Studio Preview)","standalone").action(async(e,t)=>{t.mode&&!hn.includes(t.mode)&&(d(`Invalid mode: ${t.mode}. Must be one of: ${hn.join(", ")}`),process.exit(1));let n={...gs,mode:t.mode},r=[];e&&!nt.includes(e)&&(d(`Invalid skill type: ${e}. Must be one of: ${nt.join(", ")}`),process.exit(1));let o=await at();o.source==="snapshot"&&(j(`Live capability catalog unavailable (${o.reason??"unknown reason"}) \u2014 generating from the snapshot baked into this CLI.`),console.log(q.gray(` Run \`${u.commands[0]} login\` then re-run with --force to regenerate from the live catalog.`)));let i=[...is(n,o,{branding:et(n)}),{name:"tts",content:Je(n)},{name:"music",content:ze(n)},{name:"sfx",content:Xe(n)},{name:"mix",content:He(n)},{name:"image",content:Ye(n)},{name:"video-search",content:Qe(n)},{name:"scrape",content:Ze(n)},{name:"config",content:tt(n)}];(!e||e==="main")&&r.push({name:u.name,content:ln(n,o),references:i}),(!e||e==="video")&&r.push({content:pn(n,o),name:`${u.name}-video`,references:ss(n,o)}),(!e||e==="presentation")&&r.push({name:`${u.name}-presentation`,content:mn(n)}),(!e||e==="presentation-edit")&&r.push({name:`${u.name}-presentation-edit`,content:un(n)}),e==="tts"&&r.push({name:`${u.name}-tts`,content:Je(n)}),e==="music"&&r.push({name:`${u.name}-music`,content:ze(n)}),e==="sfx"&&r.push({name:`${u.name}-sfx`,content:Xe(n)}),e==="mix"&&r.push({name:`${u.name}-mix`,content:He(n)}),e==="image"&&r.push({name:`${u.name}-image`,content:Ye(n)}),e==="video-search"&&r.push({name:`${u.name}-video-search`,content:Qe(n)}),e==="scrape"&&r.push({name:`${u.name}-scrape`,content:Ze(n)}),e==="branding"&&r.push({name:`${u.name}-branding`,content:et(n)}),e==="config"&&r.push({name:`${u.name}-config`,content:tt(n)}),console.log();for(let a of r){g(`Installing ${a.name}...`);let s=gn(a.name,a.content,{dir:t.dir,local:t.local,force:t.force},a.references);if(s.installed.length>0&&(C(`${a.name} installed successfully`),S(" Installed to",s.installed.join(", "))),s.skipped.length>0&&(g(` Skipped (already exists): ${s.skipped.join(", ")}`),console.log(q.gray(" Use --force to overwrite"))),s.errors.length>0)for(let l of s.errors)d(` ${l}`);s.installed.length===0&&s.skipped.length===0&&s.errors.length===0&&(g(" No supported AI coding assistants detected"),console.log(q.gray(` Supported editors: ${ps().join(", ")}`)),console.log(q.gray(" Use --dir <path> to install to a specific directory"))),console.log()}});rt.command("show").description("Display skill content").argument("[type]","Skill type (default: main)").option("-m, --mode <mode>","Skill mode: standalone or studio","standalone").action(async(e="main",t)=>{t.mode&&!hn.includes(t.mode)&&(d(`Invalid mode: ${t.mode}. Must be one of: ${hn.join(", ")}`),process.exit(1));let n={...gs,mode:t.mode},r=await at(),i={main:()=>ln(n,r),video:()=>pn(n,r),presentation:()=>mn(n),"presentation-edit":()=>un(n),tts:()=>Je(n),music:()=>ze(n),sfx:()=>Xe(n),mix:()=>He(n),image:()=>Ye(n),"video-search":()=>Qe(n),scrape:()=>Ze(n),branding:()=>et(n),config:()=>tt(n)}[e];i?console.log(i()):(d(`Invalid skill type: ${e}. Must be one of: ${nt.join(", ")}`),process.exit(1))});rt.command("uninstall").description(`Remove ${u.displayName} skills from AI coding assistants`).argument("[type]","Skill type: main, video, presentation, or omit for all").option("-g, --global","Uninstall globally (from home directory)",!0).option("-l, --local","Uninstall locally (from current directory)").action(async(e,t)=>{let n=[];e&&!nt.includes(e)&&(d(`Invalid skill type: ${e}. Must be one of: ${nt.join(", ")}`),process.exit(1)),(!e||e==="main")&&n.push(u.name),(!e||e==="video")&&n.push(`${u.name}-video`),(!e||e==="presentation")&&n.push(`${u.name}-presentation`),(!e||e==="presentation-edit")&&n.push(`${u.name}-presentation-edit`),(!e||e==="tts")&&n.push(`${u.name}-tts`),(!e||e==="music")&&n.push(`${u.name}-music`),(!e||e==="sfx")&&n.push(`${u.name}-sfx`),(!e||e==="mix")&&n.push(`${u.name}-mix`),(!e||e==="image")&&n.push(`${u.name}-image`),(!e||e==="video-search")&&n.push(`${u.name}-video-search`),(!e||e==="scrape")&&n.push(`${u.name}-scrape`),(!e||e==="branding")&&n.push(`${u.name}-branding`),(!e||e==="config")&&n.push(`${u.name}-config`),console.log();for(let r of n){let o=fn(r,{local:t.local});if(o.removed.length>0?(C(`${r} uninstalled`),S(" Removed from",o.removed.join(", "))):g(` ${r} not found`),o.errors.length>0)for(let i of o.errors)j(` Failed to remove: ${i}`)}console.log()});import{Command as Qp}from"commander";import xt from"chalk";var fs=new Qp("templates").description("List slide design templates (use with `create --template <id>`)").argument("[search]","Filter templates by name, description, or category").option("-f, --format <format>","Output format (table, json)","table").option("--limit <n>","Maximum templates to list","25").action(async(e,t)=>{await A();try{let n=Number.parseInt(t.limit??"25",10),{templates:r}=await co(e,Number.isFinite(n)?n:25);if(r.length===0){t.format==="json"?console.log(JSON.stringify([])):g("No templates found");return}if(t.format==="json"){console.log(JSON.stringify(r,null,2));return}for(let o of r){let i=[o.isDefault?xt.green("default"):null,o.category??null,o.recommendedModes?.length?`modes: ${o.recommendedModes.join("/")}`:null].filter(Boolean).join(" \xB7 ");console.log(`${xt.bold(o.name)} ${xt.gray(o.id)}${i?`
|
|
2649
|
+
${xt.gray(i)}`:""}`)}console.log(),console.log(xt.gray(`Use one with: ${u.commands[0]} create "<topic>" --template <id>`))}catch(n){d(n instanceof Error?n.message:String(n)),process.exit(n.exitCode??1)}});import{Command as Zp}from"commander";import Sr from"chalk";var hs=new Zp("whoami").description("Show current user and team information").option("-f, --format <format>","Output format (human, json)","human").action(async e=>{await A();try{let t=await he();if(En(),e.format==="json"){console.log(JSON.stringify(t,null,2));return}se("User"),console.log(),S("Email",t.user.email),t.user.username&&S("Username",t.user.username),(t.user.firstName||t.user.lastName)&&S("Name",[t.user.firstName,t.user.lastName].filter(Boolean).join(" "));let n=t.authType==="apiKey"?"API Key":t.authType==="oauth"?"OAuth":"Session";if(S("Auth Type",n),t.currentTeam&&(console.log(),se("Current Team"),console.log(),S("ID",t.currentTeam.id),S("Name",t.currentTeam.name),S("Plan",t.currentTeam.planName),S("Role",t.currentTeam.isOwner?"Owner":"Member")),t.teams.length>1){console.log(),se("All Teams"),console.log();for(let r of t.teams){let o=r.isCurrent?Sr.green(" (current)"):"";console.log(` ${Sr.bold(r.name)}${o}`),console.log(Sr.gray(` ID: ${r.id} | Plan: ${r.planName} | Role: ${r.role}`))}}console.log()}catch(t){d(t instanceof Error?t.message:String(t)),process.exit(t.exitCode??1)}});function ys(e){return e[0]==="--"?e.slice(1):e}var tg="0.3.19",B=new eg,D=u.commands[0];B.name(D).description(`${u.displayName} CLI \u2014 presentations, videos, avatars, audio, branding, media and research`).version(tg,"-v, --version","Show version number").option("--debug","Enable debug logging").option("--no-color","Disable colored output").configureOutput({outputError:(e,t)=>{t(V.red(e))}});B.addCommand(Mo);Za(B);B.addCommand(ti);B.addCommand(An);B.addCommand(ei);B.addCommand(fs);B.addCommand(Qo);B.addCommand(Jo);B.addCommand(hs);B.addCommand(ai);B.addCommand(si);B.addCommand(Ko);B.addCommand(rt);B.addCommand(Mt);var bs=Ho();bs.commands.length>0&&B.addCommand(bs);function ng(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r++){let o=[r];for(let i=1;i<=t.length;i++){let a=e[r-1]===t[i-1]?0:1;o[i]=Math.min(o[i-1]+1,n[i]+1,n[i-1]+a)}n=o}return n[t.length]}function rg(e){let t=e.toLowerCase(),n=t.length<=4?1:2,r,o=Number.POSITIVE_INFINITY;for(let i of B.commands)for(let a of[i.name(),...i.aliases()]){let s=ng(t,a.toLowerCase());s<o&&(o=s,r=i.name())}return r!==void 0&&o<=n?r:void 0}B.on("command:*",e=>{let t=String(e[0]);console.error(V.red(`Error: Unknown command '${t}'`)),console.error();let n=rg(t);n&&console.error(`Did you mean '${n}'?`),console.error(`Run '${D} --help' to see available commands.`),console.error(`Run '${D} capabilities' for the full list of callable capabilities.`),process.exit(1)});B.addHelpText("after",`
|
|
2650
|
+
${V.bold("Start here:")}
|
|
2651
|
+
$ ${D} capabilities ${V.gray("# every capability + its exact command path")}
|
|
2652
|
+
$ ${D} <group> --help ${V.gray("# drill into any command group above")}
|
|
2653
|
+
|
|
2654
|
+
${V.bold("Common tasks:")}
|
|
2655
|
+
${V.gray("Make a presentation")}
|
|
2656
|
+
$ ${D} create "<topic>" --context "..."
|
|
2657
|
+
${V.gray("Turn a finished presentation into an MP4 (narration + avatar)")}
|
|
2658
|
+
$ ${D} presentation video <slug>
|
|
2659
|
+
${V.gray("Export a presentation as a ZIP of HTML + assets")}
|
|
2660
|
+
$ ${D} export <slug> -o deck.zip
|
|
2661
|
+
${V.gray("Make a video from scratch (no deck)")}
|
|
2662
|
+
$ ${D} video storyboard create ${V.gray("then")} $ ${D} video create
|
|
2663
|
+
${V.gray("Regenerate one slide's narration in a video draft")}
|
|
2664
|
+
$ ${D} presentation video-narration <project-id>
|
|
2665
|
+
${V.gray("Generate speaker notes")}
|
|
2666
|
+
$ ${D} presentation speaker-notes <presentation-id>
|
|
2667
|
+
${V.gray("Import a PowerPoint")}
|
|
2668
|
+
$ ${D} presentation import
|
|
2669
|
+
${V.gray("Extract a brand identity from a URL")}
|
|
2670
|
+
$ ${D} branding extract <url>
|
|
2671
|
+
${V.gray("Voiceover, music, sound effects")}
|
|
2672
|
+
$ ${D} tts generate | ${D} music generate | ${D} sfx generate
|
|
2673
|
+
${V.gray("Find stock footage / images")}
|
|
2674
|
+
$ ${D} video find | ${D} image search
|
|
2675
|
+
${V.gray("Read a web page or a YouTube transcript")}
|
|
2676
|
+
$ ${D} scrape <url> | ${D} transcript <url>
|
|
2677
|
+
|
|
2678
|
+
${V.bold("Two different video pipelines:")}
|
|
2679
|
+
'${D} presentation video ...' renders an EXISTING deck to MP4.
|
|
2680
|
+
'${D} video ...' builds a video from a storyboard or brief with stock
|
|
2500
2681
|
and generated footage \u2014 no deck involved.
|
|
2501
2682
|
|
|
2502
|
-
${
|
|
2503
|
-
Run '${
|
|
2683
|
+
${V.bold("Authentication:")}
|
|
2684
|
+
Run '${D} login' to authenticate (recommended).
|
|
2504
2685
|
Or set CC_SLIDES_API_KEY environment variable for API key auth.
|
|
2505
2686
|
|
|
2506
|
-
${
|
|
2687
|
+
${V.bold("Note:")}
|
|
2507
2688
|
The command list above is not always complete: feature-flag-gated commands
|
|
2508
|
-
(the '${
|
|
2509
|
-
and '${
|
|
2510
|
-
'${
|
|
2689
|
+
(the '${D} derive' subcommands) appear only after '${D} login'
|
|
2690
|
+
and '${D} config refresh' have cached your feature access. Run
|
|
2691
|
+
'${D} capabilities' for the authoritative list.
|
|
2511
2692
|
|
|
2512
|
-
${
|
|
2513
|
-
${
|
|
2514
|
-
`);
|
|
2693
|
+
${V.bold("More Info:")}
|
|
2694
|
+
${V.blue(u.docsUrl)}
|
|
2695
|
+
`);B.parse(ys(process.argv.slice(2)),{from:"user"});
|