@conceptcraft/mindframes 0.3.28 → 0.3.29
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 +13 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -61,7 +61,7 @@ ${n.text}`}function zo(e,t){return t?e.messages.filter(r=>r.text.trim()).at(-1)?
|
|
|
61
61
|
`),usage:c}}function Vl(e){return e.trim().replace(/\s+/g," ").toLocaleLowerCase()}import{randomUUID as kw}from"crypto";import{mkdir as xw}from"fs/promises";import{hostname as ti,platform as Rw}from"os";import{join as Cw}from"path";var vn=class extends Error{constructor(n,r,i=!1){super(n);this.statusCode=r;this.reRegister=i;this.name="RunnerApiError"}statusCode;reRegister};async function In(e,t={}){let n=await fe();t.body!==void 0&&(n["Content-Type"]="application/json");let r=new AbortController,i=setTimeout(()=>r.abort(),t.timeoutMs??3e4),o=()=>r.abort();t.signal?.addEventListener("abort",o,{once:!0});try{let c=await fetch(`${K()}${e}`,{body:t.body!==void 0?JSON.stringify(t.body):void 0,headers:n,method:t.method??"GET",signal:r.signal}),l=await c.text(),d={};try{d=l?JSON.parse(l):{}}catch{d={}}if(!c.ok){let g=mt(l,c.status);throw new vn(`[${g.code}] ${g.message}`,c.status,d.reRegister===!0)}return d}finally{clearTimeout(i),t.signal?.removeEventListener("abort",o)}}async function Gl(e){await In("/api/runner/register",{body:e,method:"POST",timeoutMs:15e3})}async function Kl(e,t){return(await In(`/api/runner/work?runnerId=${encodeURIComponent(e)}`,{signal:t,timeoutMs:28e3})).job??null}async function Wl(e){await In("/api/runner/heartbeat",{body:{runnerId:e},method:"POST",timeoutMs:1e4})}async function Jl(e,t){return{cancelRequested:(await In(`/api/runner/jobs/${encodeURIComponent(e)}/events`,{body:{events:t},method:"POST",timeoutMs:15e3})).cancelRequested===!0}}async function Qo(e,t,n){await In(`/api/runner/jobs/${encodeURIComponent(e)}/complete`,{body:{result:n,runnerId:t},method:"POST",timeoutMs:15e3})}async function ei(e,t,n,r=!0){await In(`/api/runner/jobs/${encodeURIComponent(e)}/fail`,{body:{message:n,retryable:r,runnerId:t},method:"POST",timeoutMs:15e3})}var kn=class extends Error{runId;timeoutMs;constructor(t,n){super(t),this.name="PollTimeoutError",this.runId=n.runId,this.timeoutMs=n.timeoutMs}};function zl(e,t){let n=Math.max(0,e-1),r=Math.min(t.capMs,t.baseMs*2**Math.min(n,30));return Math.floor(r*(t.random??Math.random)())}function Zo(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=setTimeout(i,e);function i(){clearTimeout(r),t?.removeEventListener("abort",i),n()}t?.addEventListener("abort",i,{once:!0})})}async function Hl(e){let t=e.timeoutMs??18e5;if(!Number.isFinite(t)||t<=0)throw new Error("pollUntil requires a positive finite timeoutMs.");let n=e.now??Date.now,r=n()+t,i=await e.poll();for(;!e.isDone(i);){e.onValue?.(i);let o=r-n();if(o<=0)throw e.timeoutError?.(t)??new kn(`Poll timed out after ${Math.round(t/1e3)}s.`,{timeoutMs:t});await Zo(Math.min(Math.max(0,e.intervalMs(i)),o),e.signal),i=await e.poll()}return i}import{mkdirSync as bw,readFileSync as ww,writeFileSync as Xl}from"fs";import{dirname as vw,join as Iw}from"path";function ea(e){return Iw(e,"sessions.json")}function ta(e){try{let t=ww(ea(e),"utf8"),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return{}}function Yl(e,t,n){return t?ta(e)[t]?.[n]??null:null}function Ql(e,t,n,r){if(!(!t||!r))try{let i=ea(e);bw(vw(i),{recursive:!0});let o=ta(e);o[t]={...o[t],[n]:r},Xl(i,`${JSON.stringify(o,null," ")}
|
|
62
62
|
`,"utf8")}catch{}}function Zl(e,t,n){if(t)try{let r=ta(e);if(!r[t])return;delete r[t][n],Xl(ea(e),`${JSON.stringify(r,null," ")}
|
|
63
63
|
`,"utf8")}catch{}}var Sw=300,Ew=3e4,Pw=5*6e4;async function em(e){let[t,n]=await Promise.all([Qr(e.claudeBin),Zr(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"]:[]],i=`${ti().split(".")[0]}-${kw().slice(0,8)}`,o=()=>Gl({capabilities:["chat_turn","proof"],claudeCodeVersion:t?.version??null,cliVersion:e.version,codexVersion:n?.version??null,hostname:ti(),platform:Rw(),runnerId:i,runtimes:r});await o(),e.log(`Registered as ${i} (runtimes: ${r.join(", ")}). Waiting for work\u2026`);let c=0,l=0;for(;!e.signal?.aborted;){let d=null;try{d=await Kl(i,e.signal),c=0}catch(g){if(e.signal?.aborted)break;if(g instanceof vn&&g.reRegister){e.log("Server asked for re-registration.");try{await o(),l=0}catch(y){l+=1;let v=y instanceof Error?y.message:String(y);e.log(`Re-registration failed (${l} consecutive): ${v} Retrying with backoff.`)}}else e.log("Work poll failed; retrying\u2026");c+=1,await Zo(zl(c,{baseMs:e.pollBackoffMs??5e3,capMs:Pw}),e.signal);continue}if(!d){if(e.once)continue;continue}if(e.log(`Claimed ${d.jobType} job ${d.runId}.`),await Aw({claude:t,codex:n,job:d,options:e,runnerId:i}),e.once)break}}async function Aw({claude:e,codex:t,job:n,options:r,runnerId:i}){let o=new AbortController,c=()=>o.abort();r.signal?.addEventListener("abort",c,{once:!0});let l=setInterval(()=>{Wl(i).catch(()=>{})},Ew),d=[],g=!1,y=async()=>{if(g||d.length===0)return;g=!0;let T=d.splice(0,100);try{let{cancelRequested:L}=await Jl(n.runId,T);L&&o.abort()}catch(L){L instanceof vn&&L.statusCode===409&&o.abort()}finally{g=!1}},v=setInterval(()=>{y()},Sw),x=T=>{d.push(T)};try{if(n.jobType==="runner.proof"){let T=typeof n.input.message=="string"?n.input.message:"proof";x({eventType:"proof.echo",payload:{message:T}}),await na(y,d),await Qo(n.runId,i,{echo:T}),r.log(`Proof job ${n.runId} completed.`);return}if(n.jobType==="runner.chat_turn"){let T=n.input.runtime==="codex"?"codex":"claude-code",L=T==="codex"?t&&{detection:t,run:Bl}:e&&{detection:e,run:jl};if(!L){await ei(n.runId,i,T==="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 $=typeof n.input.chatId=="string"&&n.input.chatId?n.input.chatId:null,N=Cw(r.workspaceRoot,"chats",$??n.runId);await xw(N,{recursive:!0});let S=Tw(n.input),E=re=>x({eventType:re.eventType,message:re.message??null,payload:re.eventType==="chat.session"?{host:ti(),runtime:T,runtimeVersion:L.detection.version,...re.payload??{}}:re.payload??{}}),A=Yl(r.workspaceRoot,$,T),D;try{D=await L.run({bin:L.detection.bin,input:S,onEvent:E,resumeSessionId:A,signal:o.signal,workspace:N})}catch(re){if(!A||o.signal.aborted)throw re;r.log(`Resume of ${T} session failed; retrying fresh.`),Zl(r.workspaceRoot,$,T),D=await L.run({bin:L.detection.bin,input:S,onEvent:E,resumeSessionId:null,signal:o.signal,workspace:N})}Ql(r.workspaceRoot,$,T,D.sessionId),x({eventType:"chat.session",payload:{host:ti(),runtime:T,runtimeVersion:L.detection.version,sessionId:D.sessionId,sessionPath:D.sessionPath}}),await na(y,d),await Qo(n.runId,i,{modelId:D.modelId,runtime:T,runtimeVersion:L.detection.version,sessionId:D.sessionId,sessionPath:D.sessionPath,text:D.text,usage:D.usage??{}}),r.log(`Chat turn ${n.runId} (${T}) completed.`);return}await ei(n.runId,i,`This runner does not support ${n.jobType} jobs. Update the desktop app / CLI.`,!1)}catch{let L="Local runner job crashed.";r.log(`Job ${n.runId} failed: ${L}`),await na(y,d).catch(()=>{}),await ei(n.runId,i,L).catch(()=>{})}finally{clearInterval(v),clearInterval(l),r.signal?.removeEventListener("abort",c)}}function Tw(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 na(e,t){for(;t.length>0;)await e(),t.length>0&&await new Promise(n=>setTimeout(n,25))}function Nw(){return $w(Ow(),`.${f.commands[0]}-runner`,"runs")}var ni=new Dw("runner").description("Run agent work locally with your own Claude Code / Codex login (desktop lane)");ni.command("status").description("Check local Claude Code / Codex detection and account auth").action(async()=>{let[e,t]=await Promise.all([Qr(),Zr()]);if(console.log(e?qe.green(`\u2713 Claude Code ${e.version}`):qe.red("\u2717 Claude Code not found on PATH")),console.log(t?qe.green(`\u2713 Codex ${t.version} (${t.bin})`):qe.red("\u2717 Codex not found (PATH or Codex.app)")),!Ze()){console.log(qe.red(`\u2717 Not logged in. Run '${f.commands[0]} login' first.`)),process.exitCode=2;return}try{let n=await Je();console.log(qe.green(`\u2713 Logged in as ${n.user.email}`))}catch{console.log(qe.red("\u2717 Auth check failed. Please sign in again and retry.")),process.exitCode=2}});ni.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=>{Ze()||(console.error(qe.red(`Not authenticated. Run '${f.commands[0]} login' first.`)),process.exit(2));let t=new AbortController,n=()=>{console.log(qe.gray(`
|
|
64
|
-
Stopping runner\u2026`)),t.abort()};process.on("SIGINT",n),process.on("SIGTERM",n);try{await em({claudeBin:e.claudeBin,codexBin:e.codexBin,log:r=>console.log(qe.gray(`[runner] ${r}`)),once:e.once,signal:t.signal,version:"0.3.28",workspaceRoot:e.workspace??Nw()})}catch{console.error(qe.red("The local runner failed. Check the runner logs and try again.")),process.exit(1)}});import se from"chalk";import{Command as P$}from"commander";import{Command as ra}from"commander";import{readFileSync as Lw}from"fs";function _(e,t=()=>Lw(0,"utf8")){if(e.approvalReceipt&&e.approvalReceiptStdin)throw new P("Pass only one approval receipt input mode.",400);let n=e.approvalReceiptStdin?t().trim():e.approvalReceipt;if(e.approvalReceiptStdin&&!n)throw new P("No approval receipt was provided on stdin.",400);return n}function $t(e,t){return[...t,e]}function Uw(e){let[t,n]=e.split("@");return n?{templateId:t,version:Number.parseInt(n,10)}:{templateId:t}}function _w(e){if(typeof e.static=="string")return JSON.parse(e.static);let t=e.template;if(t.length)return{allowPreLaunch:e.allowPreLaunch?!0:void 0,audience:e.audience,imagery:e.imagery,market:e.market,productId:e.productId,sizes:e.size,templates:t.map(Uw),variations:e.variations??1}}var jw=new ra("create").description("Start durable ad-set generation").argument("<title>","Ad-set title").requiredOption("--brief <brief>","Campaign brief").option("--hook <text>","Opening hook (repeat)",$t,[]).option("--angle <text>","Creative angle (repeat)",$t,[]).option("--cta <text>","Call to action (repeat)",$t,[]).option("--voice <text>","Voice or persona (repeat)",$t,[]).option("--aspect <ratio>","9:16, 1:1, or 16:9 (repeat)",$t,[]).option("--duration <seconds>","Creative duration in seconds",e=>Number.parseInt(e,10)).option("--max-variations <count>","Maximum generated variations",e=>Number.parseInt(e,10)).option("--review-policy <policy>","review or auto_save").option("--style <style>","ugc, clean, cinematic, or testimonial","ugc").option("--format <format>","video (default) or static").option("--template <id[@version]>","Static: approved ad template (repeat)",$t,[]).option("--size <id>","Static: size id, e.g. 300x250 (repeat)",$t,[]).option("--variations <count>","Static: distinct variations per template",e=>Number.parseInt(e,10)).option("--audience <audience>","Static: claim scope audience").option("--market <market>","Static: claim scope market").option("--product-id <id>","Static: claim scope product").option("--allow-pre-launch","Static: allow pre-launch claims (flagged)").option("--imagery <mode>","Static: approved-only (default) or generate-backgrounds").option("--static <json>","Static: the whole static block as JSON").option("--branding-id <id>","Branding ID").option("--team-id <id>","Workspace ID").requiredOption("--idempotency-key <key>","Stable invocation key bound into the approval receipt").option("--approval-receipt <receipt>","Receipt returned by the browser confirmation URL; omit on the first call to get that URL").option("--approval-receipt-stdin","Read the approval receipt from stdin instead of argv").option("--yes","Approve generation").action(async(e,t)=>{if(!t.yes)return a("Pass --yes to approve generation");try{let n=_w(t),r=t.format??(n?"static":void 0);m(await p("createAdSet",{format:r,static:n,angles:t.angle.length?t.angle:void 0,approvalReceipt:_(t),aspects:t.aspect.length?t.aspect:void 0,brandingId:t.brandingId,brief:t.brief,ctas:t.cta.length?t.cta:void 0,durationSec:t.duration,hooks:r==="static"?void 0:t.hook.length?t.hook:[t.brief],maxVariations:t.maxVariations,reviewPolicy:t.reviewPolicy,style:r==="static"?void 0:t.style,teamId:t.teamId,title:e,voices:t.voice.length?t.voice:void 0},t.idempotencyKey))}catch(n){a(u(n,"Generation failed")),process.exit(s.GENERAL_ERROR)}}),qw=new ra("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 R("createAdSet",e,t.teamId))}catch(n){a(u(n,"Status failed")),process.exit(s.GENERAL_ERROR)}}),tm=new ra("ad-set").description("Generate a set of ad creatives (hooks, copy, visuals) from a campaign brief").addCommand(jw).addCommand(qw);import{randomUUID as nm}from"crypto";import{readFileSync as Mw}from"fs";import{Command as Qn}from"commander";var Vw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ri(e,t){Vw.test(e)||(a(`"${e}" is not a ${t} id.`),process.exit(s.INVALID_INPUT))}function rm(e,t){try{return Mw(e,"utf8")}catch{a(`${t}: cannot read file "${e}".`),process.exit(s.INVALID_INPUT)}}function ia(e,t){let n=rm(e,t);try{return JSON.parse(n)}catch{a(`${t}: "${e}" is not valid JSON.`),process.exit(s.INVALID_INPUT)}}function oa(e,t){let n=Number(e);return(!Number.isInteger(n)||n<1)&&(a(`${t} must be a positive integer.`),process.exit(s.INVALID_INPUT)),n}function im(e){return{html:rm(e.html,"--html"),legalPlacement:ia(e.legalPlacement,"--legal-placement"),sizes:ia(e.sizes,"--sizes"),slotSchema:ia(e.slotSchema,"--slot-schema"),...e.teamId?{teamId:e.teamId}:{}}}function om(e){return e.requiredOption("--html <file>","Template HTML file").requiredOption("--slot-schema <file>","JSON file: slot name \u2192 { type, required, label?, maxLength?, maxItems? }").requiredOption("--sizes <file>",'JSON file: [{ "id": "1x1", "label": "Feed square", "width": 1080, "height": 1080 }]').requiredOption("--legal-placement <file>",'JSON file: size id \u2192 { "isi": { "variant": "abbreviated", "minFontPx": 12 } }').option("--idempotency-key <key>","Reuse a request key to retry this same save").option("--team-id <id>","Workspace ID")}async function ii(e,t,n,r){try{m(await p(e,t,r))}catch(i){a(u(i,n)),process.exit(s.GENERAL_ERROR)}}var Fw=new Qn("list").description("List a brand's governed ad templates").option("--brand-id <id>","Brand profile ID (default: the default brand)").option("--format-family <family>","static, carousel or video").option("--limit <n>","Maximum templates to return (1-100)").option("--team-id <id>","Workspace ID").action(async e=>{await w(),e.brandId&&ri(e.brandId,"brand"),await ii("listAdTemplates",{...e.brandId?{brandId:e.brandId}:{},...e.formatFamily?{formatFamily:e.formatFamily}:{},...e.limit?{limit:oa(e.limit,"--limit")}:{},...e.teamId?{teamId:e.teamId}:{}},"List failed")}),Bw=new Qn("get").description("Read one ad template version with its HTML and lint report").argument("<template-id>","Ad template ID").option("--template-version <n>","Version to read (default: latest)").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await w(),ri(e,"template"),await ii("getAdTemplate",{templateId:e,...t.templateVersion?{version:oa(t.templateVersion,"--template-version")}:{},...t.teamId?{teamId:t.teamId}:{}},"Read failed")}),Gw=om(new Qn("create").description("Create an ad template as a draft (version 1)").requiredOption("--brand-id <id>","Brand profile ID").requiredOption("--name <name>","Template name").option("--format-family <family>","static (default), carousel or video")).action(async e=>{await w(),ri(e.brandId,"brand"),await ii("createAdTemplate",{brandId:e.brandId,name:e.name,...e.formatFamily?{formatFamily:e.formatFamily}:{},...im(e)},"Create failed",e.idempotencyKey??nm())}),Kw=om(new Qn("update").description("Save an edited template as a new draft version (earlier versions stay unchanged)").argument("<template-id>","Ad template ID").requiredOption("--expected-latest-version <n>","The latest version you edited; a stale value is refused").option("--name <name>","Rename the template")).action(async(e,t)=>{await w(),ri(e,"template"),await ii("updateAdTemplate",{templateId:e,expectedLatestVersion:oa(t.expectedLatestVersion,"--expected-latest-version"),...t.name?{name:t.name}:{},...im(t)},"Save failed",t.idempotencyKey??nm())}),am=new Qn("ad-template").description("Governed ad templates: list, read, and save drafts (a person approves them in the app)").addCommand(Fw).addCommand(Bw).addCommand(Gw).addCommand(Kw);import{randomUUID as lm}from"crypto";import{readFileSync as mm}from"fs";import{readFile as Xw}from"fs/promises";import{Command as Me}from"commander";import{randomUUID as Ww}from"crypto";function nt(e,t){a(u(e,t)),process.exit(e instanceof P?e.exitCode:s.GENERAL_ERROR)}function Zn(e){return`cli:agent-management:${e}:${Ww()}`}function xn(e,t){let n=Number(e);if(!Number.isInteger(n)||n<=0)throw new Error(`${t} must be a positive integer`);return n}import{Command as er}from"commander";var Jw=new er("list").description("List one roster page: your Agents plus teammates' team-visible Agents").option("--cursor <cursor>","Continue from a previous nextCursor").option("--page-size <n>","Roster rows to return (1-100)","50").option("--team-id <id>","Workspace ID").action(async e=>{try{m(await p("listAgentRoster",{cursor:e.cursor,pageSize:xn(e.pageSize,"--page-size"),teamId:e.teamId}))}catch(t){nt(t,"Could not list the Agent roster")}}),zw=new er("get").description("Read one roster-visible Agent card without private configuration").argument("<agent-id>","Roster-visible Agent UUID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await p("getRosterAgent",{agentId:e,teamId:t.teamId}))}catch(n){nt(n,"Could not read the roster Agent")}}),sm=new er("roster").description("Discover Agents shared inside the current workspace; never cross-workspace").addCommand(Jw).addCommand(zw),Hw=new er("set").description("Share an owned Agent with the workspace or make it private").argument("<agent-id>","Owned scheduled Agent UUID").argument("<visibility>","Desired visibility: private or team",b("visibility",["private","team"])).requiredOption("--expected-visibility <visibility>","Current value from agent roster get: private, team, or legacy public",b("--expected-visibility",["private","team","public"])).option("--idempotency-key <key>","Reuse only for an exact retry of this visibility change").option("--team-id <id>","Workspace ID").action(async(e,t,n)=>{try{m(await p("setAgentVisibility",{agentId:e,expectedVisibility:n.expectedVisibility,teamId:n.teamId,visibility:t},n.idempotencyKey?.trim()||Zn("visibility")))}catch(r){nt(r,"Could not change Agent visibility")}}),dm=new er("visibility").description("Control whether an owned Agent is private or team-visible").addCommand(Hw);function Rn(e,t){return[...t,e]}function Yw(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw new Error("Expected a positive integer.");return t}async function oi(e,t){let n=t.trim(),r=n.startsWith("{")?n:await Xw(n,"utf8"),i=JSON.parse(r);if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`${e} must contain one JSON object.`);return i}var Qw=new Me("create").description("Activate a reviewed Agent draft; get browser approval, then retry with the same key and receipt.").argument("<draft-id>","Reviewed agent draft UUID").requiredOption("--expected-version <number>","Exact draft version shown during review",Yw).requiredOption("--idempotency-key <key>","Stable key bound into the approval receipt and reused on retry").option("--approval-receipt <receipt>","Receipt from the browser confirmation URL").option("--yes","Confirm activation intent; this never substitutes for the approval receipt").option("--team-id <id>","Workspace ID").action(async(e,t)=>{t.yes||(a("Pass --yes to request activation. A server-issued approval receipt is still required."),process.exit(s.INVALID_INPUT)),await pm("Agent activation failed",()=>p("createAgent",{approvalReceipt:t.approvalReceipt,draftId:e,expectedVersion:t.expectedVersion,teamId:t.teamId},t.idempotencyKey))}),Zw=new Me("recommend").description("Save a private inactive scheduled-agent draft for review; this command never activates or runs it.").argument("<name>","Agent name").requiredOption("--instructions <markdown>","Standing agent instructions").option("--description <text>","Agent description","").option("--goal <text>","User-visible recurring objective").option("--rationale <text>","Why this draft is being recommended").option("--schedule <frequency>","manual, daily, weekdays, weekly, or monthly").option("--schedule-r-rule <rrule>","Precise recurrence rule").option("--schedule-time <hh:mm>","Local run time").option("--timezone <zone>","IANA timezone").option("--schedule-config <json-or-path>","Full schedule configuration as inline JSON or a JSON file").option("--source <connector>","Source connector (repeatable)",Rn,[]).option("--x-handle-target <handle>","Target for the x_handle source").option("--x-search-target <query>","Query for the x_search source").option("--primary-output <adapter>","Legacy primary output fallback").option("--output <adapter>","Output adapter (repeatable)",Rn,[]).option("--output-config <json-or-path>","Full output slot configuration (repeatable)",Rn,[]).option("--delivery-adapter <adapter>","Delivery adapter").option("--delivery-config <json-or-path>","Full delivery configuration as inline JSON or a JSON file").option("--review-policy <policy>","manual_review, auto_send, or draft_only","manual_review").option("--runtime <json-or-path>","Scheduled runtime configuration as inline JSON or a JSON file").option("--sandbox-blueprint-id <id>","Sandbox blueprint UUID").option("--idempotency-key <key>","Stable retry key").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await pm("Agent recommendation failed",async()=>p("recommendAgent",{deliveryAdapter:t.deliveryAdapter,deliveryConfig:t.deliveryConfig?await oi("--delivery-config",t.deliveryConfig):void 0,description:t.description,goal:t.goal,instructionsMarkdown:t.instructions,name:e,outputAdapter:t.primaryOutput,outputAdapters:t.output.length?t.output:void 0,outputConfigs:t.outputConfig.length?await Promise.all(t.outputConfig.map(n=>oi("--output-config",n))):void 0,rationale:t.rationale,reviewPolicy:t.reviewPolicy,runtime:t.runtime?await oi("--runtime",t.runtime):void 0,sandboxBlueprintId:t.sandboxBlueprintId,schedule:t.schedule,scheduleConfig:t.scheduleConfig?await oi("--schedule-config",t.scheduleConfig):void 0,scheduleRRule:t.scheduleRRule,scheduleTime:t.scheduleTime,sourceConnectors:t.source.length?t.source:void 0,teamId:t.teamId,timezone:t.timezone,xHandleTarget:t.xHandleTarget,xSearchTarget:t.xSearchTarget},t.idempotencyKey??lm()))});async function pm(e,t){try{m(await t())}catch(n){if(n instanceof P){let r=`[${n.errorCode}] `;console.error(JSON.stringify({error:{code:n.errorCode,message:n.message.startsWith(r)?n.message.slice(r.length):n.message,retryable:n.retryable},ok:!1})),process.exit(n.exitCode)}console.error(JSON.stringify({error:{code:"operation_failed",message:u(n,e),retryable:!1},ok:!1})),process.exit(s.GENERAL_ERROR)}}function ev(e,t){return e==="none"?null:xn(e,t)}function tv(e){return e==="none"?null:e}function Dt(e,t){let n;try{n=mm(e,"utf8")}catch(r){throw new Error(`${t} could not read ${e}: ${u(r,"unknown file error")}`)}try{return JSON.parse(n)}catch(r){throw new Error(`${t} must point to valid JSON: ${u(r,"invalid JSON")}`)}}function nv(e,t){try{return mm(e,"utf8")}catch(n){throw new Error(`${t} could not read ${e}: ${u(n,"unknown file error")}`)}}var rv=new Me("list").description("List all owned Agents, following cursor pages to closure").option("--cursor <cursor>","Resume from a previous nextCursor").option("--page-size <n>","Rows fetched per page","50").option("--team-id <id>","Workspace ID").action(async e=>{try{let t=[],n=e.cursor;for(;;){let r=await p("listAgents",{cursor:n,pageSize:xn(e.pageSize,"--page-size"),teamId:e.teamId});if(t.push(...r.agents),!r.hasMore||!r.nextCursor)break;n=r.nextCursor}m({agents:t,total:t.length})}catch(t){nt(t,"Could not list Agents")}}),iv=new Me("get").description("Read one owned Agent and its complete configuration").argument("<agent-id>","Scheduled Agent UUID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await p("getAgent",{agentId:e,teamId:t.teamId}))}catch(n){nt(n,"Could not read the Agent")}}),ov=new Me("configure").description("Update Agent configuration; enable automatic external delivery in the browser").argument("<agent-id>","Scheduled Agent UUID").requiredOption("--expected-version <n>","Version returned by agent get").option("--name <text>","Agent name").option("--description <text>","Agent description").option("--goal <text>","Recurring objective").option("--instructions-file <path>","UTF-8 Markdown instructions").option("--schedule-file <path>","Typed schedule JSON document").option("--sources-file <path>","Typed source array JSON document").option("--output-file <path>","Typed primary output JSON document").option("--outputs-file <path>","Typed output array JSON document").option("--delivery-file <path>","Typed delivery JSON document").option("--review-policy <policy>","manual_review, auto_send, or draft_only").option("--runtime-file <path>","Typed runtime JSON document").option("--sandbox-blueprint-id <id|none>","Subscription sandbox blueprint, or none").option("--per-run-credit-cap <credits|none>","Positive credit ceiling, or none").option("--files-file <path>","Typed attached-file array JSON document").option("--idempotency-key <key>","Stable retry key; generated when omitted").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await p("updateAgentConfiguration",{additionalFiles:t.filesFile?Dt(t.filesFile,"--files-file"):void 0,agentId:e,delivery:t.deliveryFile?Dt(t.deliveryFile,"--delivery-file"):void 0,description:t.description,expectedVersion:xn(t.expectedVersion,"--expected-version"),goal:t.goal,instructionsMarkdown:t.instructionsFile?nv(t.instructionsFile,"--instructions-file"):void 0,name:t.name,output:t.outputFile?Dt(t.outputFile,"--output-file"):void 0,outputs:t.outputsFile?Dt(t.outputsFile,"--outputs-file"):void 0,perRunCreditCap:t.perRunCreditCap===void 0?void 0:ev(t.perRunCreditCap,"--per-run-credit-cap"),reviewPolicy:t.reviewPolicy,runtime:t.runtimeFile?Dt(t.runtimeFile,"--runtime-file"):void 0,sandboxBlueprintId:t.sandboxBlueprintId===void 0?void 0:tv(t.sandboxBlueprintId),schedule:t.scheduleFile?Dt(t.scheduleFile,"--schedule-file"):void 0,sources:t.sourcesFile?Dt(t.sourcesFile,"--sources-file"):void 0,teamId:t.teamId},t.idempotencyKey??Zn("configure")))}catch(n){nt(n,"Could not update the Agent")}});function cm(e){return new Me(e).description(`${e==="pause"?"Pause":"Resume"} an Agent schedule`).argument("<agent-id>","Scheduled Agent UUID").option("--idempotency-key <key>","Stable retry key; generated when omitted").option("--team-id <id>","Workspace ID").action(async(t,n)=>{try{m(await p(e==="pause"?"pauseAgentSchedule":"resumeAgentSchedule",{agentId:t,teamId:n.teamId},n.idempotencyKey??Zn(e)))}catch(r){nt(r,`Could not ${e} the Agent schedule`)}})}function aa(e,t){a(u(e,t)),process.exit(s.GENERAL_ERROR)}function av(e){return`cli:agent-memory:${e}:${lm()}`}function sv(e,t){let n=e.indexOf("="),r=n===-1?e:e.slice(0,n),i=n===-1?"":e.slice(n+1);return[...t,{name:r.trim(),note:i.trim()}]}var dv=new Me("show").description("Show what a scheduled agent remembers").argument("<agent-id>","Scheduled Agent UUID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await p("getAgentMemory",{agentId:e,teamId:t.teamId}))}catch(n){aa(n,"Could not read the agent's memory")}}),cv=new Me("set").description("Add to or remove from what an agent remembers. Owner or workspace admin only.").argument("<agent-id>","Scheduled Agent UUID").option("--learned <text>","Durable fact to add (repeatable)",Rn,[]).option("--always <text>","Standing instruction to add (repeatable)",Rn,[]).option("--never <text>","Thing it must not do, to add (repeatable)",Rn,[]).option("--track <name=note>","Entity to track, as name=note (repeatable)",sv,[]).option("--notes <text>","Replace the freeform notes").option("--operation <operation>","Mutation operation: add or remove","add").option("--remove-field <field>","Field to remove from: learned, recurringInstructions, negativePreferences, entities, or notes").option("--remove-value <text>","Item to remove; not needed when removing notes").option("--remove <field>","Deprecated alias for --remove-field").option("--value <text>","Deprecated alias for --remove-value").option("--expected-version <n>","Refuse the write unless the stored memory is still at this version").option("--idempotency-key <key>","Stable retry key; generated when omitted").option("--team-id <id>","Workspace ID").action(async(e,t)=>{let n=t.removeField??t.remove,r=t.removeValue??t.value,i=t.operation==="remove"||!!n;try{m(await p("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:i?"remove":"add",recurringInstructions:t.always.length?t.always:void 0,removeField:n,removeValue:r,teamId:t.teamId},t.idempotencyKey??av(i?"remove":"add")))}catch(o){aa(o,"Could not update the agent's memory")}}),lv=new Me("forget").description("Erase every stored version of an agent's memory. This cannot be undone.").argument("<agent-id>","Scheduled Agent UUID").option("--team-id <id>","Workspace ID").requiredOption("--idempotency-key <key>","Stable key bound into the approval receipt and reused on retry").option("--approval-receipt <receipt>","Receipt from the browser confirmation URL").option("--approval-receipt-stdin","Read the browser-issued approval receipt from stdin").option("--yes","Confirm erasure intent; this never substitutes for an approval receipt").action(async(e,t)=>{if(!t.yes)return a("Pass --yes to request erasure. A browser-issued approval receipt is still required.");try{let n=_(t);m(await p("forgetAgentMemory",{approvalReceipt:n,agentId:e,teamId:t.teamId},t.idempotencyKey))}catch(n){aa(n,"Could not erase the agent's memory")}}),mv=new Me("memory").description("Read, edit, and erase what a scheduled agent remembers").addCommand(dv).addCommand(cv).addCommand(lv),um=new Me("agent").description("Recommend, activate, configure, and manage scheduled Agents").addCommand(rv).addCommand(iv).addCommand(sm).addCommand(dm).addCommand(ov).addCommand(cm("pause")).addCommand(cm("resume")).addCommand(Qw).addCommand(Zw).addCommand(mv);import{randomUUID as pv}from"crypto";import{password as uv}from"@inquirer/prompts";import{Command as ai}from"commander";function sa(e){if(e==="claude-code"||e==="codex")return e;throw new Error("--runtime must be claude-code or codex")}function gv(e,t){let n=e;if(t==="claude-code"&&(n==="zai-claude"||n==="anthropic-compatible")||t==="codex"&&n==="openai-responses-compatible")return n;throw new Error(t==="claude-code"?"--provider must be zai-claude or anthropic-compatible for Claude":"--provider must be openai-responses-compatible for Codex")}async function fv(){let e="";for await(let t of process.stdin)if(e+=String(t),e.length>65536)throw new Error("Credential input is too large");return e.trim()}var hv=new ai("add").description("Enroll a provider credential without exposing it in arguments").requiredOption("--runtime <runtime>","claude-code or codex").requiredOption("--provider <provider>","zai-claude, anthropic-compatible, or openai-responses-compatible").requiredOption("--label <name>","Profile name shown in Mindframes").requiredOption("--model <model-id>","Provider model id").option("--base-url <url>","Public HTTPS provider base URL").option("--api-key-stdin","Read the provider key from stdin instead of a hidden prompt").option("--use","Select the new profile immediately").action(async e=>{try{let t=sa(e.runtime),n=gv(e.provider,t);if(!e.apiKeyStdin&&!process.stdin.isTTY)throw new Error("Non-interactive enrollment requires --api-key-stdin. Never pass provider keys as command arguments.");let r=e.apiKeyStdin?await fv():(await uv({mask:"*",message:"Provider API key:"})).trim();if(!r)throw new Error("Provider API key is required");let i=await Zd({apiKey:r,...e.baseUrl?{baseUrl:e.baseUrl}:{},label:e.label,makeDefault:e.use??!1,modelId:e.model,provider:n,runtime:t});C(`Saved connection profile ${i.label} (${i.id})`)}catch(t){a(u(t,"Profile enrollment failed")),process.exit(s.GENERAL_ERROR)}}),yv=new ai("list").description("List secret-free Claude Code or Codex connection profiles").requiredOption("--runtime <runtime>","claude-code or codex").action(async e=>{try{let t=sa(e.runtime);m(await p("listAiConnectionProfiles",{runtime:t}))}catch(t){a(u(t,"Profile list failed")),process.exit(s.GENERAL_ERROR)}}),bv=new ai("select").description("Select a profile UUID, or 'native' for the first-party route").requiredOption("--runtime <runtime>","claude-code or codex").requiredOption("--profile-id <id>","Profile UUID or native").option("--idempotency-key <key>","Reuse only for an exact retry of this profile selection").option("--yes","Confirm changing the active inference route").action(async e=>{e.yes||(a("Pass --yes to confirm changing the active connection profile."),process.exit(s.INVALID_INPUT));try{let t=sa(e.runtime),n=await p("selectAiConnectionProfile",{profileId:e.profileId,runtime:t},e.idempotencyKey?.trim()||pv());C(n.selectedProfileId?`Selected connection profile ${n.selectedProfileId}`:"Selected the native provider route")}catch(t){a(u(t,"Profile selection failed")),process.exit(s.GENERAL_ERROR)}}),gm=new ai("ai-connections").description("Manage Claude Code and Codex inference routes").addCommand(hv).addCommand(yv).addCommand(bv);import{Command as ca}from"commander";import{Command as fm}from"commander";var wv=new fm("set").description("Set the poster an artifact shows on cards").argument("<artifact-kind>","Artifact kind: presentation, video, microsite, survey, \u2026").argument("<target-id>","Artifact id \u2014 a presentation's documentId, other kinds' row id").option("--slide <number>","Presentations: rendered slide number").option("--at-seconds <seconds>","Videos: moment to cut the poster from").option("--image-url <url>","Existing https image to use as the poster").option("--upload-key <key>","Key of an image you uploaded").option("--team-id <id>","Workspace to act in").action(async(e,t,n)=>{[n.slide,n.atSeconds,n.imageUrl,n.uploadKey].filter(o=>o!==void 0).length>1&&(a("Name at most one poster source: --slide, --at-seconds, --image-url or --upload-key. Name none to restore the automatic preview."),process.exit(s.INVALID_INPUT));let i={artifactKind:e,targetId:t};if(n.slide!==void 0){let o=Number(n.slide);(!Number.isInteger(o)||o<1)&&(a("--slide must be a whole slide number, 1 or more."),process.exit(s.INVALID_INPUT)),i.slideNumber=o}if(n.atSeconds!==void 0){let o=Number(n.atSeconds);(!Number.isFinite(o)||o<0)&&(a("--at-seconds must be a number of seconds, zero or more."),process.exit(s.INVALID_INPUT)),i.atSeconds=o}n.imageUrl!==void 0&&(i.imageUrl=n.imageUrl),n.uploadKey!==void 0&&(i.uploadKey=n.uploadKey),n.teamId!==void 0&&(i.teamId=n.teamId);try{let o=await U(n.teamId),c=await p("setArtifactPoster",i,Q({command:"artifact poster set",payload:i,workspaceId:o}));m(c),C(c.posterUrl===null?"Poster reset to the automatic preview.":`Poster set from ${c.source}.`)}catch(o){a(u(o,"Setting the poster failed")),process.exit(s.GENERAL_ERROR)}}),hm=new fm("poster").description("Set the poster an artifact shows on cards").addCommand(wv);var da=["article","document","footageProject","microsite","presentation","presentationVideo","video"];function ym(e,t){a(u(e,t)),process.exit(s.GENERAL_ERROR)}function vv(e){if(e===void 0)return;let t=/^\s*(\d+)\s*(?:-\s*(\d+)\s*)?$/.exec(e);t||(a(`--slides expects N or N-M, got "${e}"`),process.exit(s.GENERAL_ERROR));let n=Number(t[1]),r=t[2]===void 0?n:Number(t[2]);return(n<1||r<n)&&(a(`--slides range must start at 1 and end no earlier than it starts, got "${e}"`),process.exit(s.GENERAL_ERROR)),{from:n,to:r}}var Iv=new ca("read").description("Read an owned artifact's full content").argument("<kind>",`Artifact kind: ${da.join(", ")}`).argument("<artifact-id>","Artifact id, or slug where the kind has one").option("--slides <range>","Presentations only: N or N-M. Omit to read every slide.").option("--team-id <id>","Workspace to read from").option("--version-id <id>","Footage projects only: saved version UUID").action(async(e,t,n)=>{da.includes(e)||(a(`Unknown artifact kind "${e}". Expected one of: ${da.join(", ")}`),process.exit(s.GENERAL_ERROR));try{let r=await p("readArtifact",{artifactId:t,kind:e,slides:vv(n.slides),versionId:n.versionId,teamId:n.teamId});m(r)}catch(r){ym(r,"Could not read the artifact")}}),kv=new ca("upload-url").description("Mint a presigned upload target for a file").requiredOption("--file-name <name>","Name of the file to upload").requiredOption("--file-type <type>","MIME type of the file").requiredOption("--file-size <bytes>","Exact size in bytes",e=>{let t=Number(e);return(!Number.isInteger(t)||t<0)&&(a("--file-size expects the exact whole-number byte size."),process.exit(s.GENERAL_ERROR)),t}).requiredOption("--idempotency-key <key>","Stable invocation key; a retry under it re-mints a POST for the same object").option("--team-id <id>","Workspace to mint the upload in").action(async e=>{try{m(await p("createUploadUrl",{fileName:e.fileName,fileSize:e.fileSize,fileType:e.fileType,teamId:e.teamId},e.idempotencyKey))}catch(t){ym(t,"Could not mint the upload URL")}}),bm=new ca("artifact").description("Read artifacts this workspace owns").addCommand(Iv).addCommand(kv).addCommand(hm);import{Command as vm}from"commander";var wm=1e3;function xv(e,t){let n=Number(e);return(!Number.isInteger(n)||n<1)&&(a(`${t} must be a positive whole number`),process.exit(s.GENERAL_ERROR)),n}function Rv(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}var Cv=new vm("export").description("Export who did what in the workspace (admins of governed workspaces). Newest first.").option("--from <iso>","Window start, ISO 8601 (default: 30 days before --to)").option("--to <iso>","Window end, ISO 8601 (default: now)").option("--categories <list>","Comma-separated: access,approvals,brand,features,governed_content,settings,sharing (default: all)").option("--format <format>","json (default) or csv").option("--limit <count>","Events per page, 1-1000 (default 200)").option("--cursor <cursor>","Continue from a previous page's nextCursor").option("--all","Follow nextCursor until the window is exhausted").option("--team-id <id>","Workspace ID").action(async e=>{try{let t=e.format??"json",n={categories:e.categories===void 0?void 0:Rv(e.categories),format:t,from:e.from,limit:e.limit===void 0?void 0:xv(e.limit,"--limit"),teamId:e.teamId,to:e.to},r=e.cursor,i=[];for(let l=0;l<wm;l+=1){let d=await p("exportWorkspaceAuditLog",{...n,cursor:r});if(i.push(d),!e.all||!d.nextCursor)break;n.from=d.window.from,n.to=d.window.to,r=d.nextCursor}let o=i[i.length-1],c=!!(e.all&&o?.nextCursor);if(t==="csv"){let[l,...d]=i.map(y=>y.csv??""),g=d.map(y=>y.slice(y.indexOf(`\r
|
|
64
|
+
Stopping runner\u2026`)),t.abort()};process.on("SIGINT",n),process.on("SIGTERM",n);try{await em({claudeBin:e.claudeBin,codexBin:e.codexBin,log:r=>console.log(qe.gray(`[runner] ${r}`)),once:e.once,signal:t.signal,version:"0.3.29",workspaceRoot:e.workspace??Nw()})}catch{console.error(qe.red("The local runner failed. Check the runner logs and try again.")),process.exit(1)}});import se from"chalk";import{Command as P$}from"commander";import{Command as ra}from"commander";import{readFileSync as Lw}from"fs";function _(e,t=()=>Lw(0,"utf8")){if(e.approvalReceipt&&e.approvalReceiptStdin)throw new P("Pass only one approval receipt input mode.",400);let n=e.approvalReceiptStdin?t().trim():e.approvalReceipt;if(e.approvalReceiptStdin&&!n)throw new P("No approval receipt was provided on stdin.",400);return n}function $t(e,t){return[...t,e]}function Uw(e){let[t,n]=e.split("@");return n?{templateId:t,version:Number.parseInt(n,10)}:{templateId:t}}function _w(e){if(typeof e.static=="string")return JSON.parse(e.static);let t=e.template;if(t.length)return{allowPreLaunch:e.allowPreLaunch?!0:void 0,audience:e.audience,imagery:e.imagery,market:e.market,productId:e.productId,sizes:e.size,templates:t.map(Uw),variations:e.variations??1}}var jw=new ra("create").description("Start durable ad-set generation").argument("<title>","Ad-set title").requiredOption("--brief <brief>","Campaign brief").option("--hook <text>","Opening hook (repeat)",$t,[]).option("--angle <text>","Creative angle (repeat)",$t,[]).option("--cta <text>","Call to action (repeat)",$t,[]).option("--voice <text>","Voice or persona (repeat)",$t,[]).option("--aspect <ratio>","9:16, 1:1, or 16:9 (repeat)",$t,[]).option("--duration <seconds>","Creative duration in seconds",e=>Number.parseInt(e,10)).option("--max-variations <count>","Maximum generated variations",e=>Number.parseInt(e,10)).option("--review-policy <policy>","review or auto_save").option("--style <style>","ugc, clean, cinematic, or testimonial","ugc").option("--format <format>","video (default) or static").option("--template <id[@version]>","Static: approved ad template (repeat)",$t,[]).option("--size <id>","Static: size id, e.g. 300x250 (repeat)",$t,[]).option("--variations <count>","Static: distinct variations per template",e=>Number.parseInt(e,10)).option("--audience <audience>","Static: claim scope audience").option("--market <market>","Static: claim scope market").option("--product-id <id>","Static: claim scope product").option("--allow-pre-launch","Static: allow pre-launch claims (flagged)").option("--imagery <mode>","Static: approved-only (default) or generate-backgrounds").option("--static <json>","Static: the whole static block as JSON").option("--branding-id <id>","Branding ID").option("--team-id <id>","Workspace ID").requiredOption("--idempotency-key <key>","Stable invocation key bound into the approval receipt").option("--approval-receipt <receipt>","Receipt returned by the browser confirmation URL; omit on the first call to get that URL").option("--approval-receipt-stdin","Read the approval receipt from stdin instead of argv").option("--yes","Approve generation").action(async(e,t)=>{if(!t.yes)return a("Pass --yes to approve generation");try{let n=_w(t),r=t.format??(n?"static":void 0);m(await p("createAdSet",{format:r,static:n,angles:t.angle.length?t.angle:void 0,approvalReceipt:_(t),aspects:t.aspect.length?t.aspect:void 0,brandingId:t.brandingId,brief:t.brief,ctas:t.cta.length?t.cta:void 0,durationSec:t.duration,hooks:r==="static"?void 0:t.hook.length?t.hook:[t.brief],maxVariations:t.maxVariations,reviewPolicy:t.reviewPolicy,style:r==="static"?void 0:t.style,teamId:t.teamId,title:e,voices:t.voice.length?t.voice:void 0},t.idempotencyKey))}catch(n){a(u(n,"Generation failed")),process.exit(s.GENERAL_ERROR)}}),qw=new ra("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 R("createAdSet",e,t.teamId))}catch(n){a(u(n,"Status failed")),process.exit(s.GENERAL_ERROR)}}),tm=new ra("ad-set").description("Generate a set of ad creatives (hooks, copy, visuals) from a campaign brief").addCommand(jw).addCommand(qw);import{randomUUID as nm}from"crypto";import{readFileSync as Mw}from"fs";import{Command as Qn}from"commander";var Vw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ri(e,t){Vw.test(e)||(a(`"${e}" is not a ${t} id.`),process.exit(s.INVALID_INPUT))}function rm(e,t){try{return Mw(e,"utf8")}catch{a(`${t}: cannot read file "${e}".`),process.exit(s.INVALID_INPUT)}}function ia(e,t){let n=rm(e,t);try{return JSON.parse(n)}catch{a(`${t}: "${e}" is not valid JSON.`),process.exit(s.INVALID_INPUT)}}function oa(e,t){let n=Number(e);return(!Number.isInteger(n)||n<1)&&(a(`${t} must be a positive integer.`),process.exit(s.INVALID_INPUT)),n}function im(e){return{html:rm(e.html,"--html"),legalPlacement:ia(e.legalPlacement,"--legal-placement"),sizes:ia(e.sizes,"--sizes"),slotSchema:ia(e.slotSchema,"--slot-schema"),...e.teamId?{teamId:e.teamId}:{}}}function om(e){return e.requiredOption("--html <file>","Template HTML file").requiredOption("--slot-schema <file>","JSON file: slot name \u2192 { type, required, label?, maxLength?, maxItems? }").requiredOption("--sizes <file>",'JSON file: [{ "id": "1x1", "label": "Feed square", "width": 1080, "height": 1080 }]').requiredOption("--legal-placement <file>",'JSON file: size id \u2192 { "isi": { "variant": "abbreviated", "minFontPx": 12 } }').option("--idempotency-key <key>","Reuse a request key to retry this same save").option("--team-id <id>","Workspace ID")}async function ii(e,t,n,r){try{m(await p(e,t,r))}catch(i){a(u(i,n)),process.exit(s.GENERAL_ERROR)}}var Fw=new Qn("list").description("List a brand's governed ad templates").option("--brand-id <id>","Brand profile ID (default: the default brand)").option("--format-family <family>","static, carousel or video").option("--limit <n>","Maximum templates to return (1-100)").option("--team-id <id>","Workspace ID").action(async e=>{await w(),e.brandId&&ri(e.brandId,"brand"),await ii("listAdTemplates",{...e.brandId?{brandId:e.brandId}:{},...e.formatFamily?{formatFamily:e.formatFamily}:{},...e.limit?{limit:oa(e.limit,"--limit")}:{},...e.teamId?{teamId:e.teamId}:{}},"List failed")}),Bw=new Qn("get").description("Read one ad template version with its HTML and lint report").argument("<template-id>","Ad template ID").option("--template-version <n>","Version to read (default: latest)").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await w(),ri(e,"template"),await ii("getAdTemplate",{templateId:e,...t.templateVersion?{version:oa(t.templateVersion,"--template-version")}:{},...t.teamId?{teamId:t.teamId}:{}},"Read failed")}),Gw=om(new Qn("create").description("Create an ad template as a draft (version 1)").requiredOption("--brand-id <id>","Brand profile ID").requiredOption("--name <name>","Template name").option("--format-family <family>","static (default), carousel or video")).action(async e=>{await w(),ri(e.brandId,"brand"),await ii("createAdTemplate",{brandId:e.brandId,name:e.name,...e.formatFamily?{formatFamily:e.formatFamily}:{},...im(e)},"Create failed",e.idempotencyKey??nm())}),Kw=om(new Qn("update").description("Save an edited template as a new draft version (earlier versions stay unchanged)").argument("<template-id>","Ad template ID").requiredOption("--expected-latest-version <n>","The latest version you edited; a stale value is refused").option("--name <name>","Rename the template")).action(async(e,t)=>{await w(),ri(e,"template"),await ii("updateAdTemplate",{templateId:e,expectedLatestVersion:oa(t.expectedLatestVersion,"--expected-latest-version"),...t.name?{name:t.name}:{},...im(t)},"Save failed",t.idempotencyKey??nm())}),am=new Qn("ad-template").description("Governed ad templates: list, read, and save drafts (a person approves them in the app)").addCommand(Fw).addCommand(Bw).addCommand(Gw).addCommand(Kw);import{randomUUID as lm}from"crypto";import{readFileSync as mm}from"fs";import{readFile as Xw}from"fs/promises";import{Command as Me}from"commander";import{randomUUID as Ww}from"crypto";function nt(e,t){a(u(e,t)),process.exit(e instanceof P?e.exitCode:s.GENERAL_ERROR)}function Zn(e){return`cli:agent-management:${e}:${Ww()}`}function xn(e,t){let n=Number(e);if(!Number.isInteger(n)||n<=0)throw new Error(`${t} must be a positive integer`);return n}import{Command as er}from"commander";var Jw=new er("list").description("List one roster page: your Agents plus teammates' team-visible Agents").option("--cursor <cursor>","Continue from a previous nextCursor").option("--page-size <n>","Roster rows to return (1-100)","50").option("--team-id <id>","Workspace ID").action(async e=>{try{m(await p("listAgentRoster",{cursor:e.cursor,pageSize:xn(e.pageSize,"--page-size"),teamId:e.teamId}))}catch(t){nt(t,"Could not list the Agent roster")}}),zw=new er("get").description("Read one roster-visible Agent card without private configuration").argument("<agent-id>","Roster-visible Agent UUID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await p("getRosterAgent",{agentId:e,teamId:t.teamId}))}catch(n){nt(n,"Could not read the roster Agent")}}),sm=new er("roster").description("Discover Agents shared inside the current workspace; never cross-workspace").addCommand(Jw).addCommand(zw),Hw=new er("set").description("Share an owned Agent with the workspace or make it private").argument("<agent-id>","Owned scheduled Agent UUID").argument("<visibility>","Desired visibility: private or team",b("visibility",["private","team"])).requiredOption("--expected-visibility <visibility>","Current value from agent roster get: private, team, or legacy public",b("--expected-visibility",["private","team","public"])).option("--idempotency-key <key>","Reuse only for an exact retry of this visibility change").option("--team-id <id>","Workspace ID").action(async(e,t,n)=>{try{m(await p("setAgentVisibility",{agentId:e,expectedVisibility:n.expectedVisibility,teamId:n.teamId,visibility:t},n.idempotencyKey?.trim()||Zn("visibility")))}catch(r){nt(r,"Could not change Agent visibility")}}),dm=new er("visibility").description("Control whether an owned Agent is private or team-visible").addCommand(Hw);function Rn(e,t){return[...t,e]}function Yw(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw new Error("Expected a positive integer.");return t}async function oi(e,t){let n=t.trim(),r=n.startsWith("{")?n:await Xw(n,"utf8"),i=JSON.parse(r);if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`${e} must contain one JSON object.`);return i}var Qw=new Me("create").description("Activate a reviewed Agent draft; get browser approval, then retry with the same key and receipt.").argument("<draft-id>","Reviewed agent draft UUID").requiredOption("--expected-version <number>","Exact draft version shown during review",Yw).requiredOption("--idempotency-key <key>","Stable key bound into the approval receipt and reused on retry").option("--approval-receipt <receipt>","Receipt from the browser confirmation URL").option("--yes","Confirm activation intent; this never substitutes for the approval receipt").option("--team-id <id>","Workspace ID").action(async(e,t)=>{t.yes||(a("Pass --yes to request activation. A server-issued approval receipt is still required."),process.exit(s.INVALID_INPUT)),await pm("Agent activation failed",()=>p("createAgent",{approvalReceipt:t.approvalReceipt,draftId:e,expectedVersion:t.expectedVersion,teamId:t.teamId},t.idempotencyKey))}),Zw=new Me("recommend").description("Save a private inactive scheduled-agent draft for review; this command never activates or runs it.").argument("<name>","Agent name").requiredOption("--instructions <markdown>","Standing agent instructions").option("--description <text>","Agent description","").option("--goal <text>","User-visible recurring objective").option("--rationale <text>","Why this draft is being recommended").option("--schedule <frequency>","manual, daily, weekdays, weekly, or monthly").option("--schedule-r-rule <rrule>","Precise recurrence rule").option("--schedule-time <hh:mm>","Local run time").option("--timezone <zone>","IANA timezone").option("--schedule-config <json-or-path>","Full schedule configuration as inline JSON or a JSON file").option("--source <connector>","Source connector (repeatable)",Rn,[]).option("--x-handle-target <handle>","Target for the x_handle source").option("--x-search-target <query>","Query for the x_search source").option("--primary-output <adapter>","Legacy primary output fallback").option("--output <adapter>","Output adapter (repeatable)",Rn,[]).option("--output-config <json-or-path>","Full output slot configuration (repeatable)",Rn,[]).option("--delivery-adapter <adapter>","Delivery adapter").option("--delivery-config <json-or-path>","Full delivery configuration as inline JSON or a JSON file").option("--review-policy <policy>","manual_review, auto_send, or draft_only","manual_review").option("--runtime <json-or-path>","Scheduled runtime configuration as inline JSON or a JSON file").option("--sandbox-blueprint-id <id>","Sandbox blueprint UUID").option("--idempotency-key <key>","Stable retry key").option("--team-id <id>","Workspace ID").action(async(e,t)=>{await pm("Agent recommendation failed",async()=>p("recommendAgent",{deliveryAdapter:t.deliveryAdapter,deliveryConfig:t.deliveryConfig?await oi("--delivery-config",t.deliveryConfig):void 0,description:t.description,goal:t.goal,instructionsMarkdown:t.instructions,name:e,outputAdapter:t.primaryOutput,outputAdapters:t.output.length?t.output:void 0,outputConfigs:t.outputConfig.length?await Promise.all(t.outputConfig.map(n=>oi("--output-config",n))):void 0,rationale:t.rationale,reviewPolicy:t.reviewPolicy,runtime:t.runtime?await oi("--runtime",t.runtime):void 0,sandboxBlueprintId:t.sandboxBlueprintId,schedule:t.schedule,scheduleConfig:t.scheduleConfig?await oi("--schedule-config",t.scheduleConfig):void 0,scheduleRRule:t.scheduleRRule,scheduleTime:t.scheduleTime,sourceConnectors:t.source.length?t.source:void 0,teamId:t.teamId,timezone:t.timezone,xHandleTarget:t.xHandleTarget,xSearchTarget:t.xSearchTarget},t.idempotencyKey??lm()))});async function pm(e,t){try{m(await t())}catch(n){if(n instanceof P){let r=`[${n.errorCode}] `;console.error(JSON.stringify({error:{code:n.errorCode,message:n.message.startsWith(r)?n.message.slice(r.length):n.message,retryable:n.retryable},ok:!1})),process.exit(n.exitCode)}console.error(JSON.stringify({error:{code:"operation_failed",message:u(n,e),retryable:!1},ok:!1})),process.exit(s.GENERAL_ERROR)}}function ev(e,t){return e==="none"?null:xn(e,t)}function tv(e){return e==="none"?null:e}function Dt(e,t){let n;try{n=mm(e,"utf8")}catch(r){throw new Error(`${t} could not read ${e}: ${u(r,"unknown file error")}`)}try{return JSON.parse(n)}catch(r){throw new Error(`${t} must point to valid JSON: ${u(r,"invalid JSON")}`)}}function nv(e,t){try{return mm(e,"utf8")}catch(n){throw new Error(`${t} could not read ${e}: ${u(n,"unknown file error")}`)}}var rv=new Me("list").description("List all owned Agents, following cursor pages to closure").option("--cursor <cursor>","Resume from a previous nextCursor").option("--page-size <n>","Rows fetched per page","50").option("--team-id <id>","Workspace ID").action(async e=>{try{let t=[],n=e.cursor;for(;;){let r=await p("listAgents",{cursor:n,pageSize:xn(e.pageSize,"--page-size"),teamId:e.teamId});if(t.push(...r.agents),!r.hasMore||!r.nextCursor)break;n=r.nextCursor}m({agents:t,total:t.length})}catch(t){nt(t,"Could not list Agents")}}),iv=new Me("get").description("Read one owned Agent and its complete configuration").argument("<agent-id>","Scheduled Agent UUID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await p("getAgent",{agentId:e,teamId:t.teamId}))}catch(n){nt(n,"Could not read the Agent")}}),ov=new Me("configure").description("Update Agent configuration; enable automatic external delivery in the browser").argument("<agent-id>","Scheduled Agent UUID").requiredOption("--expected-version <n>","Version returned by agent get").option("--name <text>","Agent name").option("--description <text>","Agent description").option("--goal <text>","Recurring objective").option("--instructions-file <path>","UTF-8 Markdown instructions").option("--schedule-file <path>","Typed schedule JSON document").option("--sources-file <path>","Typed source array JSON document").option("--output-file <path>","Typed primary output JSON document").option("--outputs-file <path>","Typed output array JSON document").option("--delivery-file <path>","Typed delivery JSON document").option("--review-policy <policy>","manual_review, auto_send, or draft_only").option("--runtime-file <path>","Typed runtime JSON document").option("--sandbox-blueprint-id <id|none>","Subscription sandbox blueprint, or none").option("--per-run-credit-cap <credits|none>","Positive credit ceiling, or none").option("--files-file <path>","Typed attached-file array JSON document").option("--idempotency-key <key>","Stable retry key; generated when omitted").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await p("updateAgentConfiguration",{additionalFiles:t.filesFile?Dt(t.filesFile,"--files-file"):void 0,agentId:e,delivery:t.deliveryFile?Dt(t.deliveryFile,"--delivery-file"):void 0,description:t.description,expectedVersion:xn(t.expectedVersion,"--expected-version"),goal:t.goal,instructionsMarkdown:t.instructionsFile?nv(t.instructionsFile,"--instructions-file"):void 0,name:t.name,output:t.outputFile?Dt(t.outputFile,"--output-file"):void 0,outputs:t.outputsFile?Dt(t.outputsFile,"--outputs-file"):void 0,perRunCreditCap:t.perRunCreditCap===void 0?void 0:ev(t.perRunCreditCap,"--per-run-credit-cap"),reviewPolicy:t.reviewPolicy,runtime:t.runtimeFile?Dt(t.runtimeFile,"--runtime-file"):void 0,sandboxBlueprintId:t.sandboxBlueprintId===void 0?void 0:tv(t.sandboxBlueprintId),schedule:t.scheduleFile?Dt(t.scheduleFile,"--schedule-file"):void 0,sources:t.sourcesFile?Dt(t.sourcesFile,"--sources-file"):void 0,teamId:t.teamId},t.idempotencyKey??Zn("configure")))}catch(n){nt(n,"Could not update the Agent")}});function cm(e){return new Me(e).description(`${e==="pause"?"Pause":"Resume"} an Agent schedule`).argument("<agent-id>","Scheduled Agent UUID").option("--idempotency-key <key>","Stable retry key; generated when omitted").option("--team-id <id>","Workspace ID").action(async(t,n)=>{try{m(await p(e==="pause"?"pauseAgentSchedule":"resumeAgentSchedule",{agentId:t,teamId:n.teamId},n.idempotencyKey??Zn(e)))}catch(r){nt(r,`Could not ${e} the Agent schedule`)}})}function aa(e,t){a(u(e,t)),process.exit(s.GENERAL_ERROR)}function av(e){return`cli:agent-memory:${e}:${lm()}`}function sv(e,t){let n=e.indexOf("="),r=n===-1?e:e.slice(0,n),i=n===-1?"":e.slice(n+1);return[...t,{name:r.trim(),note:i.trim()}]}var dv=new Me("show").description("Show what a scheduled agent remembers").argument("<agent-id>","Scheduled Agent UUID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await p("getAgentMemory",{agentId:e,teamId:t.teamId}))}catch(n){aa(n,"Could not read the agent's memory")}}),cv=new Me("set").description("Add to or remove from what an agent remembers. Owner or workspace admin only.").argument("<agent-id>","Scheduled Agent UUID").option("--learned <text>","Durable fact to add (repeatable)",Rn,[]).option("--always <text>","Standing instruction to add (repeatable)",Rn,[]).option("--never <text>","Thing it must not do, to add (repeatable)",Rn,[]).option("--track <name=note>","Entity to track, as name=note (repeatable)",sv,[]).option("--notes <text>","Replace the freeform notes").option("--operation <operation>","Mutation operation: add or remove","add").option("--remove-field <field>","Field to remove from: learned, recurringInstructions, negativePreferences, entities, or notes").option("--remove-value <text>","Item to remove; not needed when removing notes").option("--remove <field>","Deprecated alias for --remove-field").option("--value <text>","Deprecated alias for --remove-value").option("--expected-version <n>","Refuse the write unless the stored memory is still at this version").option("--idempotency-key <key>","Stable retry key; generated when omitted").option("--team-id <id>","Workspace ID").action(async(e,t)=>{let n=t.removeField??t.remove,r=t.removeValue??t.value,i=t.operation==="remove"||!!n;try{m(await p("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:i?"remove":"add",recurringInstructions:t.always.length?t.always:void 0,removeField:n,removeValue:r,teamId:t.teamId},t.idempotencyKey??av(i?"remove":"add")))}catch(o){aa(o,"Could not update the agent's memory")}}),lv=new Me("forget").description("Erase every stored version of an agent's memory. This cannot be undone.").argument("<agent-id>","Scheduled Agent UUID").option("--team-id <id>","Workspace ID").requiredOption("--idempotency-key <key>","Stable key bound into the approval receipt and reused on retry").option("--approval-receipt <receipt>","Receipt from the browser confirmation URL").option("--approval-receipt-stdin","Read the browser-issued approval receipt from stdin").option("--yes","Confirm erasure intent; this never substitutes for an approval receipt").action(async(e,t)=>{if(!t.yes)return a("Pass --yes to request erasure. A browser-issued approval receipt is still required.");try{let n=_(t);m(await p("forgetAgentMemory",{approvalReceipt:n,agentId:e,teamId:t.teamId},t.idempotencyKey))}catch(n){aa(n,"Could not erase the agent's memory")}}),mv=new Me("memory").description("Read, edit, and erase what a scheduled agent remembers").addCommand(dv).addCommand(cv).addCommand(lv),um=new Me("agent").description("Recommend, activate, configure, and manage scheduled Agents").addCommand(rv).addCommand(iv).addCommand(sm).addCommand(dm).addCommand(ov).addCommand(cm("pause")).addCommand(cm("resume")).addCommand(Qw).addCommand(Zw).addCommand(mv);import{randomUUID as pv}from"crypto";import{password as uv}from"@inquirer/prompts";import{Command as ai}from"commander";function sa(e){if(e==="claude-code"||e==="codex")return e;throw new Error("--runtime must be claude-code or codex")}function gv(e,t){let n=e;if(t==="claude-code"&&(n==="zai-claude"||n==="anthropic-compatible")||t==="codex"&&n==="openai-responses-compatible")return n;throw new Error(t==="claude-code"?"--provider must be zai-claude or anthropic-compatible for Claude":"--provider must be openai-responses-compatible for Codex")}async function fv(){let e="";for await(let t of process.stdin)if(e+=String(t),e.length>65536)throw new Error("Credential input is too large");return e.trim()}var hv=new ai("add").description("Enroll a provider credential without exposing it in arguments").requiredOption("--runtime <runtime>","claude-code or codex").requiredOption("--provider <provider>","zai-claude, anthropic-compatible, or openai-responses-compatible").requiredOption("--label <name>","Profile name shown in Mindframes").requiredOption("--model <model-id>","Provider model id").option("--base-url <url>","Public HTTPS provider base URL").option("--api-key-stdin","Read the provider key from stdin instead of a hidden prompt").option("--use","Select the new profile immediately").action(async e=>{try{let t=sa(e.runtime),n=gv(e.provider,t);if(!e.apiKeyStdin&&!process.stdin.isTTY)throw new Error("Non-interactive enrollment requires --api-key-stdin. Never pass provider keys as command arguments.");let r=e.apiKeyStdin?await fv():(await uv({mask:"*",message:"Provider API key:"})).trim();if(!r)throw new Error("Provider API key is required");let i=await Zd({apiKey:r,...e.baseUrl?{baseUrl:e.baseUrl}:{},label:e.label,makeDefault:e.use??!1,modelId:e.model,provider:n,runtime:t});C(`Saved connection profile ${i.label} (${i.id})`)}catch(t){a(u(t,"Profile enrollment failed")),process.exit(s.GENERAL_ERROR)}}),yv=new ai("list").description("List secret-free Claude Code or Codex connection profiles").requiredOption("--runtime <runtime>","claude-code or codex").action(async e=>{try{let t=sa(e.runtime);m(await p("listAiConnectionProfiles",{runtime:t}))}catch(t){a(u(t,"Profile list failed")),process.exit(s.GENERAL_ERROR)}}),bv=new ai("select").description("Select a profile UUID, or 'native' for the first-party route").requiredOption("--runtime <runtime>","claude-code or codex").requiredOption("--profile-id <id>","Profile UUID or native").option("--idempotency-key <key>","Reuse only for an exact retry of this profile selection").option("--yes","Confirm changing the active inference route").action(async e=>{e.yes||(a("Pass --yes to confirm changing the active connection profile."),process.exit(s.INVALID_INPUT));try{let t=sa(e.runtime),n=await p("selectAiConnectionProfile",{profileId:e.profileId,runtime:t},e.idempotencyKey?.trim()||pv());C(n.selectedProfileId?`Selected connection profile ${n.selectedProfileId}`:"Selected the native provider route")}catch(t){a(u(t,"Profile selection failed")),process.exit(s.GENERAL_ERROR)}}),gm=new ai("ai-connections").description("Manage Claude Code and Codex inference routes").addCommand(hv).addCommand(yv).addCommand(bv);import{Command as ca}from"commander";import{Command as fm}from"commander";var wv=new fm("set").description("Set the poster an artifact shows on cards").argument("<artifact-kind>","Artifact kind: presentation, video, microsite, survey, \u2026").argument("<target-id>","Artifact id \u2014 a presentation's documentId, other kinds' row id").option("--slide <number>","Presentations: rendered slide number").option("--at-seconds <seconds>","Videos: moment to cut the poster from").option("--image-url <url>","Existing https image to use as the poster").option("--upload-key <key>","Key of an image you uploaded").option("--team-id <id>","Workspace to act in").action(async(e,t,n)=>{[n.slide,n.atSeconds,n.imageUrl,n.uploadKey].filter(o=>o!==void 0).length>1&&(a("Name at most one poster source: --slide, --at-seconds, --image-url or --upload-key. Name none to restore the automatic preview."),process.exit(s.INVALID_INPUT));let i={artifactKind:e,targetId:t};if(n.slide!==void 0){let o=Number(n.slide);(!Number.isInteger(o)||o<1)&&(a("--slide must be a whole slide number, 1 or more."),process.exit(s.INVALID_INPUT)),i.slideNumber=o}if(n.atSeconds!==void 0){let o=Number(n.atSeconds);(!Number.isFinite(o)||o<0)&&(a("--at-seconds must be a number of seconds, zero or more."),process.exit(s.INVALID_INPUT)),i.atSeconds=o}n.imageUrl!==void 0&&(i.imageUrl=n.imageUrl),n.uploadKey!==void 0&&(i.uploadKey=n.uploadKey),n.teamId!==void 0&&(i.teamId=n.teamId);try{let o=await U(n.teamId),c=await p("setArtifactPoster",i,Q({command:"artifact poster set",payload:i,workspaceId:o}));m(c),C(c.posterUrl===null?"Poster reset to the automatic preview.":`Poster set from ${c.source}.`)}catch(o){a(u(o,"Setting the poster failed")),process.exit(s.GENERAL_ERROR)}}),hm=new fm("poster").description("Set the poster an artifact shows on cards").addCommand(wv);var da=["article","document","footageProject","microsite","presentation","presentationVideo","video"];function ym(e,t){a(u(e,t)),process.exit(s.GENERAL_ERROR)}function vv(e){if(e===void 0)return;let t=/^\s*(\d+)\s*(?:-\s*(\d+)\s*)?$/.exec(e);t||(a(`--slides expects N or N-M, got "${e}"`),process.exit(s.GENERAL_ERROR));let n=Number(t[1]),r=t[2]===void 0?n:Number(t[2]);return(n<1||r<n)&&(a(`--slides range must start at 1 and end no earlier than it starts, got "${e}"`),process.exit(s.GENERAL_ERROR)),{from:n,to:r}}var Iv=new ca("read").description("Read an owned artifact's full content").argument("<kind>",`Artifact kind: ${da.join(", ")}`).argument("<artifact-id>","Artifact id, or slug where the kind has one").option("--slides <range>","Presentations only: N or N-M. Omit to read every slide.").option("--team-id <id>","Workspace to read from").option("--version-id <id>","Footage projects only: saved version UUID").action(async(e,t,n)=>{da.includes(e)||(a(`Unknown artifact kind "${e}". Expected one of: ${da.join(", ")}`),process.exit(s.GENERAL_ERROR));try{let r=await p("readArtifact",{artifactId:t,kind:e,slides:vv(n.slides),versionId:n.versionId,teamId:n.teamId});m(r)}catch(r){ym(r,"Could not read the artifact")}}),kv=new ca("upload-url").description("Mint a presigned upload target for a file").requiredOption("--file-name <name>","Name of the file to upload").requiredOption("--file-type <type>","MIME type of the file").requiredOption("--file-size <bytes>","Exact size in bytes",e=>{let t=Number(e);return(!Number.isInteger(t)||t<0)&&(a("--file-size expects the exact whole-number byte size."),process.exit(s.GENERAL_ERROR)),t}).requiredOption("--idempotency-key <key>","Stable invocation key; a retry under it re-mints a POST for the same object").option("--team-id <id>","Workspace to mint the upload in").action(async e=>{try{m(await p("createUploadUrl",{fileName:e.fileName,fileSize:e.fileSize,fileType:e.fileType,teamId:e.teamId},e.idempotencyKey))}catch(t){ym(t,"Could not mint the upload URL")}}),bm=new ca("artifact").description("Read artifacts this workspace owns").addCommand(Iv).addCommand(kv).addCommand(hm);import{Command as vm}from"commander";var wm=1e3;function xv(e,t){let n=Number(e);return(!Number.isInteger(n)||n<1)&&(a(`${t} must be a positive whole number`),process.exit(s.GENERAL_ERROR)),n}function Rv(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}var Cv=new vm("export").description("Export who did what in the workspace (admins of governed workspaces). Newest first.").option("--from <iso>","Window start, ISO 8601 (default: 30 days before --to)").option("--to <iso>","Window end, ISO 8601 (default: now)").option("--categories <list>","Comma-separated: access,approvals,brand,features,governed_content,settings,sharing (default: all)").option("--format <format>","json (default) or csv").option("--limit <count>","Events per page, 1-1000 (default 200)").option("--cursor <cursor>","Continue from a previous page's nextCursor").option("--all","Follow nextCursor until the window is exhausted").option("--team-id <id>","Workspace ID").action(async e=>{try{let t=e.format??"json",n={categories:e.categories===void 0?void 0:Rv(e.categories),format:t,from:e.from,limit:e.limit===void 0?void 0:xv(e.limit,"--limit"),teamId:e.teamId,to:e.to},r=e.cursor,i=[];for(let l=0;l<wm;l+=1){let d=await p("exportWorkspaceAuditLog",{...n,cursor:r});if(i.push(d),!e.all||!d.nextCursor)break;n.from=d.window.from,n.to=d.window.to,r=d.nextCursor}let o=i[i.length-1],c=!!(e.all&&o?.nextCursor);if(t==="csv"){let[l,...d]=i.map(y=>y.csv??""),g=d.map(y=>y.slice(y.indexOf(`\r
|
|
65
65
|
`)+2));process.stdout.write([l,...g].join(""))}else i.length===1?m(i[0]):m({...o,events:i.flatMap(l=>l.events),nextCursor:o?.nextCursor??null,window:i[0]?.window});c&&(a(`Export incomplete: stopped after ${wm} pages. Continue with --cursor ${o?.nextCursor} --from ${n.from} --to ${n.to}`),process.exit(s.GENERAL_ERROR))}catch(t){a(u(t,"Exporting the workspace audit log failed")),process.exit(s.GENERAL_ERROR)}}),Im=new vm("audit-log").description("Workspace audit log").addCommand(Cv);import{randomUUID as di}from"crypto";import{readFileSync as Dv}from"fs";import{readFile as Nv}from"fs/promises";import Nt from"chalk";import{Command as Pe}from"commander";import Lv from"ora";import{mkdir as Sv,writeFile as km}from"fs/promises";import{dirname as Ev}from"path";async function Ie(e,t){if(await Sv(Ev(t),{recursive:!0}),e.startsWith("data:")){let i=e.match(/^data:[^;]+;base64,(.+)$/);if(!i)throw new Error("Invalid data URL format");let o=Buffer.from(i[1],"base64");if(o.length===0)throw new Error("Downloaded media was empty");await km(t,o);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 km(t,r)}import{existsSync as xm}from"fs";import{resolve as Pv}from"path";var Av=/^([A-Za-z][A-Za-z0-9_-]*)=(.+)$/;function Tv(e){let t=e.trim();if(!t)throw new P("A reference image value cannot be empty.",400);if(xm(t))return{source:t};let n=Av.exec(t);return n?{label:n[1],source:n[2]}:{source:t}}function Ov(e,t,n){if(!e.startsWith("image/")&&e!=="application/octet-stream")throw new P(`Reference image ${t} (${n}) is ${e}, not an image. A reference must be an image; pass an image file or a public image URL.`,400)}function $v(e,t){let n;try{n=new URL(e)}catch{throw new P(`Reference image ${t} (${e}) must be an existing local file or an HTTP(S) URL.`,400)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new P(`Reference image ${t} (${e}) must use an HTTP(S) URL.`,400);return n}async function si(e,t){if(e?.length){if(t.maxCount!==void 0&&e.length>t.maxCount)throw new P(`${t.maxCountSubject??"This command"} accepts at most ${t.maxCount} reference images; ${e.length} were provided.`,400);return Promise.all(e.map(async(n,r)=>{let i=r+1,{label:o,source:c}=Tv(n);if(xm(c)){let d=Pv(c),g=gn(d);t.rejectNonImageFiles&&Ov(g,i,c);let y=await ie(d,{idempotencyKey:`${t.idempotencyKey}:reference:${i}`}),v=y.type||g;return{...o?{label:o}:{},...v.startsWith("image/")?{mediaType:v}:{},url:y.url}}let l=$v(c,i);return{...o?{label:o}:{},url:l.toString()}}))}}var Uv=15e3,_v=40,jv=3;function qv(e,t){return[...t,e]}async function Mv(e){let t=e.trim(),n=t.startsWith("[")?t:await Nv(t,"utf8"),r=JSON.parse(n);if(!Array.isArray(r)||r.some(i=>!i||typeof i!="object"||Array.isArray(i)))throw new Error("--starter-looks-json must contain one JSON array of objects.");return r}async function Rm(e,t){return(await si(e,{idempotencyKey:t,maxCount:jv,maxCountSubject:"A presenter Look"}))?.map(r=>({url:r.url}))}function la(e,t){if(t==="json"){m(e);return}if(t==="quiet"){console.log(e.videoUrl??e.requestId);return}I(`Request ID: ${e.requestId}`),I(`Status: ${e.status}`),e.durationSec!=null&&I(`Duration: ${e.durationSec}s`),e.videoUrl&&C(`Video URL: ${e.videoUrl}`),e.error&&a(`Error: ${e.error}`)}var Vv=new Pe("options").description("List available presenter avatars and voices").option("--language <language>","Filter voices by language").option("--team-id <id>","Workspace ID; defaults to the selected workspace").option("-f, --format <format>","Output format: human, json, quiet",b("--format",["human","json","quiet"]),"human").action(async e=>{try{let t=await kc(e.language,e.teamId);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){I("Your presenters:");for(let r of n)console.log(` ${r.id} ${r.name}`)}I("Avatars:");for(let r of t.avatars){let i=r.renderTiers?.length?` [${r.renderTiers.join(", ")}]`:"";console.log(` ${r.id} ${r.name}${i}`)}I("Voices:");for(let r of t.voices)console.log(` ${r.id} ${r.name}${r.language?` (${r.language})`:""}`)}catch(t){a(u(t,"Unknown error")),process.exit(s.GENERAL_ERROR)}}),Fv=new Pe("options").description("List personal-presenter engines, prices, supported sources, and exact consent wording").option("--locale <locale>","Consent locale: en, es, hi, ru, or zh","en").option("--team-id <id>","Workspace ID").option("-f, --format <format>","Output format: human, json, quiet",b("--format",["human","json","quiet"]),"human").action(async e=>{try{let t=await p("listPresenterCreationOptions",{locale:e.locale,teamId:e.teamId});if(e.format==="json")return m(t);if(e.format==="quiet"){for(let n of t.options)console.log(n.id);return}I(t.canCreate?"Presenter creation is enabled.":"Presenter creation is not enabled for this account.");for(let n of t.options)console.log(`
|
|
66
66
|
${Nt.bold(n.label)} ${Nt.gray(n.id)}`),console.log(` ${n.description}`),console.log(` Sources: ${n.supportedKinds.join(", ")}`),console.log(` Credits: ${Object.entries(n.creationCredits).map(([r,i])=>`${r}=${i}`).join(", ")}`),console.log(` Consent: ${n.consentCopyText}`)}catch(t){a(u(t,"Options failed")),process.exit(s.GENERAL_ERROR)}}),Bv=new Pe("create").description("Create a personal presenter after browser-confirmed likeness consent").requiredOption("--name <name>","Presenter name").requiredOption("--engine <id>","Engine id from 'avatar presenter options'").requiredOption("--kind <kind>","Source kind: footage, photo, or prompt").requiredOption("--consent-statement <text>","Exact consent text from 'avatar presenter options'").option("--locale <locale>","Consent locale","en").option("--source <path>","Local footage or headshot file").option("--prompt <text>","Synthetic-persona description").option("--reference-image <path...>","Up to three local prompt reference images",qv,[]).option("--starter-looks-json <json-or-path>","Optional starter-look array as inline JSON or a JSON file").option("--team-id <id>","Workspace ID").option("--idempotency-key <key>","Stable key bound into the approval receipt and upload retries").option("--approval-receipt <receipt>","Receipt from the browser confirmation URL").option("--approval-receipt-stdin","Read the browser-issued receipt from stdin").option("--yes","Confirm creation intent; this never substitutes for likeness consent").option("--no-wait","Return after the presenter creation run is accepted").option("--wait-timeout-seconds <n>","Max seconds to wait for the presenter creation run (default 3600)",Number).action(async e=>{e.yes||(a("Pass --yes to confirm presenter creation intent. Browser-issued likeness approval is still required."),process.exit(s.INVALID_INPUT)),["footage","photo","prompt"].includes(e.kind)||(a("--kind must be footage, photo, or prompt."),process.exit(s.INVALID_INPUT)),e.approvalReceipt&&e.approvalReceiptStdin&&(a("Pass only one approval receipt input mode."),process.exit(s.INVALID_INPUT));let t=e.approvalReceiptStdin?Dv(0,"utf8").trim():e.approvalReceipt;e.approvalReceiptStdin&&!t&&(a("No approval receipt was provided on stdin."),process.exit(s.INVALID_INPUT));let n=e.idempotencyKey??di();try{if(e.kind==="prompt"&&!e.prompt?.trim())throw new Error("--prompt is required for prompt presenters.");if(e.kind!=="prompt"&&!e.source)throw new Error("--source is required for footage and photo presenters.");if(e.referenceImage.length>3)throw new Error("At most three --reference-image values are allowed.");let r=e.source?await ie(e.source,{idempotencyKey:`${n}:source`,storagePrefix:"presenters"}):void 0,i=await Promise.all(e.referenceImage.map((l,d)=>ie(l,{idempotencyKey:`${n}:reference:${d}`,storagePrefix:"presenters"}))),o=e.starterLooksJson?await Mv(e.starterLooksJson):[],c=await p("createPresenter",{approvalReceipt:t,consentCopyLocale:e.locale,consentCopyText:e.consentStatement,engineId:e.engine,kind:e.kind,name:e.name,...e.prompt?{prompt:e.prompt}:{},...i.length?{referenceImageS3Keys:i.map(l=>l.s3Key)}:{},...r?{s3Key:r.s3Key}:{},starterLooks:o,teamId:e.teamId},n);if(!e.wait){m(c),I(`Check progress with: ${f.commands[0]} avatar presenter status ${c.runId}`);return}m(await z("createPresenter",c.runId,e.teamId,null,{maxWaitMs:(e.waitTimeoutSeconds??3600)*1e3,statusCommand:"avatar presenter status"}))}catch(r){let i=u(r);a(i),i.includes("approval")&&I(`Retry with the receipt and the same key: --approval-receipt <receipt> --idempotency-key ${n}`),process.exit(s.GENERAL_ERROR)}}),Gv=new Pe("status").description("Read personal-presenter creation status").argument("<run-id>","Durable run ID").option("--team-id <id>","Workspace ID").action(async(e,t)=>{try{m(await R("createPresenter",e,t.teamId))}catch(n){a(u(n,"Status failed")),process.exit(s.GENERAL_ERROR)}}),Kv=new Pe("presenter").description("Discover and create reusable personal presenters").addCommand(Fv).addCommand(Bv).addCommand(Gv),Wv=new Pe("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("--branding-id <id>","Workspace brand applied to the presenter clip").option("--cast-preset-id <id>","Saved cast preset supplying presenter, backdrop, and voice").option("--captions","Burn provider-generated captions into the clip").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; defaults to the presenter's lowest supported tier").option("--title <title>","Clip title","Presenter clip").option("--strict-branding","Fail when the selected brand cannot be applied completely").option("--idempotency-key <key>","Stable retry key for this presenter clip").option("--no-wait","Do not wait for completion").option("-f, --format <format>","Output format: human, json, quiet",b("--format",["human","json","quiet"]),"human").action(async e=>{let t=e.transparent?"webm":e.outputFormat;!!e.audioUrl==!!e.script&&(a("Provide exactly one avatar speech input: --audio-url or --script"),process.exit(s.INVALID_INPUT)),["1:1","9:16","16:9"].includes(e.aspect)||(a("Aspect must be one of 1:1, 9:16, or 16:9"),process.exit(s.INVALID_INPUT)),e.outputFormat!==void 0&&!["mp4","webm"].includes(e.outputFormat)&&(a("Output format must be mp4 or webm"),process.exit(s.INVALID_INPUT)),e.backgroundColor!==void 0&&!/^#[0-9a-fA-F]{6}$/.test(e.backgroundColor)&&(a("Background color must be a six-digit hex value"),process.exit(s.INVALID_INPUT)),e.backgroundColor&&e.backgroundImageUrl&&(a("Provide only one presenter background"),process.exit(s.INVALID_INPUT)),e.fit!==void 0&&!["contain","cover"].includes(e.fit)&&(a("Fit must be contain or cover"),process.exit(s.INVALID_INPUT)),e.fit&&!e.backgroundImageUrl&&(a("Fit requires --background-image-url"),process.exit(s.INVALID_INPUT)),e.transparent&&e.outputFormat==="mp4"&&(a("--transparent cannot be combined with --output-format mp4"),process.exit(s.INVALID_INPUT)),t==="webm"&&(e.backgroundColor||e.backgroundImageUrl)&&(a("Transparent WebM output cannot be combined with a background"),process.exit(s.INVALID_INPUT)),e.renderTier!==void 0&&!["basic","standard","premium"].includes(e.renderTier)&&(a("Render tier must be basic, standard, or premium"),process.exit(s.INVALID_INPUT));let n=e.duration?Number.parseInt(e.duration,10):void 0;n!==void 0&&(!Number.isFinite(n)||n<1||n>300)&&(a("Duration must be between 1 and 300 seconds"),process.exit(s.INVALID_INPUT));let r=e.format==="human"?Lv("Generating presenter clip...").start():null;try{let i=e.idempotencyKey??di(),o=e.audioUrl?{audioUrl:e.audioUrl}:{script:e.script??"",...e.voiceId?{voiceId:e.voiceId}:{}},c=await xc({...o,aspect:e.aspect,...e.avatarId?{avatarId:e.avatarId}:{},...e.backgroundColor?{backgroundHex:e.backgroundColor}:{},...e.backgroundImageUrl?{backgroundImageUrl:e.backgroundImageUrl}:{},...e.brandingId?{brandingId:e.brandingId}:{},...e.castPresetId?{castPresetId:e.castPresetId}:{},...e.captions?{captions:!0}:{},...n!==void 0?{durationSec:n}:{},...e.fit?{fit:e.fit}:{},...t?{outputFormat:t}:{},...e.renderTier?{renderTier:e.renderTier}:{},...e.strictBranding?{strictBranding:!0}:{},title:e.title},i);if(!e.wait){r?.stop(),la(c,e.format);return}let l=await $e(()=>qo(c.requestId),_v,Uv);if(l.status==="failed")throw new de(l.error||"Presenter generation failed");if(!l.videoUrl)throw new Error("Presenter generation completed without a video URL");r&&(r.text="Downloading presenter clip..."),await Ie(l.videoUrl,e.output),r?.stop(),la(l,e.format),e.format==="human"&&C(`Saved to: ${e.output}`)}catch(i){r?.stop(),a(u(i,"Unknown error")),process.exit(s.GENERAL_ERROR)}}),Jv=new Pe("status").description("Check a presenter clip generation request").argument("<id>","Request ID").option("-f, --format <format>","Output format: human, json, quiet",b("--format",["human","json","quiet"]),"human").action(async(e,t)=>{try{la(await qo(e),t.format)}catch(n){a(u(n,"Unknown error")),process.exit(s.GENERAL_ERROR)}}),zv=new Pe("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??di(),r=await Rm(t.referenceImage,n),i=await p("generatePresenterLook",{baseProfileId:e,description:t.description,id:t.lookId,prompt:t.prompt,...r?{referenceImages:r}:{},title:t.name},n);m(i)}catch(n){a(u(n,"Look generation failed")),process.exit(s.GENERAL_ERROR)}}),Hv=new Pe("status").description("Read presenter look generation status").argument("<run-id>","Durable run ID").option("-f, --format <format>","Output format: human, json, quiet",b("--format",["human","json","quiet"]),"human").action(async(e,t)=>{try{let n=await R("generatePresenterLook",e);if(t.format==="json")return m(n);if(t.format==="quiet")return console.log(n.status);I(`Run ID: ${e}`),I(`Status: ${n.status}`),n.error&&a(ge(n.error))}catch(n){a(u(n,"Status failed")),process.exit(s.GENERAL_ERROR)}}),Xv=new Pe("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??di(),r=await Rm(t.referenceImage,n),i=await p("revisePresenterLook",{instruction:t.instruction,...r?{referenceImages:r}:{},sourceLookId:e},n);m(i)}catch(n){a(u(n,"Look revision failed")),process.exit(s.GENERAL_ERROR)}}),Yv=new Pe("revision-status").description("Read presenter Look revision status").argument("<run-id>","Durable run ID").option("-f, --format <format>","Output format: human, json, quiet",b("--format",["human","json","quiet"]),"human").action(async(e,t)=>{try{let n=await R("revisePresenterLook",e);if(t.format==="json")return m(n);if(t.format==="quiet")return console.log(n.status);I(`Run ID: ${e}`),I(`Status: ${n.status}`),n.error&&a(ge(n.error))}catch(n){a(u(n,"Revision status failed")),process.exit(s.GENERAL_ERROR)}}),Qv=new Pe("look").description("Manage looks under an existing personal presenter").addCommand(zv).addCommand(Xv).addCommand(Yv).addCommand(Hv),ma=new Pe("avatar").description("Generate presenter clips and looks; avatar options lists the voices and looks used by presentation video presenter and cast preset").addCommand(Vv).addCommand(Kv).addCommand(Wv).addCommand(Qv).addCommand(Jv);ma.addHelpText("after",`
|
|
67
67
|
${Nt.bold("Examples:")}
|
|
@@ -709,6 +709,16 @@ ${n} presentation video scorm export <project-id> --pass-mark 80
|
|
|
709
709
|
the original set and item ids \u2014 safe to retry, never a duplicate. List and
|
|
710
710
|
read sets with \`${n} study-set list\` and \`${n} study-set get <id>\`.
|
|
711
711
|
|
|
712
|
+
Placing questions:
|
|
713
|
+
- Every question pauses the video. Give one quiz's questions the SAME
|
|
714
|
+
\`atSec\` \u2014 the player shows them back to back with no audio between; a
|
|
715
|
+
moment apart (under 2 s) is refused because narration plays between them.
|
|
716
|
+
- Put them after the scene's narration ends: an \`atSec\` just under the
|
|
717
|
+
scene's length (too late is refused with that length).
|
|
718
|
+
- A spoken call to action ("book a time", "the link is below") needs a
|
|
719
|
+
button: \`interaction add --button \u2026 --action open-url --url \u2026\`. A video
|
|
720
|
+
frame is not clickable.
|
|
721
|
+
|
|
712
722
|
## Every capability in this flow
|
|
713
723
|
|
|
714
724
|
${Rt(r,n)}
|
|
@@ -1509,7 +1519,7 @@ ${n} video <sub> --help
|
|
|
1509
1519
|
\`\`\`
|
|
1510
1520
|
|
|
1511
1521
|
The catalog is authoritative and always current; this file is a snapshot of it.
|
|
1512
|
-
`}function Gh(e,t){return[{content:bo(e,t),name:"video"},{content:Bn(e,t),name:"deck-to-video"}]}import{chmodSync as h$,existsSync as hd,mkdirSync as fd,readFileSync as y$,rmSync as b$,writeFileSync as wo}from"fs";import{homedir as zh}from"os";import{basename as w$,dirname as v$,join as Ye,relative as I$,resolve as Lr}from"path";var Zt=[{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"}];import{createHash as u$}from"crypto";var Kh="mindframes.app-skill.json";function ud(){return"0.3.
|
|
1522
|
+
`}function Gh(e,t){return[{content:bo(e,t),name:"video"},{content:Bn(e,t),name:"deck-to-video"}]}import{chmodSync as h$,existsSync as hd,mkdirSync as fd,readFileSync as y$,rmSync as b$,writeFileSync as wo}from"fs";import{homedir as zh}from"os";import{basename as w$,dirname as v$,join as Ye,relative as I$,resolve as Lr}from"path";var Zt=[{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"}];import{createHash as u$}from"crypto";var Kh="mindframes.app-skill.json";function ud(){return"0.3.29"}function gd(e,t,n){let r=u$("sha256");r.update(e);for(let i of t??[])r.update("\0ref:"),r.update(i.name),r.update("\0"),r.update(i.content);for(let i of[...n??[]].sort((o,c)=>o.path.localeCompare(c.path)))r.update("\0file:"),r.update(i.path),r.update("\0"),r.update(i.content);return r.digest("hex")}function g$(e){let t=e.match(/^description:\s*(.*)$/m);if(!t)return"";let n=t[1].trim().replace(/^["']|["']$/g,"");if(!n||/^[>|][-+]?$/.test(n)){let r=(t.index??0)+t[0].length,i=[];for(let o of e.slice(r).split(`
|
|
1513
1523
|
`).slice(1)){if(!/^\s+\S/.test(o))break;i.push(o.trim())}return i.join(" ").replace(/^["']|["']$/g,"")}return n}function f$(e,t){return["SKILL.md",...(e??[]).map(n=>`references/${n.name}.md`),...(t??[]).map(n=>n.path)]}function Wh(e,t){return{schemaVersion:1,id:e.name,name:e.name,version:ud(),apiBaseUrl:e.url,mcp:{name:e.name,url:`${e.url.replace(/\/$/,"")}/api/mcp`},skills:t.map(n=>({slug:n.name,description:g$(n.content),sha256:gd(n.content,n.references,n.files),files:f$(n.references,n.files)}))}}var k$={sonnet:"claude-sonnet-5.5",haiku:"claude-haiku-4.5",opus:"claude-opus-5.5"},x$=["permissionMode","skills","subagentType"];function R$(e,t){if(t!=="copilot")return e;let n=e.match(/^---\n([\s\S]*?)\n---\n/);if(!n)return Jh(e);let r=n[1],i=e.slice((n.index??0)+n[0].length);r=r.replace(/^(model:\s*)(\S+)([ \t]*)$/m,(c,l,d,g)=>`${l}${k$[d]??d}${g}`);for(let c of x$)r=r.replace(new RegExp(`^${c}:[^
|
|
1514
1524
|
]*
|
|
1515
1525
|
?`,"m"),"");r=r.replace(/\n+$/,"");let o=Jh(i);return`---
|
|
@@ -3010,7 +3020,7 @@ ${se.bold("Examples:")}
|
|
|
3010
3020
|
$ ${f.commands[0]} skill pack -o ./dist-skill-bundle ${se.gray("# distributable plugin bundle")}
|
|
3011
3021
|
`);cn.command("install").description(`Install ${f.displayName} skills for AI coding assistants`).argument("[type]","Skill type, or omit to install the core skill suite").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&&!Jn.includes(t.mode)&&(a(`Invalid mode: ${t.mode}. Must be one of: ${Jn.join(", ")}`),process.exit(1));let n={...bd,mode:t.mode},r=[];e&&!Ct.includes(e)&&(a(`Invalid skill type: ${e}. Must be one of: ${Ct.join(", ")}`),process.exit(1));let i=await bn();i.source==="snapshot"&&(q(`Live capability catalog unavailable (${i.reason??"unknown reason"}) \u2014 generating from the snapshot baked into this CLI.`),console.log(se.gray(` Run \`${f.commands[0]} login\` then re-run with --force to regenerate from the live catalog.`))),r.push(...yd(e,n,i)),console.log();for(let o of r){I(`Installing ${o.name}...`);let c=Io(o.name,o.content,{dir:t.dir,local:t.local,force:t.force},o.references,o.files);if(c.installed.length>0&&(C(`${o.name} installed successfully`),O(" Installed to",c.installed.join(", "))),c.skipped.length>0&&(I(` Skipped (already exists): ${c.skipped.join(", ")}`),c.outdated.length>0&&q(` Newer skill content available for: ${c.outdated.join(", ")}`),console.log(se.gray(" Use --force to overwrite"))),c.errors.length>0)for(let l of c.errors)a(` ${l}`);c.installed.length===0&&c.skipped.length===0&&c.errors.length===0&&(I(" No supported AI coding assistants detected"),console.log(se.gray(` Supported editors: ${Yh().join(", ")}`)),console.log(se.gray(" Use --dir <path> to install to a specific directory"))),console.log()}});cn.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&&!Jn.includes(t.mode)&&(a(`Invalid mode: ${t.mode}. Must be one of: ${Jn.join(", ")}`),process.exit(1));let n={...bd,mode:t.mode},r=await bn(),o={main:()=>Or(n,r),video:()=>Nr(n,r),presentation:()=>Dr(n,r),"presentation-video":()=>Ke(n,r,"presentation-video"),"presentation-edit":()=>$r(n),tts:()=>sn(n),music:()=>rn(n),sfx:()=>an(n),mix:()=>nn(n),image:()=>tn(n),"video-search":()=>dn(n),scrape:()=>on(n),branding:()=>Ke(n,r,"branding"),agents:()=>Ke(n,r,"agents"),config:()=>en(n)}[e];o?console.log(o()):(a(`Invalid skill type: ${e}. Must be one of: ${Ct.join(", ")}`),process.exit(1))});cn.command("pack").description(`Write the ${f.displayName} skill bundle to a directory \u2014 skills tree, app-skill manifest, and a Claude Code plugin descriptor`).argument("[type]","Skill type, or omit to pack the core skill suite").requiredOption("-o, --out <dir>","Output directory for the bundle").option("-m, --mode <mode>","Skill mode: standalone (render to file) or studio (Studio Preview)","standalone").action(async(e,t)=>{t.mode&&!Jn.includes(t.mode)&&(a(`Invalid mode: ${t.mode}. Must be one of: ${Jn.join(", ")}`),process.exit(1)),e&&!Ct.includes(e)&&(a(`Invalid skill type: ${e}. Must be one of: ${Ct.join(", ")}`),process.exit(1));let n={...bd,mode:t.mode},r=await bn(),i=yd(e,n,r);i.length===0&&(a(`Invalid skill type: ${e}`),process.exit(1));let o=Zh(String(t.out),n,i);C(`Packed ${o.skillNames.length} skill${o.skillNames.length===1?"":"s"}`),O(" Bundle",o.outDir),O(" Manifest",o.manifestPath),O(" Catalog source",r.source),console.log(se.gray(" The bundle is a Claude Code plugin as-is (.claude-plugin/plugin.json)."))});cn.command("uninstall").description(`Remove ${f.displayName} skills from AI coding assistants`).argument("[type]","Skill type, or omit to remove installed skills").option("-g, --global","Uninstall globally (from home directory)",!0).option("-l, --local","Uninstall locally (from current directory)").action(async(e,t)=>{let n=[];e&&!Ct.includes(e)&&(a(`Invalid skill type: ${e}. Must be one of: ${Ct.join(", ")}`),process.exit(1)),(!e||e==="main")&&n.push(f.name),(!e||e==="video")&&n.push(`${f.name}-video`),(!e||e==="presentation")&&n.push(`${f.name}-presentation`),(!e||e==="presentation-video")&&n.push(`${f.name}-presentation-video`),(!e||e==="presentation-edit")&&n.push(`${f.name}-presentation-edit`),(!e||e==="tts")&&n.push(`${f.name}-tts`),(!e||e==="music")&&n.push(`${f.name}-music`),(!e||e==="sfx")&&n.push(`${f.name}-sfx`),(!e||e==="mix")&&n.push(`${f.name}-mix`),(!e||e==="image")&&n.push(`${f.name}-image`),(!e||e==="video-search")&&n.push(`${f.name}-video-search`),(!e||e==="scrape")&&n.push(`${f.name}-scrape`),(!e||e==="branding")&&n.push(`${f.name}-branding`),(!e||e==="agents")&&n.push(`${f.name}-agents`),(!e||e==="config")&&n.push(`${f.name}-config`),console.log();for(let r of n){let i=ko(r,{local:t.local});if(i.removed.length>0?(C(`${r} uninstalled`),O(" Removed from",i.removed.join(", "))):I(` ${r} not found`),i.errors.length>0)for(let o of i.errors)q(` Failed to remove: ${o}`)}console.log()});import wd from"chalk";import{Command as A$}from"commander";var ey=new A$("whoami").description("Show current user and team information").option("-f, --format <format>","Output format (human, json)",b("--format",["human","json"]),"human").action(async e=>{await w();try{let t=await Je();if(Bo(),e.format==="json"){console.log(JSON.stringify(t,null,2));return}De("User"),console.log(),O("Email",t.user.email),t.user.username&&O("Username",t.user.username),(t.user.firstName||t.user.lastName)&&O("Name",[t.user.firstName,t.user.lastName].filter(Boolean).join(" "));let n=t.authType==="apiKey"?"API Key":t.authType==="oauth"?"OAuth":"Session";if(O("Auth Type",n),t.currentTeam&&(console.log(),De("Current Team"),console.log(),O("ID",t.currentTeam.id),O("Name",t.currentTeam.name),O("Plan",t.currentTeam.planName),O("Role",t.currentTeam.isOwner?"Owner":"Member")),t.teams.length>1){console.log(),De("All Teams"),console.log();for(let r of t.teams){let i=r.isCurrent?wd.green(" (current)"):"";console.log(` ${wd.bold(r.name)}${i}`),console.log(wd.gray(` ID: ${r.id} | Plan: ${r.planName} | Role: ${r.role}`))}}console.log()}catch(t){a("The command failed. Please try again."),process.exit(t.exitCode??1)}});function ty(e){return e[0]==="--"?e.slice(1):e}import vd from"chalk";function Id(e){e.configureOutput({outputError:(t,n)=>{n(vd.red(t));let r=/unknown option '(-{1,2}[^'\s=]+)/.exec(t);if(!r)return;let i=O$(e,r[1]);i&&n(vd.yellow(`Did you mean '${i}'?
|
|
3012
3022
|
`)),n(vd.gray(`Run '${T$(e)} --help' to see the accepted options.
|
|
3013
|
-
`))}});for(let t of e.commands)Id(t)}function T$(e){let t=[],n=e;for(;n;)t.unshift(n.name()),n=n.parent;return t.join(" ")}function O$(e,t){let n,r=Number.POSITIVE_INFINITY;for(let o of e.options)if(!o.hidden)for(let c of[o.short,o.long]){if(!c)continue;let l=kd(t,c);l<r&&(r=l,n=o.flags)}let i=t.startsWith("--")?2:1;return n!==void 0&&r<=i?n:void 0}function kd(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,i)=>i);for(let r=1;r<=e.length;r++){let i=[r];for(let o=1;o<=t.length;o++){let c=e[r-1]===t[o-1]?0:1;i[o]=Math.min(i[o-1]+1,n[o]+1,n[o-1]+c)}n=i}return n[t.length]}var D$="0.3.
|
|
3023
|
+
`))}});for(let t of e.commands)Id(t)}function T$(e){let t=[],n=e;for(;n;)t.unshift(n.name()),n=n.parent;return t.join(" ")}function O$(e,t){let n,r=Number.POSITIVE_INFINITY;for(let o of e.options)if(!o.hidden)for(let c of[o.short,o.long]){if(!c)continue;let l=kd(t,c);l<r&&(r=l,n=o.flags)}let i=t.startsWith("--")?2:1;return n!==void 0&&r<=i?n:void 0}function kd(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,i)=>i);for(let r=1;r<=e.length;r++){let i=[r];for(let o=1;o<=t.length;o++){let c=e[r-1]===t[o-1]?0:1;i[o]=Math.min(i[o-1]+1,n[o]+1,n[o-1]+c)}n=i}return n[t.length]}var D$="0.3.29",ne=new $$,G=f.commands[0];ne.name(G).description(`${f.displayName} CLI \u2014 presentations, videos, avatars, audio, branding, media and research`).version(D$,"-v, --version","Show version number").option("--debug","Enable debug logging").option("--no-color","Disable colored output").option("--wait-for-approval","When a command needs browser approval, print the URL and read the minted receipt from stdin instead of exiting");ne.addCommand(ul);Sh(ne);ne.addCommand(Pl);ne.addCommand(El);ne.addCommand(Cl);ne.addCommand(Il);ne.addCommand(ey);ne.addCommand(Dl);ne.addCommand(Nl);ne.addCommand(wl);ne.addCommand(cn);ne.addCommand(ni);var ny=Rl();ny.commands.length>0&&ne.addCommand(ny);function N$(e){let t=e.toLowerCase(),n=t.length<=4?1:2,r,i=Number.POSITIVE_INFINITY;for(let o of ne.commands)for(let c of[o.name(),...o.aliases()]){let l=kd(t,c.toLowerCase());l<i&&(i=l,r=o.name())}return r!==void 0&&i<=n?r:void 0}ne.on("command:*",e=>{let t=String(e[0]);console.error(te.red(`Error: Unknown command '${t}'`)),console.error();let n=N$(t);n&&console.error(`Did you mean '${n}'?`),console.error(`Run '${G} --help' to see available commands.`),console.error(`Run '${G} capabilities' for the full list of callable capabilities.`),process.exit(1)});ne.addHelpText("after",`
|
|
3014
3024
|
${te.bold("Start here:")}
|
|
3015
3025
|
$ ${G} capabilities ${te.gray("# every capability + its exact command path")}
|
|
3016
3026
|
$ ${G} <group> --help ${te.gray("# drill into any command group above")}
|