@hraness/slopcamera 3.2.4 → 3.2.5

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.
@@ -1533,7 +1533,7 @@ ${V}`.trim();return{exitCode:X,output:j}}async function OG(_,$,F){T9(F);let w=aw
1533
1533
  for (const url of urls.keys()) nativeRevokeUrl(url);
1534
1534
  urls.clear(); liveBytes = 0;
1535
1535
  }, { once: true }]);
1536
- }`);return is($,"return securityViolations;","return securityViolations + (sparkWorkerFailure === null ? 0 : 1);")}var nR=hQ.string().regex(/^[a-f0-9]{64}$/u),rW0=hQ.strictObject({key:hQ.string().min(1).max(512),sha256:nR}),TF=hQ.strictObject({algorithm:hQ.literal("sha256-merkle-v1"),leaves:hQ.array(rW0).min(4).max(256).superRefine((_,$)=>{for(let F=1;F<_.length;F+=1)if(_[F-1].key>=_[F].key)$.addIssue({code:"custom",message:"HTML-overlay integrity leaves must have unique ASCII-sorted keys.",path:[F,"key"]})}),rootSha256:nR,runtimeSha256:nR,schemaVersion:hQ.literal(1)}),u5=Object.freeze({browser:"playwright-chromium",browserVersion:nW0.version,browserContext:Object.freeze({acceptDownloads:!1,colorScheme:"light",locale:"en-US",offline:!0,permissions:Object.freeze([]),reducedMotion:"no-preference",serviceWorkers:"block",timezoneId:"UTC"}),contentSecurityPolicy:Object.freeze(["default-src 'none'","base-uri 'none'","connect-src 'none'","font-src https://slopcamera-overlay.invalid data:","form-action 'none'","frame-src 'none'","img-src https://slopcamera-overlay.invalid data:","media-src https://slopcamera-overlay.invalid data:","object-src 'none'","script-src 'unsafe-inline' https://slopcamera-overlay.invalid","style-src 'unsafe-inline'","worker-src 'none'"]),documentUrl:"https://slopcamera-overlay.invalid/slopcamera-overlay/document",environment:Object.freeze({fixed:Object.freeze({LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",PATH:"/usr/bin:/bin",TZ:"UTC"}),inherited:Object.freeze([]),privateDirectories:Object.freeze(["HOME","TMPDIR"])}),launch:Object.freeze({args:Object.freeze(["--disable-background-networking","--disable-breakpad","--disable-component-update","--disable-default-apps","--disable-domain-reliability","--disable-extensions","--disable-features=Translate,MediaRouter,OptimizationHints","--disable-quic","--disable-sync","--enable-unsafe-swiftshader","--force-webrtc-ip-handling-policy=disable_non_proxied_udp","--metrics-recording-only","--mute-audio","--no-default-browser-check","--no-first-run","--no-proxy-server","--use-angle=swiftshader"]),headless:!0,libraryArgs:Object.freeze({vgpu:Object.freeze(["--enable-unsafe-webgpu","--use-webgpu-adapter=swiftshader"])})}),routing:Object.freeze({allowedOrigin:"https://slopcamera-overlay.invalid",declaredResourcesOnly:!0,remoteNetworkDenied:!0}),runtimeSnapshot:Object.freeze({macosAnchor:"/private/tmp",macosAnchorPolicy:"physical-root-owned-sticky-direct-child",cleanupIdentity:"container-direct-children-and-complete-runtime-manifest",copyBufferBytes:4194304,filesystemGuard:"anchor-basename-and-recursive-parent-watch-with-path-identities",orphanRecovery:"active-to-released-lease-last-atomic-quarantine-double-open-proof",verifiedMacosFilesystemFlags:"user-immutable-recursive"}),schemaVersion:1,screenshot:Object.freeze({omitBackground:!0,scale:"css",type:"png"})}),oW0=Object.freeze({...u5.launch,args:Object.freeze([...u5.launch.args.filter((_)=>_!=="--enable-unsafe-swiftshader"&&_!=="--use-angle=swiftshader"),"--use-angle=metal","--disable-software-rasterizer"])});function iW0(_){if(_===void 0)return u5;let $=U9.parse(_);return Object.freeze({...u5,contentSecurityPolicy:$==="three-spark-webgl2-hardware-v1"?Object.freeze(u5.contentSecurityPolicy.map((F)=>{if(F==="worker-src 'none'")return"worker-src blob:";if(F==="connect-src 'none'")return"connect-src https://slopcamera-overlay.invalid data:";if(F.startsWith("script-src "))return`${F} 'wasm-unsafe-eval'`;return F})):u5.contentSecurityPolicy,executionProfile:$,launch:oW0,gpu:Object.freeze({admission:"matching-active-webgl2-and-cdp-angle-metal-v1",capture:"host-held-native-context-health-before-and-after-every-screenshot",fallback:"reject-software-or-unknown",platform:"darwin",receipt:"bounded-context-device-driver-os-evidence-per-batch"}),schemaVersion:2})}function GG(_,$=[]){let F=iW0(_),Q=B9.parse($).filter((Z)=>Z.transport==="fetch").map((Z)=>`${u5.routing.allowedOrigin}${A8(Z)}`);if(Q.length===0||!F.contentSecurityPolicy.includes("connect-src 'none'"))return F;return Object.freeze({...F,contentSecurityPolicy:Object.freeze(F.contentSecurityPolicy.map((Z)=>Z==="connect-src 'none'"?`connect-src ${Q.join(" ")}`:Z)),schemaVersion:3})}function rR(_,$){if($===void 0)return;U9.parse($);let F=$==="three-webgl2-hardware-v1"?["three"]:["@sparkjsdev/spark","three","three/addons/postprocessing/Pass.js"];if(k([..._].sort())!==k(F))throw Error("Hardware execution profile requires its exact approved scene library set.")}function yN(_){return pW0("sha256").update(_).digest("hex")}function aW0(_,$){return yN(k({domain:"slopcamera.html-overlay-integrity-leaf/v1",key:_,value:$}))}function tW0(_){let $=_.map((F)=>yN(["slopcamera.html-overlay-integrity-node/v1","leaf",F.key,F.sha256].join("\x00")));while($.length>1){let F=[];for(let w=0;w<$.length;w+=2){let Q=$[w],Z=$[w+1]??Q;F.push(yN(["slopcamera.html-overlay-integrity-node/v1","branch",Q,Z].join("\x00")))}$=F}return $[0]}function UF(_,$,F){let w=qQ.parse(_);rR(w.libraries,F);let Q=AF.parse($),Z=w.libraries.map(LF),J=oL(w.libraries),X=DR({canvas:w.canvas,parameters:w.parameters,resources:w.resources,seed:w.seed,timing:w.timing}),V=F==="three-spark-webgl2-hardware-v1"?as(X):X,Y=yN(Buffer.from(V,"utf8")),H=[{key:"authoring-config",value:{canvas:w.canvas,kind:w.kind,parameters:w.parameters,schemaVersion:w.schemaVersion,seed:w.seed,timing:w.timing}},{key:"browser-runtime",value:Q},{key:"renderer-contract",value:GG(F,w.resources)},{key:"document",value:{bytes:Buffer.byteLength(w.html,"utf8"),sha256:yN(Buffer.from(w.html,"utf8"))}},{key:"import-map",value:J},{key:"runtime",value:{bytes:Buffer.byteLength(V,"utf8"),sha256:Y}},...Z.map((W)=>({key:`library:${W.specifier}`,value:W})),...w.resources.map((W)=>({key:`resource:${W.name}`,value:W}))].map((W)=>({key:W.key,sha256:aW0(W.key,W.value)})).sort((W,O)=>W.key<O.key?-1:W.key>O.key?1:0),K=TF.parse({algorithm:"sha256-merkle-v1",leaves:H,rootSha256:tW0(H),runtimeSha256:Y,schemaVersion:1});return Object.freeze({importMap:J,integrity:Object.freeze(K),libraryLocks:Object.freeze(Z),runtimeSource:V})}var DG="slopcamera-3.2.4",gN=["scene.inspect","scene.patch","scene.evaluate","scene.render","slopcamera.studio.run","spatial.project.snapshot","spatial.project.migrate","spatial.project.patch","spatial.project.restore","spatial.project.add-shot","spatial.project.add-candidate","spatial.project.select-candidate","spatial.project.reconcile","project.snapshot","analysis.project-inactivity","analysis.faces","analysis.music","analysis.scenes","analysis.project-auto-zooms","derive.edit-batch","project.commit-edits","derive.follow-faces","edit.create-revision","edit.create-candidate-revision","edit.bind-candidate-revision","edit.freeze-revision","iteration.create-candidate","iteration.create-matrix","iteration.select","project.promote-selection","render.bind-candidate-output","render.project-plan","render.project","render.materialize-selection","media.ingest","media.overlay","media.html-overlay","media.audio-effects","media.color-grade","gateway.image","gateway.video","gateway.speech","gateway.transcription","recording.start","recording.pause","recording.resume","recording.stop","slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.vectorize","slopcamera.image.generate"],hN=["cpu","local-io","ffmpeg","vision","whisper","network","paid-call","project-render","project-publication","output-publication","capture-device","browser"];import{isAbsolute as eW0,relative as oR,resolve as ts}from"path";import{z as w1}from"zod";var _K0=w1.strictObject({path:X0}),vQ=536870912,zG=w1.union([_K0,Kj,N0]),CG=w1.strictObject({endBehavior:w1.enum(["hide","loop","freeze-end"]).default("hide"),playbackRate:w1.number().finite().positive().max(64).default(1),sourceInUs:w1.number().int().safe().nonnegative().default(0),sourceOutUs:w1.number().int().safe().positive().optional()}).prefault({}),iR=w1.strictObject({artifact:N0,id:w1.string().min(1).max(256),provider:w1.enum(["apple-emoji-pack","brand-catalog"]),selector:lB,variant:w1.enum(["color","duotone"])}),$K0=w1.discriminatedUnion("kind",[w1.strictObject({artifact:zG,kind:w1.literal("image")}),w1.strictObject({artifact:zG,kind:w1.literal("svg")}),w1.strictObject({artifact:zG,kind:w1.literal("gif"),playback:CG}),w1.strictObject({artifact:zG,audioPolicy:oW.default({kind:"mute"}),kind:w1.literal("video"),playback:CG}),w1.strictObject({kind:w1.literal("emoji"),provider:w1.enum(["apple-emoji-pack","brand-catalog","auto"]).default("auto"),query:w1.string().min(1).max(256),resolved:iR.optional(),variant:w1.enum(["color","duotone"]).optional()})]),es=w1.discriminatedUnion("kind",[w1.strictObject({artifact:N0,kind:w1.literal("image")}),w1.strictObject({artifact:N0,kind:w1.literal("svg")}),w1.strictObject({artifact:N0,kind:w1.literal("gif"),playback:CG}),w1.strictObject({artifact:N0,audioPolicy:oW,kind:w1.literal("video"),playback:CG}),w1.strictObject({kind:w1.literal("emoji"),provider:w1.enum(["apple-emoji-pack","brand-catalog","auto"]),query:w1.string().min(1).max(256),resolved:iR,variant:w1.enum(["color","duotone"]).optional()})]),aR=w1.strictObject({anchor:uB.default("center"),blendMode:w1.enum(["normal","addition","darken","lighten","multiply","overlay","screen"]).default("normal"),crop:sB.default({kind:"none"}),entrance:rY.default({kind:"none"}),exit:rY.default({kind:"none"}),fit:w1.enum(["contain","cover","fill"]).default("fill"),mask:pB.default({kind:"none"}),motion:nB.default({kind:"none"}),opacity:w1.number().finite().min(0).max(1).default(1),position:A$.default({x:0,y:0}),rotationDegrees:w1.number().finite().min(-3600).max(3600).default(0),scale:w1.number().finite().positive().max(128).default(1),size:cB.default({kind:"intrinsic"}),zIndex:w1.number().int().safe().default(0)}).prefault({}),xQ=w1.strictObject({capabilityBindings:C5.optional(),identityKey:w1.string().min(1).max(128).optional(),layout:aR,project:T1,range:P0,source:$K0}),tR=xQ.extend({source:es}).strict(),kF=w1.strictObject({artifact:N0,created:w1.boolean(),operation:a2,receipt:N0}),eR=w1.strictObject({artifact:N0,createdAt:w1.string().datetime({offset:!0}),exactInputSha256:P,ffprobeVersion:w1.string().min(1).max(256).nullable(),kind:w1.union([w1.literal("slopcamera.local-overlay-preparation-receipt"),w1.literal("studio.local-overlay-preparation-receipt")]),operationSha256:P,overlayId:w1.string().min(1).max(128),projectGenerationSha256:P,projectId:T1,schemaVersion:w1.literal(1)});function FK0(_){let $=_.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test($))return{kind:"id",value:$};if([..._].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test(_))return{kind:"unicode",value:_};return{kind:"name",value:_}}function wK0(_){if(!("bytes"in _))return _;return N0.parse({bytes:_.bytes,path:_.path,sha256:_.sha256})}function _p(_){return _.kind==="image"||_.kind==="gif"||_.kind==="video"?["ffprobe"]:[]}async function QK0(_,$,F,w){let Q=await w(_.paths.repositoryRoot,$.query,$.variant,$.provider),Z=oR(_.paths.repositoryRoot,Q.path),J=await A1(_,{path:Z},F,vQ);if(J.artifact.sha256!==Q.sha256)throw new N("conflict","Resolved emoji bytes disagree with the checked emoji catalog.");let X=iR.parse({artifact:J.artifact,id:Q.id,provider:Q.provider,selector:FK0($.query),variant:Q.variant});if($.resolved!==void 0&&k($.resolved)!==k(X))throw new N("conflict","The checked emoji asset changed after exact node planning.");return es.parse({...$,resolved:X})}async function _E(_,$,F,w={}){let Q=xQ.parse($),Z=_p(Q.source),J=Q.source.kind==="emoji"?QK0(_,Q.source,F,w.resolveEmoji??mX):A1(_,wK0(Q.source.artifact),F,vQ).then((Y)=>({...Q.source,artifact:Y.artifact})),[X,V]=await Promise.all([J,d5(_,Z,Q.capabilityBindings)]);return tR.parse({...Q,capabilityBindings:V,source:X})}function ZK0(_,$){let F=ts(_,$),w=oR(ts(_),F);if(w===""||w.startsWith("..")||eW0(w))throw new N("unsafe-path","Prepared overlay asset escaped its project bundle.");return F}function JK0(_,$,F){let w=dB.parse($),Q={bytes:w.asset.bytes,mediaType:w.asset.mediaType,sha256:w.asset.sha256},Z=w.kind==="image"||w.kind==="svg"?{asset:Q,kind:w.kind}:w.kind==="emoji"?{asset:Q,kind:w.kind,provider:w.provider,selector:w.selector}:{asset:Q,audioPolicy:w.audioPolicy,kind:w.kind,playback:w.playback};return`overlay_${S({domain:"studio.media-overlay-operation/v1",identityKey:_.identityKey??null,intrinsicSize:F,layout:_.layout,project:_.project,range:_.range,source:Z}).slice(0,32)}`}function XK0(_={}){let $=_.ingestFile??XG,F=_.ingestEmoji??VG,w=_.inspectPng??yQ,Q=_.inspectSvg??CF,Z=_.probe??L9,J=_.resolveEmoji??mX;return{inputSchema:xQ,inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",lifecycle:{kind:"local-artifact",execute:async(X,V)=>{n(X.abortSignal);let Y=await _E(X.application,V,X.abortSignal,{resolveEmoji:J}),j=_p(Y.source);await A9(X,X.application,Y.capabilityBindings,j);let H=Y.capabilityBindings??await g6(X.application,j),K=await i1(X.application,Y.project);if(m5(X.expectedProjectGeneration,K.generation),Y.range.endUs>K.plan.timelineDurationUs)throw new N("usage","Overlay range exceeds the project timeline.");let W=Z8(Q8(K.plan),Y.range).reduce((z,C)=>z+C.output.endUs-C.output.startUs,0);if(W<=0)throw new N("conflict","Overlay range has no visible kept output time.");let O=Y.source.kind==="emoji"?void 0:await A1(X.application,Y.source.artifact,X.abortSignal,vQ),L=Y.source.kind==="emoji"?Y.source:void 0,G=L===void 0?void 0:await J(X.application.paths.repositoryRoot,L.query,L.variant,L.provider);if(G!==void 0&&L!==void 0&&(G.id!==L.resolved.id||G.provider!==L.resolved.provider||G.variant!==L.resolved.variant||G.sha256!==L.resolved.artifact.sha256))throw new N("conflict","Resolved emoji changed immediately before preparation.");let D=await W5(X);try{await X.workflow?.beforePublication(),n(X.abortSignal);let z=G===void 0?await $(K.openProject.directory.path,O.absolutePath,Y.source.kind):await F(K.openProject.directory.path,G),C=O?.artifact??L.resolved.artifact;if(z.bytes!==C.bytes||z.sha256!==C.sha256||z.provenance.sourceSha256!==C.sha256)throw new N("conflict","Prepared overlay bytes disagree with the exact bound source.");let A=ZK0(K.openProject.directory.path,z.path),B=(await A1(X.application,{path:oR(X.application.paths.repositoryRoot,A)},X.abortSignal,vQ)).artifact;if(B.bytes!==z.bytes||B.sha256!==z.sha256)throw new N("conflict","Prepared project asset disagrees with its published bytes.");let T=z.mediaType==="image/svg+xml"?{...await Q(A),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:Y.source.kind==="emoji"?{...await w(A),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await Z(h4(H,"ffprobe"),new e_(g$(X.application,H),X.abortSignal),A),M={height:"pixelHeight"in T?T.pixelHeight:T.height,width:"pixelWidth"in T?T.pixelWidth:T.width},R={bytes:z.bytes,mediaType:z.mediaType,path:z.path,provenance:z.provenance,sha256:z.sha256},g;if(Y.source.kind==="image"||Y.source.kind==="svg")g={asset:R,kind:Y.source.kind};else if(Y.source.kind==="emoji")g={asset:R,kind:"emoji",provider:Y.source.resolved.provider,selector:Y.source.resolved.selector};else{if(T.durationUs===null||T.durationUs<=0)throw new N("invalid-data","Animated overlay media must report a positive duration.");let m=lX({mediaDurationUs:T.durationUs,outputDurationUs:W,playbackRate:Y.source.playback.playbackRate,sourceInUs:Y.source.playback.sourceInUs,sourceOutUs:Y.source.playback.sourceOutUs}),y={audioEndUs:T.audioEndUs,audioStartUs:T.audioStartUs,audioStreamIndex:T.audioStreamIndex,endBehavior:Y.source.playback.endBehavior,playbackRate:Y.source.playback.playbackRate,streamStartUs:T.videoStartUs,videoStreamIndex:T.videoStreamIndex,...m};if(Y.source.kind==="gif")g={asset:R,audioPolicy:{kind:"mute"},kind:"gif",playback:y};else{if(Y.source.audioPolicy.kind!=="mute"&&!T.hasAudio)throw new N("conflict","The selected video overlay audio policy requires an audio stream.");g={asset:R,audioPolicy:Y.source.audioPolicy,kind:"video",playback:y}}}let U=a2.parse({...Y.layout,coordinateSpace:"output-pixels",intrinsicSize:M,overlayId:JK0(Y,g,M),range:Y.range,source:g}),E=eR.parse({artifact:B,createdAt:X.application.clock.now().toISOString(),exactInputSha256:S(Y),ffprobeVersion:j.length===0?null:P_(H,"ffprobe"),kind:"slopcamera.local-overlay-preparation-receipt",operationSha256:S(U),overlayId:U.overlayId,projectGenerationSha256:K.generation.generationSha256,projectId:K.project.projectId,schemaVersion:1}),f=await _$({context:X,receipt:E,workspace:D}),v=kF.parse({artifact:B,created:z.created,operation:U,receipt:f});return await K4(X,{inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",outputSchemaId:"slopcamera.operation.media.overlay.output/v1",version:1},v),v}finally{await D.dispose()}}},outputSchema:kF,outputSchemaId:"slopcamera.operation.media.overlay.output/v1",policy:{cache:"exact-run",cancellable:!0,effect:"local-derived-write",maxDurationMs:3600000,maxFanOut:0,maxInputBytes:262144,maxOutputBytes:2097152,preparation:["project-state","local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(X)=>X.receipt.path,summarize:(X)=>({fields:{bytes:X.artifact.bytes,created:X.created,kind:X.operation.source.kind,overlayId:X.operation.overlayId,receipt:X.receipt.path,sha256:X.artifact.sha256},kind:"media.overlay"}),version:1}}var $p=XK0();var AG=2097152,BG=134217728,wE=536870912,FE=["ffmpeg","ffprobe","html-browser"],WK0=E2.union([aL,E2.strictObject({path:X0}),N0]),KK0=E2.union([aL,N0]),OK0=E2.union([Q_,Kj]),LK0=v6.omit({bytes:!0,sha256:!0}).extend({artifact:OK0}).strict(),GK0=v6.extend({artifact:N0}).strict(),vN=E2.strictObject({canvas:EQ,capabilityBindings:C5.optional(),document:WK0,identityKey:E2.string().min(1).max(128).optional(),layout:aR,libraries:OF.default([]),parameters:xX.default({}),project:T1,range:P0,resources:E2.array(LK0).max(64).default([]),seed:E2.number().int().min(0).max(4294967295).default(0),timing:GF}),QE=vN.omit({document:!0,resources:!0}).extend({document:KK0,resources:E2.array(GK0).max(64)}).strict(),ZE=E2.strictObject({artifact:N0,browserVersion:E2.string().min(1).max(512),createdAt:E2.string().datetime({offset:!0}),executionIntegrity:TF.optional(),exactInputSha256:P,ffmpegVersion:E2.string().min(1).max(512),ffprobeVersion:E2.string().min(1).max(512),frameCount:E2.number().int().safe().positive(),kind:E2.union([E2.literal("slopcamera.html-overlay-preparation-receipt"),E2.literal("studio.html-overlay-preparation-receipt")]),libraryLocks:NR,libraryLocksSha256:P,operationSha256:P,overlayId:E2.string().min(1).max(128),projectGenerationSha256:P,projectId:T1,schemaVersion:E2.literal(1)}),wp=kF;function DK0(_){if(!("mediaType"in _.artifact))return _.artifact;if(_.artifact.mediaType!==_.mediaType)throw new N("invalid-data",`HTML overlay resource ${_.name} declares ${_.mediaType} but its generated artifact is ${_.artifact.mediaType}.`);return N0.parse({bytes:_.artifact.bytes,path:_.artifact.path,sha256:_.artifact.sha256})}async function zK0(_,$,F){if("html"in $)return $;return(await A1(_,$,F,AG)).artifact}function CK0(_,$){return Z8(Q8(_),$).reduce((F,w)=>F+w.output.endUs-w.output.startUs,0)}async function JE(_,$,F){let w=vN.parse($),[Q,Z,J]=await Promise.all([zK0(_,w.document,F),Promise.all(w.resources.map(async(Y)=>({...Y,artifact:(await A1(_,DK0(Y),F,BG)).artifact}))),d5(_,FE,w.capabilityBindings)]),X=B9.parse(Z.map(({artifact:Y,...j})=>({...j,bytes:Y.bytes,sha256:Y.sha256}))),V=new Map(Z.map((Y)=>[Y.name,Y.artifact]));return QE.parse({...w,capabilityBindings:J,document:Q,resources:X.map((Y)=>({...Y,artifact:V.get(Y.name)}))})}function AK0(_){let $;try{$=new TextDecoder("utf-8",{fatal:!0}).decode(_)}catch{throw new N("invalid-data","The HTML overlay document must be valid UTF-8.")}if($.trim()==="")throw new N("invalid-data","The HTML overlay document is empty.");return $}async function BK0(_,$){let F=await jK0(_,Fp.O_RDONLY|(Fp.O_NOFOLLOW??0));try{let w=await F.stat();if(!w.isFile()||w.size<=0)throw new N("invalid-data","Rendered HTML overlay is empty.");let Q=VK0("sha256"),Z=Buffer.allocUnsafe(1048576),J=0;while(J<w.size){n($);let V=await F.read(Z,0,Math.min(Z.byteLength,w.size-J),J);if(V.bytesRead===0)break;Q.update(Z.subarray(0,V.bytesRead)),J+=V.bytesRead}let X=await F.stat();if(J!==w.size||X.dev!==w.dev||X.ino!==w.ino||X.size!==w.size||X.mtimeMs!==w.mtimeMs||X.ctimeMs!==w.ctimeMs)throw new N("conflict","Rendered HTML overlay changed while it was being verified.");return Q.digest("hex")}finally{await F.close()}}var TK0=E2.object({streams:E2.array(E2.object({codec_name:E2.string(),height:E2.number().int().positive(),pix_fmt:E2.string(),width:E2.number().int().positive()})).min(1)});async function UK0(_,$,F,w,Q){let Z=await new e_(g$(_,$),Q).run([h4($,"ffprobe"),"-v","error","-select_streams","v:0","-show_entries","stream=codec_name,pix_fmt,width,height","-of","json",F],{maxOutputBytes:65536,stdin:"ignore",timeoutMs:30000});if(Z.exitCode!==0)throw new N("invalid-data","Rendered HTML overlay could not be inspected as an alpha video.");let J;try{J=JSON.parse(Z.stdout)}catch{throw new N("invalid-data","Rendered HTML overlay inspection returned invalid JSON.")}let X=TK0.parse(J).streams[0];if(X.codec_name!=="qtrle"||X.pix_fmt!=="argb"||X.width!==w.width||X.height!==w.height)throw new N("invalid-data","Rendered HTML overlay must be a canvas-sized qtrle/argb alpha video.",{stream:X})}function kK0(_,$,F){return`overlay_${S({assetSha256:F,authoring:$,domain:"studio.media-html-overlay-operation/v1",identityKey:_.identityKey??null,layout:_.layout,project:_.project,range:_.range}).slice(0,32)}`}function XE(_={}){let $=_.ingest??gs,F=_.probe??L9,w=_.bindBrowserRuntime??BF,Q=_.toolVersion??DG;return{inputSchema:vN,inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",lifecycle:{kind:"local-artifact",execute:async(Z,J)=>{n(Z.abortSignal);let X=await JE(Z.application,J,Z.abortSignal);await A9(Z,Z.application,X.capabilityBindings,FE);let V=X.capabilityBindings??await g6(Z.application,FE),Y=Z.application.htmlOverlayRenderer;if(Y===void 0)throw new N("unavailable","This Slopcamera host does not provide an HTML-overlay browser renderer.");let j=await i1(Z.application,X.project);if(m5(Z.expectedProjectGeneration,j.generation),X.range.endUs>j.plan.timelineDurationUs)throw new N("usage","HTML overlay range exceeds the project timeline.");let H=CK0(j.plan,X.range);if(H<=0)throw new N("conflict","HTML overlay range has no visible kept output time.");if(X.timing.durationUs!==H)throw new N("conflict","HTML overlay timing duration must equal the range's visible output duration.",{actualDurationUs:X.timing.durationUs,expectedDurationUs:H});let[K,W]=await Promise.all(["html"in X.document?Promise.resolve(X.document.html):I4(Z.application,X.document,Z.abortSignal,AG).then((D)=>AK0(D.data)),Promise.all(X.resources.map(async(D)=>({...D,absolutePath:(await A1(Z.application,D.artifact,Z.abortSignal,BG)).absolutePath})))]),O=qQ.parse({canvas:X.canvas,html:K,kind:"slopcamera.html-overlay",libraries:X.libraries,parameters:X.parameters,resources:W.map((D)=>({bytes:D.bytes,mediaType:D.mediaType,name:D.name,sha256:D.sha256,...D.transport===void 0?{}:{transport:D.transport},urlPath:D.urlPath})),schemaVersion:1,seed:X.seed,timing:X.timing}),L=await W5(Z),G=await YK0($E(L.path,"html-overlay-"));try{let D=await w(w$(V,"html-browser"),Z.abortSignal),z=UF(O,D).integrity,C=await Y.renderFrames({authoring:O,browserRuntime:D,outputDirectory:G,resources:W},Z.abortSignal),A=TF.parse(C.executionIntegrity);if(S(A)!==S(z))throw new N("conflict","HTML-overlay renderer returned integrity evidence that does not match the planned browser execution.");let B=jR.parse(C.libraryLocks),T=O.libraries.map(LF);if(S(B)!==S(T))throw new N("conflict","HTML-overlay renderer returned library locks that do not exactly match the authoring selection.");let M=B8(O.timing);if(C.frameCount!==M)throw new N("conflict","HTML-overlay renderer returned an unexpected frame count.");let R=$E(G,"overlay.mov"),g=[h4(V,"ffmpeg"),"-hide_banner","-loglevel","error","-nostdin","-n","-framerate",String(O.timing.fps),"-start_number","0","-i",C.framePattern,"-frames:v",String(C.frameCount),"-an","-c:v","qtrle","-pix_fmt","argb","-movflags","+faststart",R],U=await new e_(g$(Z.application,V),Z.abortSignal).run(g,{cwd:G,maxOutputBytes:1048576,stdin:"ignore",timeoutMs:3600000});if(U.exitCode!==0)throw new N("invalid-data",`FFmpeg could not encode the HTML overlay: ${U.stderr.slice(0,2000)}`);await UK0(Z.application,V,R,O.canvas,Z.abortSignal);let E=await BK0(R,Z.abortSignal);await Z.workflow?.beforePublication(),n(Z.abortSignal);let f=await $(j.openProject.directory.path,{command:g,generator:"slopcamera-html-overlay",generatorVersion:Q,path:R,sourceSha256:E}),v=$E(j.openProject.directory.path,f.path),m=(await A1(Z.application,{path:HK0(Z.application.paths.repositoryRoot,v)},Z.abortSignal,wE)).artifact,y=await F(h4(V,"ffprobe"),new e_(g$(Z.application,V),Z.abortSignal),v);if(y.durationUs===null||y.durationUs<=0||y.hasAudio||y.pixelWidth!==O.canvas.width||y.pixelHeight!==O.canvas.height)throw new N("invalid-data","Generated HTML overlay has invalid duration, dimensions, or audio streams.");let l=lX({mediaDurationUs:y.durationUs,outputDurationUs:H,playbackRate:1,sourceInUs:0,sourceOutUs:void 0}),r={asset:{bytes:f.bytes,mediaType:f.mediaType,path:f.path,provenance:f.provenance,sha256:f.sha256},audioPolicy:{kind:"mute"},kind:"video",playback:{audioEndUs:null,audioStartUs:0,audioStreamIndex:null,endBehavior:"hide",playbackRate:1,streamStartUs:y.videoStartUs,videoStreamIndex:y.videoStreamIndex,...l}},o=a2.parse({...X.layout,coordinateSpace:"output-pixels",intrinsicSize:{height:O.canvas.height,width:O.canvas.width},overlayId:kK0(X,O,m.sha256),range:X.range,source:r}),G0=ZE.parse({artifact:m,browserVersion:P_(V,"html-browser"),createdAt:Z.application.clock.now().toISOString(),executionIntegrity:A,exactInputSha256:S(X),ffmpegVersion:P_(V,"ffmpeg"),ffprobeVersion:P_(V,"ffprobe"),frameCount:C.frameCount,kind:"slopcamera.html-overlay-preparation-receipt",libraryLocks:B,libraryLocksSha256:S(B),operationSha256:S(o),overlayId:o.overlayId,projectGenerationSha256:j.generation.generationSha256,projectId:j.project.projectId,schemaVersion:1}),a=await _$({context:Z,receipt:G0,workspace:L}),c=kF.parse({artifact:m,created:f.created,operation:o,receipt:a});return await K4(Z,{inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",version:1},c),c}finally{await NK0(G,{force:!0,recursive:!0}),await L.dispose()}}},outputSchema:kF,outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",policy:{cache:"exact-run",cancellable:!0,effect:"local-derived-write",maxDurationMs:3600000,maxFanOut:0,maxInputBytes:3145728,maxOutputBytes:2097152,preparation:["project-state","local-media"],resources:[{amount:1,resource:"browser"},{amount:1,resource:"cpu"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"local-io"},{amount:1,resource:"network"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(Z)=>Z.receipt.path,summarize:(Z)=>({fields:{bytes:Z.artifact.bytes,created:Z.created,kind:"html",overlayId:Z.operation.overlayId,receipt:Z.receipt.path,sha256:Z.artifact.sha256},kind:"media.html-overlay"}),version:1}}var kt0=XE();var RK0=["media.ingest","media.html-overlay","media.overlay","media.audio-effects","media.color-grade"],ft0=MK0.enum(RK0);async function Qp(_,$,F,w=new AbortController().signal){switch($){case"media.ingest":return await Ec(_,vX.parse(F),w);case"media.overlay":return await _E(_,xQ.parse(F),w);case"media.html-overlay":return await JE(_,vN.parse(F),w);case"media.audio-effects":return await Ac(_,gX.parse(F),w);case"media.color-grade":return await Uc(_,hX.parse(F),w)}}import{z as xN}from"zod";import{lstat as fK0,realpath as Xp}from"fs/promises";import{isAbsolute as SK0,join as yK0,relative as gK0,sep as hK0}from"path";import{z as k9}from"zod";var TG=4096,VE=4,EK0=16777216,YE=Object.freeze({maximumCount:64,maximumTotalPixels:67108864,maximumTotalSvgBytes:67108864});function Zp(_){let $=1;while($<_)$*=2;return $}function qK0(_){let $=[],F=0,w=[],Q=0,Z=0,J=0,X=0,V=()=>{if(w.length===0)return;let Y=Zp(Z+J),j=Zp(X),H=j*Y;if($.length>=YE.maximumCount||F+H>YE.maximumTotalPixels)throw RangeError("Generated caption sprites exceed the cumulative raster resource bound.");$.push({cards:w,height:Y,width:j}),F+=H,w=[],Q=0,Z=0,J=0,X=0};for(let Y of _){let{intrinsicHeight:j,intrinsicWidth:H}=Y.rendered;if(H>TG||j>TG)throw RangeError("A social caption card exceeds the sprite dimension bound.");if(Q>0&&Q+H>TG)Q=0,Z+=J+VE,J=0;if(Z>0&&Z+j>TG)V();w.push({...Y,x:Q,y:Z}),Q+=H+VE,J=Math.max(J,j),X=Math.max(X,Q-VE)}return V(),$}function bK0(_){let $=_.indexOf(">");if(!_.startsWith("<svg ")||$<0||!_.endsWith("</svg>"))throw TypeError("Social caption renderer returned an unsupported SVG document.");return _.slice($+1,-6)}function PK0(_){let $=_.cards.map((Q)=>`<g transform="translate(${Q.x} ${Q.y})">${bK0(Q.rendered.svg)}</g>`).join(""),F=[`<svg xmlns="http://www.w3.org/2000/svg" width="${_.width}" height="${_.height}" viewBox="0 0 ${_.width} ${_.height}" fill="none">`,$,`</svg>
1536
+ }`);return is($,"return securityViolations;","return securityViolations + (sparkWorkerFailure === null ? 0 : 1);")}var nR=hQ.string().regex(/^[a-f0-9]{64}$/u),rW0=hQ.strictObject({key:hQ.string().min(1).max(512),sha256:nR}),TF=hQ.strictObject({algorithm:hQ.literal("sha256-merkle-v1"),leaves:hQ.array(rW0).min(4).max(256).superRefine((_,$)=>{for(let F=1;F<_.length;F+=1)if(_[F-1].key>=_[F].key)$.addIssue({code:"custom",message:"HTML-overlay integrity leaves must have unique ASCII-sorted keys.",path:[F,"key"]})}),rootSha256:nR,runtimeSha256:nR,schemaVersion:hQ.literal(1)}),u5=Object.freeze({browser:"playwright-chromium",browserVersion:nW0.version,browserContext:Object.freeze({acceptDownloads:!1,colorScheme:"light",locale:"en-US",offline:!0,permissions:Object.freeze([]),reducedMotion:"no-preference",serviceWorkers:"block",timezoneId:"UTC"}),contentSecurityPolicy:Object.freeze(["default-src 'none'","base-uri 'none'","connect-src 'none'","font-src https://slopcamera-overlay.invalid data:","form-action 'none'","frame-src 'none'","img-src https://slopcamera-overlay.invalid data:","media-src https://slopcamera-overlay.invalid data:","object-src 'none'","script-src 'unsafe-inline' https://slopcamera-overlay.invalid","style-src 'unsafe-inline'","worker-src 'none'"]),documentUrl:"https://slopcamera-overlay.invalid/slopcamera-overlay/document",environment:Object.freeze({fixed:Object.freeze({LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",PATH:"/usr/bin:/bin",TZ:"UTC"}),inherited:Object.freeze([]),privateDirectories:Object.freeze(["HOME","TMPDIR"])}),launch:Object.freeze({args:Object.freeze(["--disable-background-networking","--disable-breakpad","--disable-component-update","--disable-default-apps","--disable-domain-reliability","--disable-extensions","--disable-features=Translate,MediaRouter,OptimizationHints","--disable-quic","--disable-sync","--enable-unsafe-swiftshader","--force-webrtc-ip-handling-policy=disable_non_proxied_udp","--metrics-recording-only","--mute-audio","--no-default-browser-check","--no-first-run","--no-proxy-server","--use-angle=swiftshader"]),headless:!0,libraryArgs:Object.freeze({vgpu:Object.freeze(["--enable-unsafe-webgpu","--use-webgpu-adapter=swiftshader"])})}),routing:Object.freeze({allowedOrigin:"https://slopcamera-overlay.invalid",declaredResourcesOnly:!0,remoteNetworkDenied:!0}),runtimeSnapshot:Object.freeze({macosAnchor:"/private/tmp",macosAnchorPolicy:"physical-root-owned-sticky-direct-child",cleanupIdentity:"container-direct-children-and-complete-runtime-manifest",copyBufferBytes:4194304,filesystemGuard:"anchor-basename-and-recursive-parent-watch-with-path-identities",orphanRecovery:"active-to-released-lease-last-atomic-quarantine-double-open-proof",verifiedMacosFilesystemFlags:"user-immutable-recursive"}),schemaVersion:1,screenshot:Object.freeze({omitBackground:!0,scale:"css",type:"png"})}),oW0=Object.freeze({...u5.launch,args:Object.freeze([...u5.launch.args.filter((_)=>_!=="--enable-unsafe-swiftshader"&&_!=="--use-angle=swiftshader"),"--use-angle=metal","--disable-software-rasterizer"])});function iW0(_){if(_===void 0)return u5;let $=U9.parse(_);return Object.freeze({...u5,contentSecurityPolicy:$==="three-spark-webgl2-hardware-v1"?Object.freeze(u5.contentSecurityPolicy.map((F)=>{if(F==="worker-src 'none'")return"worker-src blob:";if(F==="connect-src 'none'")return"connect-src https://slopcamera-overlay.invalid data:";if(F.startsWith("script-src "))return`${F} 'wasm-unsafe-eval'`;return F})):u5.contentSecurityPolicy,executionProfile:$,launch:oW0,gpu:Object.freeze({admission:"matching-active-webgl2-and-cdp-angle-metal-v1",capture:"host-held-native-context-health-before-and-after-every-screenshot",fallback:"reject-software-or-unknown",platform:"darwin",receipt:"bounded-context-device-driver-os-evidence-per-batch"}),schemaVersion:2})}function GG(_,$=[]){let F=iW0(_),Q=B9.parse($).filter((Z)=>Z.transport==="fetch").map((Z)=>`${u5.routing.allowedOrigin}${A8(Z)}`);if(Q.length===0||!F.contentSecurityPolicy.includes("connect-src 'none'"))return F;return Object.freeze({...F,contentSecurityPolicy:Object.freeze(F.contentSecurityPolicy.map((Z)=>Z==="connect-src 'none'"?`connect-src ${Q.join(" ")}`:Z)),schemaVersion:3})}function rR(_,$){if($===void 0)return;U9.parse($);let F=$==="three-webgl2-hardware-v1"?["three"]:["@sparkjsdev/spark","three","three/addons/postprocessing/Pass.js"];if(k([..._].sort())!==k(F))throw Error("Hardware execution profile requires its exact approved scene library set.")}function yN(_){return pW0("sha256").update(_).digest("hex")}function aW0(_,$){return yN(k({domain:"slopcamera.html-overlay-integrity-leaf/v1",key:_,value:$}))}function tW0(_){let $=_.map((F)=>yN(["slopcamera.html-overlay-integrity-node/v1","leaf",F.key,F.sha256].join("\x00")));while($.length>1){let F=[];for(let w=0;w<$.length;w+=2){let Q=$[w],Z=$[w+1]??Q;F.push(yN(["slopcamera.html-overlay-integrity-node/v1","branch",Q,Z].join("\x00")))}$=F}return $[0]}function UF(_,$,F){let w=qQ.parse(_);rR(w.libraries,F);let Q=AF.parse($),Z=w.libraries.map(LF),J=oL(w.libraries),X=DR({canvas:w.canvas,parameters:w.parameters,resources:w.resources,seed:w.seed,timing:w.timing}),V=F==="three-spark-webgl2-hardware-v1"?as(X):X,Y=yN(Buffer.from(V,"utf8")),H=[{key:"authoring-config",value:{canvas:w.canvas,kind:w.kind,parameters:w.parameters,schemaVersion:w.schemaVersion,seed:w.seed,timing:w.timing}},{key:"browser-runtime",value:Q},{key:"renderer-contract",value:GG(F,w.resources)},{key:"document",value:{bytes:Buffer.byteLength(w.html,"utf8"),sha256:yN(Buffer.from(w.html,"utf8"))}},{key:"import-map",value:J},{key:"runtime",value:{bytes:Buffer.byteLength(V,"utf8"),sha256:Y}},...Z.map((W)=>({key:`library:${W.specifier}`,value:W})),...w.resources.map((W)=>({key:`resource:${W.name}`,value:W}))].map((W)=>({key:W.key,sha256:aW0(W.key,W.value)})).sort((W,O)=>W.key<O.key?-1:W.key>O.key?1:0),K=TF.parse({algorithm:"sha256-merkle-v1",leaves:H,rootSha256:tW0(H),runtimeSha256:Y,schemaVersion:1});return Object.freeze({importMap:J,integrity:Object.freeze(K),libraryLocks:Object.freeze(Z),runtimeSource:V})}var DG="slopcamera-3.2.5",gN=["scene.inspect","scene.patch","scene.evaluate","scene.render","slopcamera.studio.run","spatial.project.snapshot","spatial.project.migrate","spatial.project.patch","spatial.project.restore","spatial.project.add-shot","spatial.project.add-candidate","spatial.project.select-candidate","spatial.project.reconcile","project.snapshot","analysis.project-inactivity","analysis.faces","analysis.music","analysis.scenes","analysis.project-auto-zooms","derive.edit-batch","project.commit-edits","derive.follow-faces","edit.create-revision","edit.create-candidate-revision","edit.bind-candidate-revision","edit.freeze-revision","iteration.create-candidate","iteration.create-matrix","iteration.select","project.promote-selection","render.bind-candidate-output","render.project-plan","render.project","render.materialize-selection","media.ingest","media.overlay","media.html-overlay","media.audio-effects","media.color-grade","gateway.image","gateway.video","gateway.speech","gateway.transcription","recording.start","recording.pause","recording.resume","recording.stop","slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.vectorize","slopcamera.image.generate"],hN=["cpu","local-io","ffmpeg","vision","whisper","network","paid-call","project-render","project-publication","output-publication","capture-device","browser"];import{isAbsolute as eW0,relative as oR,resolve as ts}from"path";import{z as w1}from"zod";var _K0=w1.strictObject({path:X0}),vQ=536870912,zG=w1.union([_K0,Kj,N0]),CG=w1.strictObject({endBehavior:w1.enum(["hide","loop","freeze-end"]).default("hide"),playbackRate:w1.number().finite().positive().max(64).default(1),sourceInUs:w1.number().int().safe().nonnegative().default(0),sourceOutUs:w1.number().int().safe().positive().optional()}).prefault({}),iR=w1.strictObject({artifact:N0,id:w1.string().min(1).max(256),provider:w1.enum(["apple-emoji-pack","brand-catalog"]),selector:lB,variant:w1.enum(["color","duotone"])}),$K0=w1.discriminatedUnion("kind",[w1.strictObject({artifact:zG,kind:w1.literal("image")}),w1.strictObject({artifact:zG,kind:w1.literal("svg")}),w1.strictObject({artifact:zG,kind:w1.literal("gif"),playback:CG}),w1.strictObject({artifact:zG,audioPolicy:oW.default({kind:"mute"}),kind:w1.literal("video"),playback:CG}),w1.strictObject({kind:w1.literal("emoji"),provider:w1.enum(["apple-emoji-pack","brand-catalog","auto"]).default("auto"),query:w1.string().min(1).max(256),resolved:iR.optional(),variant:w1.enum(["color","duotone"]).optional()})]),es=w1.discriminatedUnion("kind",[w1.strictObject({artifact:N0,kind:w1.literal("image")}),w1.strictObject({artifact:N0,kind:w1.literal("svg")}),w1.strictObject({artifact:N0,kind:w1.literal("gif"),playback:CG}),w1.strictObject({artifact:N0,audioPolicy:oW,kind:w1.literal("video"),playback:CG}),w1.strictObject({kind:w1.literal("emoji"),provider:w1.enum(["apple-emoji-pack","brand-catalog","auto"]),query:w1.string().min(1).max(256),resolved:iR,variant:w1.enum(["color","duotone"]).optional()})]),aR=w1.strictObject({anchor:uB.default("center"),blendMode:w1.enum(["normal","addition","darken","lighten","multiply","overlay","screen"]).default("normal"),crop:sB.default({kind:"none"}),entrance:rY.default({kind:"none"}),exit:rY.default({kind:"none"}),fit:w1.enum(["contain","cover","fill"]).default("fill"),mask:pB.default({kind:"none"}),motion:nB.default({kind:"none"}),opacity:w1.number().finite().min(0).max(1).default(1),position:A$.default({x:0,y:0}),rotationDegrees:w1.number().finite().min(-3600).max(3600).default(0),scale:w1.number().finite().positive().max(128).default(1),size:cB.default({kind:"intrinsic"}),zIndex:w1.number().int().safe().default(0)}).prefault({}),xQ=w1.strictObject({capabilityBindings:C5.optional(),identityKey:w1.string().min(1).max(128).optional(),layout:aR,project:T1,range:P0,source:$K0}),tR=xQ.extend({source:es}).strict(),kF=w1.strictObject({artifact:N0,created:w1.boolean(),operation:a2,receipt:N0}),eR=w1.strictObject({artifact:N0,createdAt:w1.string().datetime({offset:!0}),exactInputSha256:P,ffprobeVersion:w1.string().min(1).max(256).nullable(),kind:w1.union([w1.literal("slopcamera.local-overlay-preparation-receipt"),w1.literal("studio.local-overlay-preparation-receipt")]),operationSha256:P,overlayId:w1.string().min(1).max(128),projectGenerationSha256:P,projectId:T1,schemaVersion:w1.literal(1)});function FK0(_){let $=_.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test($))return{kind:"id",value:$};if([..._].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test(_))return{kind:"unicode",value:_};return{kind:"name",value:_}}function wK0(_){if(!("bytes"in _))return _;return N0.parse({bytes:_.bytes,path:_.path,sha256:_.sha256})}function _p(_){return _.kind==="image"||_.kind==="gif"||_.kind==="video"?["ffprobe"]:[]}async function QK0(_,$,F,w){let Q=await w(_.paths.repositoryRoot,$.query,$.variant,$.provider),Z=oR(_.paths.repositoryRoot,Q.path),J=await A1(_,{path:Z},F,vQ);if(J.artifact.sha256!==Q.sha256)throw new N("conflict","Resolved emoji bytes disagree with the checked emoji catalog.");let X=iR.parse({artifact:J.artifact,id:Q.id,provider:Q.provider,selector:FK0($.query),variant:Q.variant});if($.resolved!==void 0&&k($.resolved)!==k(X))throw new N("conflict","The checked emoji asset changed after exact node planning.");return es.parse({...$,resolved:X})}async function _E(_,$,F,w={}){let Q=xQ.parse($),Z=_p(Q.source),J=Q.source.kind==="emoji"?QK0(_,Q.source,F,w.resolveEmoji??mX):A1(_,wK0(Q.source.artifact),F,vQ).then((Y)=>({...Q.source,artifact:Y.artifact})),[X,V]=await Promise.all([J,d5(_,Z,Q.capabilityBindings)]);return tR.parse({...Q,capabilityBindings:V,source:X})}function ZK0(_,$){let F=ts(_,$),w=oR(ts(_),F);if(w===""||w.startsWith("..")||eW0(w))throw new N("unsafe-path","Prepared overlay asset escaped its project bundle.");return F}function JK0(_,$,F){let w=dB.parse($),Q={bytes:w.asset.bytes,mediaType:w.asset.mediaType,sha256:w.asset.sha256},Z=w.kind==="image"||w.kind==="svg"?{asset:Q,kind:w.kind}:w.kind==="emoji"?{asset:Q,kind:w.kind,provider:w.provider,selector:w.selector}:{asset:Q,audioPolicy:w.audioPolicy,kind:w.kind,playback:w.playback};return`overlay_${S({domain:"studio.media-overlay-operation/v1",identityKey:_.identityKey??null,intrinsicSize:F,layout:_.layout,project:_.project,range:_.range,source:Z}).slice(0,32)}`}function XK0(_={}){let $=_.ingestFile??XG,F=_.ingestEmoji??VG,w=_.inspectPng??yQ,Q=_.inspectSvg??CF,Z=_.probe??L9,J=_.resolveEmoji??mX;return{inputSchema:xQ,inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",lifecycle:{kind:"local-artifact",execute:async(X,V)=>{n(X.abortSignal);let Y=await _E(X.application,V,X.abortSignal,{resolveEmoji:J}),j=_p(Y.source);await A9(X,X.application,Y.capabilityBindings,j);let H=Y.capabilityBindings??await g6(X.application,j),K=await i1(X.application,Y.project);if(m5(X.expectedProjectGeneration,K.generation),Y.range.endUs>K.plan.timelineDurationUs)throw new N("usage","Overlay range exceeds the project timeline.");let W=Z8(Q8(K.plan),Y.range).reduce((z,C)=>z+C.output.endUs-C.output.startUs,0);if(W<=0)throw new N("conflict","Overlay range has no visible kept output time.");let O=Y.source.kind==="emoji"?void 0:await A1(X.application,Y.source.artifact,X.abortSignal,vQ),L=Y.source.kind==="emoji"?Y.source:void 0,G=L===void 0?void 0:await J(X.application.paths.repositoryRoot,L.query,L.variant,L.provider);if(G!==void 0&&L!==void 0&&(G.id!==L.resolved.id||G.provider!==L.resolved.provider||G.variant!==L.resolved.variant||G.sha256!==L.resolved.artifact.sha256))throw new N("conflict","Resolved emoji changed immediately before preparation.");let D=await W5(X);try{await X.workflow?.beforePublication(),n(X.abortSignal);let z=G===void 0?await $(K.openProject.directory.path,O.absolutePath,Y.source.kind):await F(K.openProject.directory.path,G),C=O?.artifact??L.resolved.artifact;if(z.bytes!==C.bytes||z.sha256!==C.sha256||z.provenance.sourceSha256!==C.sha256)throw new N("conflict","Prepared overlay bytes disagree with the exact bound source.");let A=ZK0(K.openProject.directory.path,z.path),B=(await A1(X.application,{path:oR(X.application.paths.repositoryRoot,A)},X.abortSignal,vQ)).artifact;if(B.bytes!==z.bytes||B.sha256!==z.sha256)throw new N("conflict","Prepared project asset disagrees with its published bytes.");let T=z.mediaType==="image/svg+xml"?{...await Q(A),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:Y.source.kind==="emoji"?{...await w(A),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await Z(h4(H,"ffprobe"),new e_(g$(X.application,H),X.abortSignal),A),M={height:"pixelHeight"in T?T.pixelHeight:T.height,width:"pixelWidth"in T?T.pixelWidth:T.width},R={bytes:z.bytes,mediaType:z.mediaType,path:z.path,provenance:z.provenance,sha256:z.sha256},g;if(Y.source.kind==="image"||Y.source.kind==="svg")g={asset:R,kind:Y.source.kind};else if(Y.source.kind==="emoji")g={asset:R,kind:"emoji",provider:Y.source.resolved.provider,selector:Y.source.resolved.selector};else{if(T.durationUs===null||T.durationUs<=0)throw new N("invalid-data","Animated overlay media must report a positive duration.");let m=lX({mediaDurationUs:T.durationUs,outputDurationUs:W,playbackRate:Y.source.playback.playbackRate,sourceInUs:Y.source.playback.sourceInUs,sourceOutUs:Y.source.playback.sourceOutUs}),y={audioEndUs:T.audioEndUs,audioStartUs:T.audioStartUs,audioStreamIndex:T.audioStreamIndex,endBehavior:Y.source.playback.endBehavior,playbackRate:Y.source.playback.playbackRate,streamStartUs:T.videoStartUs,videoStreamIndex:T.videoStreamIndex,...m};if(Y.source.kind==="gif")g={asset:R,audioPolicy:{kind:"mute"},kind:"gif",playback:y};else{if(Y.source.audioPolicy.kind!=="mute"&&!T.hasAudio)throw new N("conflict","The selected video overlay audio policy requires an audio stream.");g={asset:R,audioPolicy:Y.source.audioPolicy,kind:"video",playback:y}}}let U=a2.parse({...Y.layout,coordinateSpace:"output-pixels",intrinsicSize:M,overlayId:JK0(Y,g,M),range:Y.range,source:g}),E=eR.parse({artifact:B,createdAt:X.application.clock.now().toISOString(),exactInputSha256:S(Y),ffprobeVersion:j.length===0?null:P_(H,"ffprobe"),kind:"slopcamera.local-overlay-preparation-receipt",operationSha256:S(U),overlayId:U.overlayId,projectGenerationSha256:K.generation.generationSha256,projectId:K.project.projectId,schemaVersion:1}),f=await _$({context:X,receipt:E,workspace:D}),v=kF.parse({artifact:B,created:z.created,operation:U,receipt:f});return await K4(X,{inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",outputSchemaId:"slopcamera.operation.media.overlay.output/v1",version:1},v),v}finally{await D.dispose()}}},outputSchema:kF,outputSchemaId:"slopcamera.operation.media.overlay.output/v1",policy:{cache:"exact-run",cancellable:!0,effect:"local-derived-write",maxDurationMs:3600000,maxFanOut:0,maxInputBytes:262144,maxOutputBytes:2097152,preparation:["project-state","local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(X)=>X.receipt.path,summarize:(X)=>({fields:{bytes:X.artifact.bytes,created:X.created,kind:X.operation.source.kind,overlayId:X.operation.overlayId,receipt:X.receipt.path,sha256:X.artifact.sha256},kind:"media.overlay"}),version:1}}var $p=XK0();var AG=2097152,BG=134217728,wE=536870912,FE=["ffmpeg","ffprobe","html-browser"],WK0=E2.union([aL,E2.strictObject({path:X0}),N0]),KK0=E2.union([aL,N0]),OK0=E2.union([Q_,Kj]),LK0=v6.omit({bytes:!0,sha256:!0}).extend({artifact:OK0}).strict(),GK0=v6.extend({artifact:N0}).strict(),vN=E2.strictObject({canvas:EQ,capabilityBindings:C5.optional(),document:WK0,identityKey:E2.string().min(1).max(128).optional(),layout:aR,libraries:OF.default([]),parameters:xX.default({}),project:T1,range:P0,resources:E2.array(LK0).max(64).default([]),seed:E2.number().int().min(0).max(4294967295).default(0),timing:GF}),QE=vN.omit({document:!0,resources:!0}).extend({document:KK0,resources:E2.array(GK0).max(64)}).strict(),ZE=E2.strictObject({artifact:N0,browserVersion:E2.string().min(1).max(512),createdAt:E2.string().datetime({offset:!0}),executionIntegrity:TF.optional(),exactInputSha256:P,ffmpegVersion:E2.string().min(1).max(512),ffprobeVersion:E2.string().min(1).max(512),frameCount:E2.number().int().safe().positive(),kind:E2.union([E2.literal("slopcamera.html-overlay-preparation-receipt"),E2.literal("studio.html-overlay-preparation-receipt")]),libraryLocks:NR,libraryLocksSha256:P,operationSha256:P,overlayId:E2.string().min(1).max(128),projectGenerationSha256:P,projectId:T1,schemaVersion:E2.literal(1)}),wp=kF;function DK0(_){if(!("mediaType"in _.artifact))return _.artifact;if(_.artifact.mediaType!==_.mediaType)throw new N("invalid-data",`HTML overlay resource ${_.name} declares ${_.mediaType} but its generated artifact is ${_.artifact.mediaType}.`);return N0.parse({bytes:_.artifact.bytes,path:_.artifact.path,sha256:_.artifact.sha256})}async function zK0(_,$,F){if("html"in $)return $;return(await A1(_,$,F,AG)).artifact}function CK0(_,$){return Z8(Q8(_),$).reduce((F,w)=>F+w.output.endUs-w.output.startUs,0)}async function JE(_,$,F){let w=vN.parse($),[Q,Z,J]=await Promise.all([zK0(_,w.document,F),Promise.all(w.resources.map(async(Y)=>({...Y,artifact:(await A1(_,DK0(Y),F,BG)).artifact}))),d5(_,FE,w.capabilityBindings)]),X=B9.parse(Z.map(({artifact:Y,...j})=>({...j,bytes:Y.bytes,sha256:Y.sha256}))),V=new Map(Z.map((Y)=>[Y.name,Y.artifact]));return QE.parse({...w,capabilityBindings:J,document:Q,resources:X.map((Y)=>({...Y,artifact:V.get(Y.name)}))})}function AK0(_){let $;try{$=new TextDecoder("utf-8",{fatal:!0}).decode(_)}catch{throw new N("invalid-data","The HTML overlay document must be valid UTF-8.")}if($.trim()==="")throw new N("invalid-data","The HTML overlay document is empty.");return $}async function BK0(_,$){let F=await jK0(_,Fp.O_RDONLY|(Fp.O_NOFOLLOW??0));try{let w=await F.stat();if(!w.isFile()||w.size<=0)throw new N("invalid-data","Rendered HTML overlay is empty.");let Q=VK0("sha256"),Z=Buffer.allocUnsafe(1048576),J=0;while(J<w.size){n($);let V=await F.read(Z,0,Math.min(Z.byteLength,w.size-J),J);if(V.bytesRead===0)break;Q.update(Z.subarray(0,V.bytesRead)),J+=V.bytesRead}let X=await F.stat();if(J!==w.size||X.dev!==w.dev||X.ino!==w.ino||X.size!==w.size||X.mtimeMs!==w.mtimeMs||X.ctimeMs!==w.ctimeMs)throw new N("conflict","Rendered HTML overlay changed while it was being verified.");return Q.digest("hex")}finally{await F.close()}}var TK0=E2.object({streams:E2.array(E2.object({codec_name:E2.string(),height:E2.number().int().positive(),pix_fmt:E2.string(),width:E2.number().int().positive()})).min(1)});async function UK0(_,$,F,w,Q){let Z=await new e_(g$(_,$),Q).run([h4($,"ffprobe"),"-v","error","-select_streams","v:0","-show_entries","stream=codec_name,pix_fmt,width,height","-of","json",F],{maxOutputBytes:65536,stdin:"ignore",timeoutMs:30000});if(Z.exitCode!==0)throw new N("invalid-data","Rendered HTML overlay could not be inspected as an alpha video.");let J;try{J=JSON.parse(Z.stdout)}catch{throw new N("invalid-data","Rendered HTML overlay inspection returned invalid JSON.")}let X=TK0.parse(J).streams[0];if(X.codec_name!=="qtrle"||X.pix_fmt!=="argb"||X.width!==w.width||X.height!==w.height)throw new N("invalid-data","Rendered HTML overlay must be a canvas-sized qtrle/argb alpha video.",{stream:X})}function kK0(_,$,F){return`overlay_${S({assetSha256:F,authoring:$,domain:"studio.media-html-overlay-operation/v1",identityKey:_.identityKey??null,layout:_.layout,project:_.project,range:_.range}).slice(0,32)}`}function XE(_={}){let $=_.ingest??gs,F=_.probe??L9,w=_.bindBrowserRuntime??BF,Q=_.toolVersion??DG;return{inputSchema:vN,inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",lifecycle:{kind:"local-artifact",execute:async(Z,J)=>{n(Z.abortSignal);let X=await JE(Z.application,J,Z.abortSignal);await A9(Z,Z.application,X.capabilityBindings,FE);let V=X.capabilityBindings??await g6(Z.application,FE),Y=Z.application.htmlOverlayRenderer;if(Y===void 0)throw new N("unavailable","This Slopcamera host does not provide an HTML-overlay browser renderer.");let j=await i1(Z.application,X.project);if(m5(Z.expectedProjectGeneration,j.generation),X.range.endUs>j.plan.timelineDurationUs)throw new N("usage","HTML overlay range exceeds the project timeline.");let H=CK0(j.plan,X.range);if(H<=0)throw new N("conflict","HTML overlay range has no visible kept output time.");if(X.timing.durationUs!==H)throw new N("conflict","HTML overlay timing duration must equal the range's visible output duration.",{actualDurationUs:X.timing.durationUs,expectedDurationUs:H});let[K,W]=await Promise.all(["html"in X.document?Promise.resolve(X.document.html):I4(Z.application,X.document,Z.abortSignal,AG).then((D)=>AK0(D.data)),Promise.all(X.resources.map(async(D)=>({...D,absolutePath:(await A1(Z.application,D.artifact,Z.abortSignal,BG)).absolutePath})))]),O=qQ.parse({canvas:X.canvas,html:K,kind:"slopcamera.html-overlay",libraries:X.libraries,parameters:X.parameters,resources:W.map((D)=>({bytes:D.bytes,mediaType:D.mediaType,name:D.name,sha256:D.sha256,...D.transport===void 0?{}:{transport:D.transport},urlPath:D.urlPath})),schemaVersion:1,seed:X.seed,timing:X.timing}),L=await W5(Z),G=await YK0($E(L.path,"html-overlay-"));try{let D=await w(w$(V,"html-browser"),Z.abortSignal),z=UF(O,D).integrity,C=await Y.renderFrames({authoring:O,browserRuntime:D,outputDirectory:G,resources:W},Z.abortSignal),A=TF.parse(C.executionIntegrity);if(S(A)!==S(z))throw new N("conflict","HTML-overlay renderer returned integrity evidence that does not match the planned browser execution.");let B=jR.parse(C.libraryLocks),T=O.libraries.map(LF);if(S(B)!==S(T))throw new N("conflict","HTML-overlay renderer returned library locks that do not exactly match the authoring selection.");let M=B8(O.timing);if(C.frameCount!==M)throw new N("conflict","HTML-overlay renderer returned an unexpected frame count.");let R=$E(G,"overlay.mov"),g=[h4(V,"ffmpeg"),"-hide_banner","-loglevel","error","-nostdin","-n","-framerate",String(O.timing.fps),"-start_number","0","-i",C.framePattern,"-frames:v",String(C.frameCount),"-an","-c:v","qtrle","-pix_fmt","argb","-movflags","+faststart",R],U=await new e_(g$(Z.application,V),Z.abortSignal).run(g,{cwd:G,maxOutputBytes:1048576,stdin:"ignore",timeoutMs:3600000});if(U.exitCode!==0)throw new N("invalid-data",`FFmpeg could not encode the HTML overlay: ${U.stderr.slice(0,2000)}`);await UK0(Z.application,V,R,O.canvas,Z.abortSignal);let E=await BK0(R,Z.abortSignal);await Z.workflow?.beforePublication(),n(Z.abortSignal);let f=await $(j.openProject.directory.path,{command:g,generator:"slopcamera-html-overlay",generatorVersion:Q,path:R,sourceSha256:E}),v=$E(j.openProject.directory.path,f.path),m=(await A1(Z.application,{path:HK0(Z.application.paths.repositoryRoot,v)},Z.abortSignal,wE)).artifact,y=await F(h4(V,"ffprobe"),new e_(g$(Z.application,V),Z.abortSignal),v);if(y.durationUs===null||y.durationUs<=0||y.hasAudio||y.pixelWidth!==O.canvas.width||y.pixelHeight!==O.canvas.height)throw new N("invalid-data","Generated HTML overlay has invalid duration, dimensions, or audio streams.");let l=lX({mediaDurationUs:y.durationUs,outputDurationUs:H,playbackRate:1,sourceInUs:0,sourceOutUs:void 0}),r={asset:{bytes:f.bytes,mediaType:f.mediaType,path:f.path,provenance:f.provenance,sha256:f.sha256},audioPolicy:{kind:"mute"},kind:"video",playback:{audioEndUs:null,audioStartUs:0,audioStreamIndex:null,endBehavior:"hide",playbackRate:1,streamStartUs:y.videoStartUs,videoStreamIndex:y.videoStreamIndex,...l}},o=a2.parse({...X.layout,coordinateSpace:"output-pixels",intrinsicSize:{height:O.canvas.height,width:O.canvas.width},overlayId:kK0(X,O,m.sha256),range:X.range,source:r}),G0=ZE.parse({artifact:m,browserVersion:P_(V,"html-browser"),createdAt:Z.application.clock.now().toISOString(),executionIntegrity:A,exactInputSha256:S(X),ffmpegVersion:P_(V,"ffmpeg"),ffprobeVersion:P_(V,"ffprobe"),frameCount:C.frameCount,kind:"slopcamera.html-overlay-preparation-receipt",libraryLocks:B,libraryLocksSha256:S(B),operationSha256:S(o),overlayId:o.overlayId,projectGenerationSha256:j.generation.generationSha256,projectId:j.project.projectId,schemaVersion:1}),a=await _$({context:Z,receipt:G0,workspace:L}),c=kF.parse({artifact:m,created:f.created,operation:o,receipt:a});return await K4(Z,{inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",version:1},c),c}finally{await NK0(G,{force:!0,recursive:!0}),await L.dispose()}}},outputSchema:kF,outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",policy:{cache:"exact-run",cancellable:!0,effect:"local-derived-write",maxDurationMs:3600000,maxFanOut:0,maxInputBytes:3145728,maxOutputBytes:2097152,preparation:["project-state","local-media"],resources:[{amount:1,resource:"browser"},{amount:1,resource:"cpu"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"local-io"},{amount:1,resource:"network"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(Z)=>Z.receipt.path,summarize:(Z)=>({fields:{bytes:Z.artifact.bytes,created:Z.created,kind:"html",overlayId:Z.operation.overlayId,receipt:Z.receipt.path,sha256:Z.artifact.sha256},kind:"media.html-overlay"}),version:1}}var kt0=XE();var RK0=["media.ingest","media.html-overlay","media.overlay","media.audio-effects","media.color-grade"],ft0=MK0.enum(RK0);async function Qp(_,$,F,w=new AbortController().signal){switch($){case"media.ingest":return await Ec(_,vX.parse(F),w);case"media.overlay":return await _E(_,xQ.parse(F),w);case"media.html-overlay":return await JE(_,vN.parse(F),w);case"media.audio-effects":return await Ac(_,gX.parse(F),w);case"media.color-grade":return await Uc(_,hX.parse(F),w)}}import{z as xN}from"zod";import{lstat as fK0,realpath as Xp}from"fs/promises";import{isAbsolute as SK0,join as yK0,relative as gK0,sep as hK0}from"path";import{z as k9}from"zod";var TG=4096,VE=4,EK0=16777216,YE=Object.freeze({maximumCount:64,maximumTotalPixels:67108864,maximumTotalSvgBytes:67108864});function Zp(_){let $=1;while($<_)$*=2;return $}function qK0(_){let $=[],F=0,w=[],Q=0,Z=0,J=0,X=0,V=()=>{if(w.length===0)return;let Y=Zp(Z+J),j=Zp(X),H=j*Y;if($.length>=YE.maximumCount||F+H>YE.maximumTotalPixels)throw RangeError("Generated caption sprites exceed the cumulative raster resource bound.");$.push({cards:w,height:Y,width:j}),F+=H,w=[],Q=0,Z=0,J=0,X=0};for(let Y of _){let{intrinsicHeight:j,intrinsicWidth:H}=Y.rendered;if(H>TG||j>TG)throw RangeError("A social caption card exceeds the sprite dimension bound.");if(Q>0&&Q+H>TG)Q=0,Z+=J+VE,J=0;if(Z>0&&Z+j>TG)V();w.push({...Y,x:Q,y:Z}),Q+=H+VE,J=Math.max(J,j),X=Math.max(X,Q-VE)}return V(),$}function bK0(_){let $=_.indexOf(">");if(!_.startsWith("<svg ")||$<0||!_.endsWith("</svg>"))throw TypeError("Social caption renderer returned an unsupported SVG document.");return _.slice($+1,-6)}function PK0(_){let $=_.cards.map((Q)=>`<g transform="translate(${Q.x} ${Q.y})">${bK0(Q.rendered.svg)}</g>`).join(""),F=[`<svg xmlns="http://www.w3.org/2000/svg" width="${_.width}" height="${_.height}" viewBox="0 0 ${_.width} ${_.height}" fill="none">`,$,`</svg>
1537
1537
  `].join(""),w=Buffer.byteLength(F,"utf8");if(w>EK0)throw RangeError("A generated caption sprite exceeds the 16 MiB SVG bound.");return{bytes:w,contents:F}}function IK0(_){let $=_.overlays.reduce((F,w)=>Math.max(F,w.operation.zIndex),-1);if($>=Number.MAX_SAFE_INTEGER)throw RangeError("Existing overlay z-index leaves no safe caption layer.");return $+1}function Jp(_){let $=r3(_.plan),F=P.parse(_.sourceSha256),w=jT.parse(_.style);if(_.cues.length===0)throw TypeError("Captioned render planning requires at least one visible cue.");let Q=_.cues.map((H)=>({cue:H,rendered:Im(H,$.output)})),Z=IK0($),J=[],X=[],V=0;for(let[H,K]of qK0(Q).entries()){let{bytes:W,contents:O}=PK0(K),L=t(O);if(V+=W,V>YE.maximumTotalSvgBytes)throw RangeError("Generated caption sprites exceed the cumulative SVG byte bound.");let G=`renders/caption-assets/${L}.svg`,D=`overlay_caption_${S({domain:"slopcamera.social-caption-sprite/v1",sha256:L,sourceSha256:F,spriteIndex:H,style:w}).slice(0,32)}`,z={asset:{bytes:W,mediaType:"image/svg+xml",path:G,provenance:{command:["slopcamera","caption",w],generator:"slopcamera-social-caption-sprite",generatorVersion:"1",kind:"generated",sourceSha256:F},sha256:L},kind:"svg"};J.push({contents:O,path:G,sha256:L});for(let C of K.cards){let A={bottom:(K.height-C.y-C.rendered.intrinsicHeight)/K.height,kind:"normalized-insets",left:C.x/K.width,right:(K.width-C.x-C.rendered.intrinsicWidth)/K.width,top:C.y/K.height},B=a2.parse({anchor:"bottom",crop:A,entrance:{kind:"none"},exit:{kind:"none"},intrinsicSize:{height:K.height,width:K.width},opacity:1,overlayId:D,position:{x:0,y:-C.rendered.bottomSafeMargin},range:C.cue.projectRange,rotationDegrees:0,scale:1,size:{height:C.rendered.intrinsicHeight,kind:"pixels",width:C.rendered.intrinsicWidth},source:z,zIndex:Z});X.push({operation:B,outputRange:C.cue.outputRange,playbackOffsetUs:0,projectRange:C.cue.projectRange,visibleDurationUs:C.cue.outputRange.endUs-C.cue.outputRange.startUs})}}let Y=i$.parse({...$,overlays:[...$.overlays,...X],planSha256:"0".repeat(64)}),j=r3(i$.parse({...Y,planSha256:Ak(Y)}));return{artifacts:J,plan:j}}var vK0=268435456,Vp=k9.strictObject({background:k9.string().regex(/^#[0-9a-fA-F]{8}$/u).optional(),frameRate:k9.number().finite().positive().max(240).optional()}),xK0=Vp.extend({captions:TJ}).strict(),Yp=k9.strictObject({analysisId:TJ.shape.analysisId,analysisPath:X0,analysisSha256:P,assetId:t5,placementId:M1,placementSyncSha256:P,streamId:V4,subjectIntegritySha256:P,wordCount:k9.number().int().safe().positive().max(1e6)}),HE=k9.strictObject({eventsSha256:P,manifestSha256:P,placementId:M1,recordingId:v2}),jE=k9.strictObject({metadataBindings:k9.array(HE).max(256).optional(),revision:GM,settings:Vp.optional()}).superRefine((_,$)=>{if(_.metadataBindings===void 0)return;for(let F=0;F<_.metadataBindings.length;F+=1){let w=_.metadataBindings[F],Q=_.metadataBindings[F-1];if(Q!==void 0&&Q.placementId.localeCompare(w.placementId)>=0)$.addIssue({code:"custom",message:"Render metadata bindings must have unique sorted placement IDs.",path:["metadataBindings",F,"placementId"]})}}),NE=k9.strictObject({captionBinding:Yp.optional(),metadataBindings:k9.array(HE).max(256).optional(),revision:GM,settings:xK0}).superRefine((_,$)=>{if(_.metadataBindings===void 0)return;for(let F=0;F<_.metadataBindings.length;F+=1){let w=_.metadataBindings[F],Q=_.metadataBindings[F-1];if(Q!==void 0&&Q.placementId.localeCompare(w.placementId)>=0)$.addIssue({code:"custom",message:"Render metadata bindings must have unique sorted placement IDs.",path:["metadataBindings",F,"placementId"]})}}),jp=D5;function mK0(_){return S({..._,domain:"slopcamera.social-caption-source/v1"})}function lK0(_,$){let F=gK0(_,$);return F===""||F!==".."&&!F.startsWith(`..${hK0}`)&&!SK0(F)}async function uX(_,$){let F;try{F=await Xp(_.paths.projectRoot)}catch{throw new N("not-found","The project root does not exist.")}let w=yK0(F,$),Q;try{Q=await fK0(w)}catch{throw new N("not-found",`Project does not exist: ${$}`)}if(Q.isSymbolicLink()||!Q.isDirectory())throw new N("unsafe-path",`Project must be a physical directory: ${$}`);let Z=await Xp(w);if(!lK0(F,Z)||Z===F)throw new N("unsafe-path",`Project directory escapes the configured project root: ${$}`);return Z}function dK0(_){return Z$.parse({artifact:_.artifact,baseGeneration:_.baseGeneration,kind:_.kind,outputGeometrySha256:_.outputGeometrySha256,pixelHeight:_.pixelHeight,pixelWidth:_.pixelWidth,planId:_.planId,projectEditPlanSha256:_.projectEditPlanSha256,projectId:_.projectId,projectSha256:_.projectSha256,projectStructureSha256:_.projectStructureSha256,revisionSha256:_.revisionSha256,schemaVersion:_.schemaVersion})}function WE(_,$){try{return JSON.parse(_)}catch{throw new N("invalid-data",`${$} is not valid JSON.`)}}function KE(_){return new TextEncoder().encode(_).byteLength}async function UG(_,$){let F=dK0($),w=await uX(_,F.projectId),Q=L0(w),Z=await Q.readText(F.artifact.path);if(KE(Z)!==F.artifact.bytes||t(Z)!==F.artifact.sha256)throw new N("conflict","Immutable project edit revision artifact failed its byte and SHA-256 identity.");let J=j_.parse(WE(Z,"Project edit revision artifact"));if(Z!==`${k(J)}
1538
1538
  `)throw new N("conflict","Immutable project edit revision artifact is not its canonical document.");if(J.project.projectId!==F.projectId||J.projectEditPlan.planId!==F.planId||J.projectSha256!==F.projectSha256||J.projectEditPlanSha256!==F.projectEditPlanSha256||J.revisionSha256!==F.revisionSha256||b1(J.project)!==F.projectStructureSha256)throw new N("conflict","Immutable project edit revision reference does not match its frozen documents.");return{directory:w,document:J,fileSystem:Q,reference:F}}function Np(_,$,F){return{..._?.background===void 0?{}:{background:_.background},..._?.frameRate===void 0?{}:{frameRate:_.frameRate},metadata:F,pixelHeight:$.pixelHeight,pixelWidth:$.pixelWidth}}async function kG(_,$,F){let w=new Set(F.zooms.map((Z)=>Z.placementId));if((F.effects.clicks.enabled||F.effects.cursor.enabled||F.effects.keystrokes.enabled||F.effects.typedText.enabled)&&F.effects.metadataPlacementId!==null)w.add(F.effects.metadataPlacementId);let Q=await Promise.all([...w].sort().map(async(Z)=>{let J=$.placements.find((j)=>j.placementId===Z);if(J===void 0)throw new N("not-found",`Unknown project metadata placement: ${Z}`);let X=$.assets.find((j)=>j.assetId===J.assetId);if(X?.source.kind!=="recording")throw new N("conflict",`Placement ${J.placementId} is not backed by a Slopcamera recording with window and input metadata.`);let V=await g4(_,X.source.recordingId),Y=await M6(V);return{binding:HE.parse({eventsSha256:S(Y),manifestSha256:S(V.manifest),placementId:J.placementId,recordingId:X.source.recordingId}),context:{events:Y,manifest:V.manifest,placementId:J.placementId}}}));return{bindings:Q.map((Z)=>Z.binding),contexts:Q.map((Z)=>Z.context)}}async function Hp(_,$){let F=TJ.parse($),w=_.document.project,Q=w.analyses.find((K)=>K.kind==="speech"&&K.analysisId===F.analysisId);if(Q===void 0||Q.kind!=="speech")throw new N("not-found",`Unknown project speech analysis: ${F.analysisId}`);let Z=w.placements.find((K)=>K.placementId===F.placementId);if(Z===void 0)throw new N("not-found",`Unknown caption placement: ${F.placementId}`);if(!Z.enabled||Z.assetId!==Q.assetId)throw new N("conflict","Caption placement must be enabled and contain the analyzed audio asset.");if(Z.audio.find((K)=>K.streamId===Q.streamId)?.presentation.enabled!==!0)throw new N("conflict","Caption source audio must be enabled and audible on the selected placement.");let X=w.assets.find((K)=>K.assetId===Q.assetId),V=X?.streams.find((K)=>K.streamId===Q.streamId);if(X===void 0||V?.kind!=="audio")throw new N("conflict","Caption speech analysis no longer identifies a project audio stream.");let Y,j;try{Y=await _.fileSystem.readText(Q.path),j=S5.parse(WE(Y,"Speech analysis artifact"))}catch(K){if(K instanceof N)throw K;throw new N("invalid-data",`Speech analysis ${Q.analysisId} is unreadable or invalid.`)}if(Y!==`${k(j)}
1539
1539
  `||t(Y)!==Q.sha256||j.analysisId!==Q.analysisId||j.subject.assetId!==Q.assetId||j.subject.streamId!==Q.streamId||j.durationUs!==X.durationUs)throw new N("conflict",`Speech analysis ${Q.analysisId} is stale or failed its exact identity check.`);let H=S({assetDurationUs:X.durationUs,stream:V});if(j.subject.integritySha256!==H)throw new N("conflict",`Speech analysis ${Q.analysisId} no longer matches its audio stream.`);if(j.result.status!=="transcribed"||j.result.words.length===0)throw new N("unsupported-plan","Caption export requires a speech analysis with timed words.");if(Q.wordCount!==j.result.words.length||Q.fillerCount!==j.result.fillers.length)throw new N("invalid-data",`Speech analysis reference ${Q.analysisId} disagrees with its artifact counts.`);return{analysis:j,binding:Yp.parse({analysisId:Q.analysisId,analysisPath:Q.path,analysisSha256:Q.sha256,assetId:Q.assetId,placementId:Z.placementId,placementSyncSha256:Y4(Z),streamId:Q.streamId,subjectIntegritySha256:H,wordCount:j.result.words.length})}}async function MG(_,$){let F=jE.parse($),w=await UG(_,F.revision),Q=await kG(_.paths.artifactRoot,w.document.project,w.document.projectEditPlan);return jE.parse({...F,metadataBindings:Q.bindings})}async function Wp(_,$){let F=NE.parse($),w=await UG(_,F.revision),[Q,Z]=await Promise.all([kG(_.paths.artifactRoot,w.document.project,w.document.projectEditPlan),Hp(w,F.settings.captions)]);return NE.parse({...F,captionBinding:Z.binding,metadataBindings:Q.bindings})}function uK0(_,$,F){return DN.parse({kind:"slopcamera.project-render-plan-document",outputGeometrySha256:F.outputGeometrySha256,plan:r3(_),projectEditPlanSha256:$.projectEditPlanSha256,projectSha256:$.projectSha256,renderPlanSha256:S(_),revisionSha256:$.revisionSha256,schemaVersion:1})}async function m6(_,$){let F=D5.parse($),w=await uX(_,F.projectId),Q=L0(w),Z=await Q.readText(F.artifact.path);if(KE(Z)!==F.artifact.bytes||t(Z)!==F.artifact.sha256)throw new N("conflict","Immutable project render plan artifact failed its byte and SHA-256 identity.");let J=DN.parse(WE(Z,"Project render plan artifact"));if(Z!==`${k(J)}
@@ -1772,7 +1772,7 @@ ${_.map(($)=>`- ${$}`).join(`
1772
1772
  `))}function FB0(_,$,F){ba(_);let w=$.find((V)=>sb(V,_));if(w===void 0||w.document.phase!==_.document.phase||mF(w.document)!==mF(_.document))throw new c1("OWNERSHIP_LOST","Host-resource lease marker no longer matches its descriptor.");let Q=BigInt(_.document.ticket);if($.some((V)=>V.document.phase==="W"&&BigInt(V.document.ticket)<Q&&pb(V.document.claims,_.document.claims)))return{admitted:!1,queueState:Va(_,$)};let J=$.filter((V)=>V.document.phase==="A");if(!Pa(F,J,_.document.claims))return{admitted:!1,queueState:Va(_,$)};let X={..._.document,phase:"A"};return ub(_.descriptor,mF(X)),_.document=X,{admitted:!0,queueState:""}}function wB0(_,$){return sb(_,$)&&_.document.phase==="A"&&$.document.phase==="A"&&mF(_.document)===mF($.document)}async function QB0(_,$,F,w,Q,Z){let J,X=0;for(;;){let V=await oD($,F.pollIntervalMilliseconds,w,Q,()=>{let Y=Z();rD(Y,F.profile);let j=cb($,F.profile,F.profileSha256);return FB0(_,j,F.profile)});if(V.admitted)return;if(V.queueState===J)X+=1;else J=V.queueState,X=0;await Ra(tA0(F.pollIntervalMilliseconds,_.document.ticket,X),w,Q)}}async function ZB0(_,$,F,w){ba(_);let Q=g7.now()+F.waitTimeoutMilliseconds;await oD($,F.pollIntervalMilliseconds,void 0,Q,()=>{let Z=w();if(rD(Z,F.profile),!cb($,F.profile,F.profileSha256).some((X)=>wB0(X,_)))throw new c1("OWNERSHIP_LOST","Host-resource lease is not backed by its exact active kernel lock.")})}async function JB0(_,$,F,w){if(_.released)return;_.released=!0;try{f_(_.descriptor)}catch(Z){if(!x7(Z,"EBADF"))throw Z}let Q=g7.now()+F.waitTimeoutMilliseconds;await oD($,F.pollIntervalMilliseconds,void 0,Q,()=>{let Z=w();if(rD(Z,F.profile),VZ(_.path)===null)return;let J=y9(_.path),X=!1;try{let V=h9(J);if(!y7(_.identity,V))throw new c1("OWNERSHIP_LOST","Host-resource marker inode changed before release.");if(X=I7(J),!X)return;qa(_.path,_.identity)}finally{if(X)try{f7(J)}catch{}f_(J)}})}function XB0(_){if(!cD(process.platform))throw new c1("UNSUPPORTED_PLATFORM","Slopcamera host-resource coordination requires Darwin or Linux.");let $=v7(_.profile??Aa()),F=_.stateRoot??pA0();if(typeof F!=="string"||!yb(F)||F.includes("\x00")||Buffer.byteLength(F,"utf8")>La)throw n1("Host-resource state root must be a bounded absolute path.");return{pollIntervalMilliseconds:GV(_.pollIntervalMilliseconds,Da,1000,"INVALID_PROFILE","Host-resource poll interval"),profile:$,profileSha256:db(S7($)),stateRoot:F,waitTimeoutMilliseconds:GV(_.waitTimeoutMilliseconds,za,d$,"INVALID_PROFILE","Host-resource wait timeout")}}function VB0(_={}){let $=XB0(_),F,w=()=>{if(F===void 0)F=nA0($.stateRoot);return F.path},Q=()=>{return oA0(w(),$.profile)},Z={profile:$.profile,scope:"machine",async withLease(J,X,V={}){let Y=lb(J,$.profile);if(typeof X!=="function")throw new c1("INVALID_CLAIMS","Host-resource lease callback must be a function.");let j=GV(V.waitTimeoutMilliseconds,$.waitTimeoutMilliseconds,d$,"INVALID_CLAIMS","Host-resource lease wait timeout"),H=V.signal,K=g7.now()+j;sD(H,K);let W=w(),O,L=!1,G,D;try{O=await oD(W,$.pollIntervalMilliseconds,H,K,()=>{let A=Q();return rD(A,$.profile),cb(W,$.profile,$.profileSha256),$B0(W,A,Y,$.profileSha256)}),await QB0(O,W,$,H,K,Q);let z=O,C=Object.freeze({claims:Y,inheritedFileDescriptor:z.descriptor,profile:$.profile,ticket:z.document.ticket,assertOwned:async()=>{await ZB0(z,W,$,Q)}});await C.assertOwned();try{G=await X(C),L=!0,await C.assertOwned()}catch(A){D=A}}finally{if(O!==void 0)try{await JB0(O,W,$,Q)}catch(z){if(D===void 0)D=z}}if(!L||D!==void 0)throw D;return G}};return Object.freeze(Z)}var Pb=new Map;function YB0(_={}){let $=v7(_.profile??Aa()),F=GV(_.waitTimeoutMilliseconds,za,d$,"INVALID_PROFILE","Host-resource wait timeout");if(_.pollIntervalMilliseconds!==void 0)GV(_.pollIntervalMilliseconds,Da,1000,"INVALID_PROFILE","Host-resource poll interval");let w=S7($),Q=Pb.get(w);if(Q===void 0){if(Pb.size>=dA0)throw new c1("INVALID_PROFILE","This process already coordinates the maximum number of host-resource profiles.");Q={active:new Map,nextTicket:1n,waiting:[]},Pb.set(w,Q)}let{active:Z,waiting:J}=Q,X=(H)=>{if(H.timeout!==void 0)clearTimeout(H.timeout);if(H.abortListener!==void 0)H.signal?.removeEventListener("abort",H.abortListener)},V=()=>[...Z.values()].map((H)=>({document:{version:1,owner:H.ticket.padStart(32,"0").slice(-32),profileSha256:db(S7($)),ticket:H.ticket,phase:"A",claims:H.claims},identity:{device:0,inode:0},name:H.ticket,path:""})),Y=()=>{for(let H=0;H<J.length;){let K=J[H];if(K===void 0)break;if(J.slice(0,H).some((D)=>pb(D.claims,K.claims))||!Pa($,V(),K.claims)){H+=1;continue}J.splice(H,1),X(K);let O;try{O=Sb(process.platform==="win32"?"NUL":"/dev/null",xF.O_RDONLY)}catch(D){K.settled=!0,K.reject(new c1("UNSAFE_STATE","Process-local host-resource admission could not open its lease descriptor.",D));continue}K.active=!0,Z.set(K.ticket,K),K.descriptor=O;let G=Object.freeze({assertOwned:async()=>{if(K.settled||!K.active||Z.get(K.ticket)!==K||K.descriptor!==O)throw new c1("OWNERSHIP_LOST","Process-local host-resource lease is no longer active.");try{h9(O)}catch(D){throw new c1("OWNERSHIP_LOST","Process-local host-resource descriptor is no longer open.",D)}},claims:K.claims,inheritedFileDescriptor:O,profile:$,ticket:K.ticket});(async()=>{let D=!1,z,C;try{await G.assertOwned(),z=await K.callback(G),await G.assertOwned(),D=!0}catch(A){C=A}finally{K.active=!1,K.settled=!0,Z.delete(K.ticket);try{f_(O)}catch(A){if(C===void 0)C=A}Y()}if(D&&C===void 0)K.resolve(z);else K.reject(C)})()}};return Object.freeze({profile:$,scope:"process",async withLease(H,K,W={}){let O=lb(H,$);if(typeof K!=="function")return Promise.reject(new c1("INVALID_CLAIMS","Host-resource lease callback must be a function."));if(Q.nextTicket>vb)return Promise.reject(n1("Host-resource tickets are exhausted."));let L=GV(W.waitTimeoutMilliseconds,F,d$,"INVALID_CLAIMS","Host-resource lease wait timeout"),G=String(Q.nextTicket);return Q.nextTicket+=1n,await new Promise((D,z)=>{let C={active:!1,callback:K,claims:O,reject:z,resolve:D,settled:!1,signal:W.signal,ticket:G},A=(B)=>{if(C.active||C.settled)return;C.settled=!0;let T=J.indexOf(C);if(T>=0)J.splice(T,1);X(C),z(B),Y()};if(C.abortListener=()=>A(new c1("WAIT_ABORTED","Host-resource admission was cancelled before execution.")),C.timeout=setTimeout(()=>A(new c1("WAIT_TIMEOUT","Host-resource admission exceeded its bounded wait.")),L),C.timeout.unref?.(),W.signal?.addEventListener("abort",C.abortListener,{once:!0}),W.signal?.aborted===!0){C.abortListener();return}J.push(C),Y()})}})}function v9(_={},$=process.platform){if(cD($))return VB0(_);let{profile:F,pollIntervalMilliseconds:w,waitTimeoutMilliseconds:Q}=_;return YB0({...F===void 0?{}:{profile:F},...w===void 0?{}:{pollIntervalMilliseconds:w},...Q===void 0?{}:{waitTimeoutMilliseconds:Q}})}var AV=["slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.vectorize","slopcamera.image.generate"];class K_ extends Error{code;constructor(_,$){super(`[${_}] ${$}`);this.name="SlopcameraOperationError",this.code=_}}var LB0={type:"string",minLength:3,maxLength:256,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*/[a-zA-Z0-9][a-zA-Z0-9._:-]*$"},DV={type:"string",minLength:1,maxLength:4096};function Sa(_){if(typeof _!=="object"||_===null||Object.isFrozen(_))return _;for(let $ of Object.values(_))Sa($);return Object.freeze(_)}var d7=Sa([{code:"slopcamera.diagram.check",title:"Check diagram",description:"Parse and lint a checked Slopcamera diagram source without changing its files.",execution:"local",authentication:"none",destructive:!1,idempotent:!0,inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:DV}},resources:[{resource:"cpu",amount:1},{resource:"local-io",amount:1}]},{code:"slopcamera.diagram.render",title:"Render diagram",description:"Render a checked Slopcamera diagram source to its replaceable light, dark, PNG, SVG, and tldraw artifacts.",execution:"local",authentication:"none",destructive:!0,idempotent:!0,inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:DV,outDirectory:DV,scale:{type:"number",exclusiveMinimum:0,maximum:4}}},resources:[{resource:"cpu",amount:1},{resource:"local-io",amount:1}]},{code:"slopcamera.image.vectorize",title:"Vectorize image",description:"Convert a local caller-owned raster into a bounded inert SVG without authentication or network access.",execution:"local",authentication:"none",destructive:!0,idempotent:!1,inputSchema:{type:"object",additionalProperties:!1,required:["inputPath","outputPath"],properties:{inputPath:DV,outputPath:DV,duotone:{type:"array",minItems:2,maxItems:2,items:{type:"string",pattern:"^#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$"}},alphaCutoff:{type:"integer",minimum:1,maximum:64},timeoutMs:{type:"integer",minimum:1,maximum:300000}}},resources:[{resource:"cpu",amount:1},{resource:"local-io",amount:1}]},{code:"slopcamera.image.generate",title:"Generate image",description:"Generate one bounded image directly through Vercel AI Gateway with an environment credential and no client retry.",execution:"gateway",authentication:"environment",destructive:!0,idempotent:!1,inputSchema:{type:"object",additionalProperties:!1,required:["model","prompt","outputPath"],properties:{model:LB0,prompt:{type:"string",minLength:1,maxLength:HV},outputPath:DV}},resources:[{resource:"local-io",amount:1},{resource:"network",amount:1},{resource:"paid-call",amount:1}],transport:{method:"POST",authority:"https://ai-gateway.vercel.sh/v4/ai",authorization:"bearer",retry:"never"}}]);function q8(_){throw new K_("INVALID_OPERATION_INPUT",_)}function GB0(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function iD(_,$){if(!GB0(_))q8("Operation input must be an object.");let F=Object.keys(_).filter((w)=>!$.includes(w));if(F.length>0)q8(`Unsupported operation input field: ${F[0]}.`);return _}function CV(_,$){if(typeof _!=="string"||_.length<1||_.length>4096||_.includes("\x00"))q8(`${$} must be a non-empty bounded local path.`);return _}function DB0(_){let $=iD(_,["path"]);return{path:CV($.path,"path")}}function zB0(_){let $=iD(_,["path","outDirectory","scale"]),F=$.scale;if(F!==void 0&&(typeof F!=="number"||!Number.isFinite(F)||F<=0||F>4))q8("scale must be greater than zero and no more than 4.");return{path:CV($.path,"path"),...$.outDirectory===void 0?{}:{outDirectory:CV($.outDirectory,"outDirectory")},...F===void 0?{}:{scale:F}}}function CB0(_){let $=iD(_,["inputPath","outputPath","duotone","alphaCutoff","timeoutMs"]),F=CV($.inputPath,"inputPath"),w=CV($.outputPath,"outputPath");if(!w.toLowerCase().endsWith(".svg"))q8("outputPath must end in .svg.");let Q=$.duotone;if(Q!==void 0&&(!Array.isArray(Q)||Q.length!==2||Q.some((X)=>typeof X!=="string"||!/^#[a-f0-9]{3}(?:[a-f0-9]{3})?$/iu.test(X))))q8("duotone must contain exactly two #rgb or #rrggbb colors.");let Z=$.alphaCutoff;if(Z!==void 0&&(!Number.isInteger(Z)||Z<1||Z>64))q8("alphaCutoff must be an integer from 1 through 64.");let J=$.timeoutMs;if(J!==void 0&&(!Number.isInteger(J)||J<1||J>300000))q8("timeoutMs must be an integer from 1 through 300000.");return{inputPath:F,outputPath:w,...Q===void 0?{}:{duotone:Q},...Z===void 0?{}:{alphaCutoff:Z},...J===void 0?{}:{timeoutMs:J}}}function AB0(_){let $=iD(_,["model","prompt","outputPath"]);if(typeof $.model!=="string"||$.model.length>256||!/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/iu.test($.model))q8("model must be a bounded Vercel AI Gateway provider/model id.");if(typeof $.prompt!=="string"||$.prompt.trim().length<1||/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test($.prompt)||Buffer.byteLength($.prompt,"utf8")>HV)q8(`prompt must be non-empty and no more than ${HV} UTF-8 bytes.`);let F=CV($.outputPath,"outputPath");if(!/\.(?:jpe?g|png|webp)$/iu.test(F))q8("outputPath must end in .png, .jpg, .jpeg, or .webp.");return{model:$.model,prompt:$.prompt,outputPath:F}}function b8(_,$){switch(_){case"slopcamera.diagram.check":return DB0($);case"slopcamera.diagram.render":return zB0($);case"slopcamera.image.vectorize":return CB0($);case"slopcamera.image.generate":return AB0($);default:throw new K_("INVALID_OPERATION","Unknown Slopcamera operation code.")}}function ya(_){return AV.includes(_)}function aD(_){let $=d7.find((F)=>F.code===_);if($===void 0)throw new K_("INVALID_OPERATION","Unknown Slopcamera operation code.");return $.resources}function tD(_="",$=d7.length){if(typeof _!=="string"||_.length>200||/[\u0000-\u001f\u007f]/u.test(_)||!Number.isInteger($)||$<1||$>20)throw new K_("INVALID_SEARCH","Search requires a bounded query and a limit from 1 through 20.");let F=_.toLowerCase().split(/\s+/u).filter((w)=>w.length>0);return d7.filter((w)=>{let Q=`${w.code} ${w.title} ${w.description}`.toLowerCase();return F.every((Z)=>Q.includes(Z))}).slice(0,$)}function ga(_,$){let F=[..._.inheritedFileDescriptors??[],$.inheritedFileDescriptor].filter((X,V,Y)=>Y.indexOf(X)===V);if(F.length>16||F.some((X)=>!Number.isSafeInteger(X)||X<0||X>2147483647))throw new K_("INVALID_OPERATION_INPUT","Operation host-resource inheritance exceeds its descriptor bound.");let{hostResourceCoordinator:w,signal:Q,waitTimeoutMilliseconds:Z,...J}=_;return{...J,inheritedFileDescriptors:F}}async function nb(_,$,F={}){return await(F.hostResourceCoordinator??v9()).withLease(aD(_),async(Q)=>{return await Q.assertOwned(),await $(Q)},{...F.signal===void 0?{}:{signal:F.signal},...F.waitTimeoutMilliseconds===void 0?{}:{waitTimeoutMilliseconds:F.waitTimeoutMilliseconds}})}var m7=Object.freeze({icons:W_});async function ha(_){let $=fa(_),F;try{F=JSON.parse(await HB0($,"utf8"))}catch(Q){throw new K_("INVALID_OPERATION_INPUT","Diagram source could not be read as JSON.")}let w=b9(F);for(let Q of w.shapes)if((Q.type==="rect"||Q.type==="ellipse")&&Q.icon!==void 0&&!Object.hasOwn(W_,Q.icon))throw new K_("INVALID_OPERATION_INPUT","Diagram requests an unavailable built-in icon.");return{absolutePath:$,spec:w}}async function l7(_,$){let F=zV(Ia(_),`.${jB0()}.slopcamera-operation.tmp`);try{await OB0(F,$,{flag:"wx"}),await WB0(F,_)}finally{await KB0(F,{force:!0}).catch(()=>{return})}}async function BB0(_){let{spec:$}=await ha(_);return{findings:E8($),configPath:null}}async function TB0(_){let{absolutePath:$,spec:F}=await ha(_.path),w=fa(_.outDirectory??Ia($)),Q=_.scale??2,[Z,J]=await Promise.all([X$(F,"light",m7),X$(F,"dark",m7)]),[X,V]=[M8(Z,m7,Q),M8(J,m7,Q)],Y={spec:$,tldr:zV(w,`${F.name}.tldr`),lightSvg:zV(w,`${F.name}.light.svg`),darkSvg:zV(w,`${F.name}.dark.svg`),lightPng:zV(w,`${F.name}.light.png`),darkPng:zV(w,`${F.name}.dark.png`)};return await NB0(w,{recursive:!0}),await Promise.all([l7(Y.tldr,fF(F,m7)),l7(Y.lightSvg,Z.svg),l7(Y.darkSvg,J.svg),l7(Y.lightPng,X),l7(Y.darkPng,V)]),{artifacts:Y,findings:E8(F),configPath:null}}async function va(_,$,F={}){let w=b8(_,$);switch(_){case"slopcamera.diagram.check":return await BB0(w.path);case"slopcamera.diagram.render":return await TB0(w);case"slopcamera.image.vectorize":{let Q=w,Z=await Q3(Q.inputPath,{outputPath:Q.outputPath,...Q.duotone===void 0?{}:{duotone:Q.duotone},...Q.alphaCutoff===void 0?{}:{alphaCutoff:Q.alphaCutoff},...Q.timeoutMs===void 0?{}:{limits:{maxDurationMs:Q.timeoutMs}},...F.inheritedFileDescriptors===void 0?{}:{inheritedFileDescriptors:F.inheritedFileDescriptors}});if(Z.outputPath===null)throw new K_("INVALID_OPERATION_INPUT","Vectorization did not publish its required output.");return{outputPath:Z.outputPath,receipt:Z.receipt}}case"slopcamera.image.generate":return await KV({...w,...F.signal===void 0?{}:{signal:F.signal}},F);default:throw new K_("INVALID_OPERATION","Unknown Slopcamera operation code.")}}async function jZ(_,$,F,w={}){await F.assertOwned();let Q=new Map;for(let J of F.claims){if(typeof J.resource!=="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(J.resource)||!Number.isSafeInteger(J.amount)||J.amount<1)throw new K_("INVALID_OPERATION","The active host-resource lease contains invalid claims.");let X=(Q.get(J.resource)??0)+J.amount;if(!Number.isSafeInteger(X))throw new K_("INVALID_OPERATION","The active host-resource lease contains invalid claims.");Q.set(J.resource,X)}let Z=aD(_).filter((J)=>(Q.get(J.resource)??0)<J.amount);if(Z.length>0)throw new K_("INVALID_OPERATION",`The active host-resource lease does not cover ${Z.map((J)=>`${J.resource}:${String(J.amount)}`).join(", ")}.`);return await va(_,$,ga(w,F))}async function NZ(_,$,F={}){let w=b8(_,$);return await nb(_,async(Q)=>await va(_,w,ga(F,Q)),F)}import{rename as da,rm as ua,writeFile as PB0}from"fs/promises";import{dirname as IB0,join as BV}from"path";import{open as UB0,mkdir as kB0,realpath as u7,stat as rb}from"fs/promises";import{basename as MB0,dirname as xa,isAbsolute as ma,join as RB0,relative as la,resolve as eD,win32 as EB0}from"path";var x9=1048576;class a1 extends Error{code;constructor(_,$){super($);this.name="WorkspaceBoundaryError",this.code=_}}function $z(_){if(typeof _==="object"&&_!==null&&"code"in _&&typeof _.code==="string")return _.code;return}function _z(_,$){if(_.length===0||_.includes("\x00"))throw new a1("INVALID_PATH","Path must be a non-empty root-relative path.");if(ma(_)||EB0.isAbsolute(_)||/^[A-Za-z]:/.test(_))throw new a1("INVALID_PATH","Absolute paths are not allowed.");let F=_.split(/[\\/]/).filter((w)=>w!==""&&w!==".");if(F.includes(".."))throw new a1("INVALID_PATH","Parent-directory traversal is not allowed.");if(F.length===0){if(!$.allowRoot)throw new a1("INVALID_PATH","Path must identify a file below the root.");return{native:".",portable:"."}}return{native:F.join("/"),portable:F.join("/")}}function qB0(_,$){let F=la(_,$);return F===""||!F.startsWith("..")&&!ma(F)}async function bB0(_){let $;try{$=await UB0(_,"r");let F=await $.stat();if(!F.isFile())throw new a1("SOURCE_NOT_FILE","Diagram source must be a regular file.");if(F.size>x9)throw new a1("SOURCE_TOO_LARGE",`Diagram source exceeds the ${x9}-byte limit.`);let w=Buffer.allocUnsafe(x9+1),Q=0;while(Q<=x9){let Z=await $.read(w,Q,x9+1-Q,null);if(Z.bytesRead===0)break;Q+=Z.bytesRead}if(Q>x9)throw new a1("SOURCE_TOO_LARGE",`Diagram source exceeds the ${x9}-byte limit.`);try{return new TextDecoder("utf-8",{fatal:!0}).decode(w.subarray(0,Q))}catch{throw new a1("SOURCE_ENCODING","Diagram source must contain valid UTF-8.")}}catch(F){if(F instanceof a1)throw F;if($z(F)==="ENOENT")throw new a1("SOURCE_NOT_FOUND","Diagram source does not exist.");throw new a1("FILESYSTEM_ERROR","Diagram source could not be read.")}finally{await $?.close()}}class HZ{rootDirectory;constructor(_){this.rootDirectory=_}static async create(_){let $;try{if($=await u7(eD(_)),!(await rb($)).isDirectory())throw new a1("OUTPUT_NOT_DIRECTORY","MCP root must be a directory.")}catch(F){if(F instanceof a1)throw F;throw new a1("FILESYSTEM_ERROR","MCP root could not be opened.")}return new HZ($)}assertConfined(_){if(!qB0(this.rootDirectory,_))throw new a1("PATH_OUTSIDE_ROOT","Path resolves outside the MCP root.")}toRelativePath(_){this.assertConfined(_);let $=la(this.rootDirectory,_);return $===""?".":$.split("\\").join("/")}async readSource(_){let $=_z(_,{allowRoot:!1}),F=eD(this.rootDirectory,$.native);this.assertConfined(F);let w;try{w=await u7(F)}catch(Q){if($z(Q)==="ENOENT")throw new a1("SOURCE_NOT_FOUND","Diagram source does not exist.");throw new a1("FILESYSTEM_ERROR","Diagram source could not be resolved.")}return this.assertConfined(w),{absolutePath:w,relativePath:this.toRelativePath(w),text:await bB0(w)}}async resolveInputFile(_,$){let F=_z(_,{allowRoot:!1}),w=eD(this.rootDirectory,F.native);this.assertConfined(w);let Q;try{Q=await u7(w),this.assertConfined(Q);let Z=await rb(Q);if(!Z.isFile())throw new a1("SOURCE_NOT_FILE","Input must be a regular file.");if(!Number.isSafeInteger($)||$<1||Z.size>$)throw new a1("SOURCE_TOO_LARGE",`Input exceeds the ${$}-byte limit.`)}catch(Z){if(Z instanceof a1)throw Z;if($z(Z)==="ENOENT")throw new a1("SOURCE_NOT_FOUND","Input does not exist.");throw new a1("FILESYSTEM_ERROR","Input could not be resolved.")}return{absolutePath:Q,relativePath:this.toRelativePath(Q)}}async prepareOutputFile(_){let $=_z(_,{allowRoot:!1}),F=MB0($.native);if(F==="."||F===".."||F.length===0)throw new a1("INVALID_PATH","Output path must identify a file below the root.");let w=await this.prepareOutputDirectory(xa($.native)),Q=RB0(w.absolutePath,F);return this.assertConfined(Q),{absolutePath:Q,relativePath:this.toRelativePath(Q)}}async prepareOutputDirectory(_){let $=_z(_,{allowRoot:!0}),F=eD(this.rootDirectory,$.native);this.assertConfined(F);let w=F;for(;;)try{let Q=await u7(w);this.assertConfined(Q);break}catch(Q){if(Q instanceof a1)throw Q;if($z(Q)!=="ENOENT")throw new a1("FILESYSTEM_ERROR","Output directory could not be resolved.");let Z=xa(w);if(Z===w)throw new a1("PATH_OUTSIDE_ROOT","Output directory resolves outside the MCP root.");w=Z}try{await kB0(F,{recursive:!0});let Q=await u7(F);if(this.assertConfined(Q),!(await rb(Q)).isDirectory())throw new a1("OUTPUT_NOT_DIRECTORY","Output path must be a directory.");return{absolutePath:Q,relativePath:this.toRelativePath(Q)}}catch(Q){if(Q instanceof a1)throw Q;throw new a1("FILESYSTEM_ERROR","Output directory could not be created.")}}}var TV=4,n7=16777216,r7=64,o7=128,oa=40,ob=2,fB0=12,c7=Object.freeze({icons:W_}),ca={type:"object",additionalProperties:!1,required:["code","message","shapeIds"],properties:{code:{type:"string"},message:{type:"string"},shapeIds:{type:"array",items:{type:"string"}}}};function ia(_){if(typeof _!=="object"||_===null||Object.isFrozen(_))return _;for(let $ of Object.values(_))ia($);return Object.freeze(_)}var kV=ia([{name:"check_diagram",title:"Check diagram",description:"Parse and lint one root-relative Slopcamera diagram source without changing files. Uses only built-in icons and themes.",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string",description:"Root-relative path to a diagram JSON source (1 MiB maximum)."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","findings","summary"],properties:{ok:{const:!0},source:{type:"string"},findings:{type:"array",items:ca},summary:{type:"object",additionalProperties:!1,required:["shapeCount","edgeCount","findingCount","returnedFindingCount","findingsTruncated"],properties:{shapeCount:{type:"integer",minimum:0},edgeCount:{type:"integer",minimum:0},findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"}}}}},annotations:{title:"Check diagram",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"render_diagram",title:"Render diagram",description:"Render one root-relative Slopcamera diagram source with built-in icons and themes, overwriting its paired .tldr, light/dark SVG, and light/dark PNG artifacts.",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string",description:"Root-relative path to a diagram JSON source (1 MiB maximum)."},out_dir:{type:"string",description:"Optional root-relative output directory. Defaults to the source directory."},scale:{type:"number",exclusiveMinimum:0,maximum:TV,default:ob,description:"PNG scale. The scaled canvas may contain at most 16,777,216 pixels."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","scale","findings","artifacts","summary"],properties:{ok:{const:!0},source:{type:"string"},scale:{type:"number"},findings:{type:"array",items:ca},artifacts:{type:"object",additionalProperties:!1,required:["tldr","lightSvg","darkSvg","lightPng","darkPng"],properties:{tldr:{type:"string"},lightSvg:{type:"string"},darkSvg:{type:"string"},lightPng:{type:"string"},darkPng:{type:"string"}}},summary:{type:"object",additionalProperties:!1,required:["shapeCount","edgeCount","findingCount","returnedFindingCount","findingsTruncated"],properties:{shapeCount:{type:"integer",minimum:0},edgeCount:{type:"integer",minimum:0},findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"}}}}},annotations:{title:"Render diagram",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},{name:"search_slopcamera",title:"Search Slopcamera operations",description:"Search the fixed semantic Slopcamera operation registry by bounded text. This never executes code or changes files.",inputSchema:{type:"object",additionalProperties:!1,properties:{query:{type:"string",maxLength:200,description:"Optional terms matched against operation codes and descriptions."},limit:{type:"integer",minimum:1,maximum:20,default:4}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","operations"],properties:{ok:{const:!0},operations:{type:"array",maxItems:20,items:{type:"object",required:["code","title","description","execution","authentication","inputSchema"]}}}},annotations:{title:"Search Slopcamera operations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"execute_slopcamera",title:"Execute Slopcamera operation",description:"Execute one exact operation code with typed JSON input. Never accepts or evaluates source code. Local paths remain confined to the configured workspace root.",inputSchema:{type:"object",additionalProperties:!1,required:["operation","input"],properties:{operation:{type:"string",enum:AV},input:{type:"object",description:"Typed input matching the selected operation's registry schema."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","operation","result"],properties:{ok:{const:!0},operation:{type:"string",enum:AV},result:{type:"object"}}},annotations:{title:"Execute Slopcamera operation",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}]);class d4 extends Error{code;issues;constructor(_,$,F){super($);if(this.name="ToolFailure",this.code=_,F!==void 0)this.issues=F}}function UV(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function u$(_,$=160){return _.replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim().slice(0,$)}function sa(_){return _.slice(0,24).map(($)=>u$($,240))}function Fz(_,$){let F=Object.keys(_).filter((w)=>!$.has(w));if(F.length>0)throw new d4("INVALID_ARGUMENTS",`Unsupported argument: ${u$(F[0]??"unknown")}.`)}function aa(_){if(typeof _!=="string"||_.length===0)throw new d4("INVALID_ARGUMENTS","path must be a non-empty root-relative string.");if(!_.toLowerCase().endsWith(".diagram.json"))throw new d4("INVALID_ARGUMENTS","path must end in .diagram.json.");return _}function SB0(_){if(!UV(_))throw new d4("INVALID_ARGUMENTS","Tool arguments must be an object.");return Fz(_,new Set(["path"])),{path:aa(_.path)}}function yB0(_){if(!UV(_))throw new d4("INVALID_ARGUMENTS","Tool arguments must be an object.");Fz(_,new Set(["path","out_dir","scale"]));let $=_.out_dir;if($!==void 0&&(typeof $!=="string"||$.length===0))throw new d4("INVALID_ARGUMENTS","out_dir must be a non-empty root-relative string when present.");let F=_.scale??ob;if(typeof F!=="number"||!Number.isFinite(F)||F<=0||F>TV)throw new d4("RENDER_LIMIT",`scale must be greater than zero and no more than ${TV}.`);return{path:aa(_.path),...$===void 0?{}:{outDirectory:$},scale:F}}function gB0(_){if(!UV(_))throw new d4("INVALID_ARGUMENTS","Tool arguments must be an object.");Fz(_,new Set(["query","limit"]));let $=_.query??"",F=_.limit??AV.length;if(typeof $!=="string"||$.length>200||/[\u0000-\u001f\u007f]/u.test($)||!Number.isInteger(F)||F<1||F>20)throw new d4("INVALID_ARGUMENTS","query must be a bounded string and limit must be an integer from 1 through 20.");return{query:$,limit:F}}function hB0(_){if(!UV(_))throw new d4("INVALID_ARGUMENTS","Tool arguments must be an object.");if(Fz(_,new Set(["operation","input"])),typeof _.operation!=="string"||!AV.includes(_.operation)||!UV(_.input))throw new d4("INVALID_ARGUMENTS","operation must be an exact Slopcamera operation code and input must be an object.");return{operation:_.operation,input:_.input}}function vB0(_){for(let $ of _.shapes)if(($.type==="rect"||$.type==="ellipse")&&$.icon!==void 0&&!Object.hasOwn(W_,$.icon))throw new d4("UNKNOWN_ICON",`Shape ${u$($.id)} requests unavailable built-in icon ${u$($.icon)}.`)}function xB0(_){let $=_.edges?.length??0;if(_.shapes.length>r7||$>o7)throw new d4("COMPLEXITY_LIMIT",`Diagram may contain at most ${r7} shapes and ${o7} edges in MCP mode.`)}function mB0(_){if(!UV(_))return;let $=Array.isArray(_.shapes)?_.shapes.length:0,F=Array.isArray(_.edges)?_.edges.length:0;if($>r7||F>o7)throw new d4("COMPLEXITY_LIMIT",`Diagram may contain at most ${r7} shapes and ${o7} edges in MCP mode.`)}function lB0(_,$){let F=_.canvas.width*$,w=_.canvas.height*$,Q=Math.ceil(F)*Math.ceil(w);if(!Number.isFinite(Q)||F<1||w<1||Q>n7)throw new d4("RENDER_LIMIT",`Scaled canvas must be at least 1 pixel on each axis and no more than ${n7.toLocaleString("en-US")} pixels total.`)}function dB0(_){return{code:u$(_.code,64),message:u$(_.message,240),shapeIds:_.shapeIds.slice(0,fB0).map(($)=>u$($,120))}}function pa(_){return _.slice(0,oa).map(dB0)}function na(_,$,F){return{shapeCount:_.shapes.length,edgeCount:_.edges?.length??0,findingCount:$,returnedFindingCount:F,findingsTruncated:F<$}}function s7(_,$){return{content:[{type:"text",text:_}],structuredContent:$}}function uB0(_){let $="INTERNAL_ERROR",F="The tool failed safely.",w;if(_ instanceof d4)$=_.code,F=u$(_.message,320),w=_.issues;else if(_ instanceof a1)$=_.code,F=u$(_.message,320);else if(_ instanceof H2)$=_.code,F=u$(_.message.replace(/^\[[A-Z_]+\]\s*/u,""),320);else if(_ instanceof K_)$=_.code,F=u$(_.message.replace(/^\[[A-Z_]+\]\s*/u,""),320);else if(_ instanceof p)$=`VECTORIZE_${_.code.toUpperCase()}`,F="Local vectorization failed safely.";else if(_ instanceof rQ)$="INVALID_DIAGRAM",F="Diagram source did not pass validation.",w=sa(_.issues);else if(typeof _==="object"&&_!==null&&"issues"in _&&Array.isArray(_.issues)&&_.issues.every((Z)=>typeof Z==="string"))$="INVALID_LAYOUT",F="Diagram layout could not be resolved.",w=sa(_.issues);let Q=w===void 0||w.length===0?"":`
1773
1773
  ${w.map((Z)=>`- ${Z}`).join(`
1774
1774
  `)}`;return{content:[{type:"text",text:`[${$}] ${F}${Q}`}],isError:!0}}function cB0(_){let $=_.lastIndexOf("/");return $===-1?".":_.slice(0,$)}async function p7(_,$){let F=BV(IB0(_),`.${crypto.randomUUID()}.slopcamera-mcp.tmp`);try{await PB0(F,$,{flag:"wx"});try{await da(F,_)}catch(w){let Q=typeof w==="object"&&w!==null&&"code"in w&&typeof w.code==="string"?w.code:void 0;if(Q!=="EEXIST"&&Q!=="EPERM")throw w;await ua(_,{force:!0}),await da(F,_)}}finally{await ua(F,{force:!0})}}async function ra(_,$){let F=await _.readSource($),w;try{w=JSON.parse(F.text)}catch{throw new d4("INVALID_JSON","Diagram source is not valid JSON.")}mB0(w);let Q=b9(w);return xB0(Q),vB0(Q),{source:F,spec:Q}}class WZ{boundary;generateDependencies;hostResourceCoordinator;renderQueue=Promise.resolve();constructor(_,$,F){this.boundary=_,this.generateDependencies=$,this.hostResourceCoordinator=F}static async create(_,$={},F){return new WZ(await HZ.create(_),$,F??v9())}async withHostAdmission(_,$){return await nb(_,$,{hostResourceCoordinator:this.hostResourceCoordinator})}enqueueRender(_){let $=this.renderQueue.then(_,_);return this.renderQueue=$.then(()=>{return},()=>{return}),$}async call(_,$){try{if(_==="check_diagram"){let F=SB0($);return await this.withHostAdmission("slopcamera.diagram.check",async()=>await this.check(F))}if(_==="render_diagram"){let F=yB0($);return await this.enqueueRender(async()=>await this.withHostAdmission("slopcamera.diagram.render",async()=>await this.render(F)))}if(_==="search_slopcamera"){let F=gB0($),w=tD(F.query,F.limit);return s7(`Found ${w.length} Slopcamera operation${w.length===1?"":"s"}.`,{ok:!0,operations:w})}if(_==="execute_slopcamera"){let F=hB0($);return await this.execute(F)}throw new d4("UNKNOWN_TOOL","Requested tool is not available.")}catch(F){return uB0(F)}}wrapSemanticResult(_,$){if($.isError===!0)return $;return{content:$.content,structuredContent:{ok:!0,operation:_,result:$.structuredContent??{}}}}async execute(_){if(_.operation==="slopcamera.diagram.check"){let $=b8(_.operation,_.input);return this.wrapSemanticResult(_.operation,await this.withHostAdmission(_.operation,async()=>await this.check({path:$.path})))}if(_.operation==="slopcamera.diagram.render"){let $=b8(_.operation,_.input);return this.enqueueRender(async()=>await this.withHostAdmission(_.operation,async()=>this.wrapSemanticResult(_.operation,await this.render({path:$.path,...$.outDirectory===void 0?{}:{outDirectory:$.outDirectory},scale:$.scale??ob}))))}if(_.operation==="slopcamera.image.vectorize"){let $=b8(_.operation,_.input);return this.enqueueRender(async()=>await this.withHostAdmission(_.operation,async(F)=>{let w=await this.boundary.resolveInputFile($.inputPath,e6.maxInputBytes),Q=await this.boundary.prepareOutputFile($.outputPath),Z=await Q3(w.absolutePath,{outputPath:Q.absolutePath,...$.duotone===void 0?{}:{duotone:$.duotone},...$.alphaCutoff===void 0?{}:{alphaCutoff:$.alphaCutoff},...$.timeoutMs===void 0?{}:{limits:{maxDurationMs:$.timeoutMs}},inheritedFileDescriptors:[F.inheritedFileDescriptor]});return s7(`Executed ${_.operation}: ${Q.relativePath}`,{ok:!0,operation:_.operation,result:{inputPath:w.relativePath,outputPath:Q.relativePath,receipt:Z.receipt}})}))}return await this.withHostAdmission(_.operation,async()=>{let $=b8(_.operation,_.input),F=await this.boundary.prepareOutputFile($.outputPath),w=await KV({...$,outputPath:F.absolutePath},this.generateDependencies);return s7(`Executed ${_.operation}: ${F.relativePath} (request ${u$(w.requestId,256)}).`,{ok:!0,operation:_.operation,result:{bytes:w.bytes,mediaType:w.mediaType,model:w.model,outputPath:F.relativePath,provider:w.provider,requestId:w.requestId,sha256:w.sha256,warnings:w.warnings}})})}async check(_){let{source:$,spec:F}=await ra(this.boundary,_.path),w=E8(F),Q=pa(w),Z=na(F,w.length,Q.length),J=w.length===0?`Checked ${$.relativePath}: no findings.`:`Checked ${$.relativePath}: ${w.length} finding${w.length===1?"":"s"}; ${Q.length} returned in structured content${Q.length<w.length?" (truncated)":""}.`;return s7(J,{ok:!0,source:$.relativePath,findings:Q,summary:Z})}async render(_){let{source:$,spec:F}=await ra(this.boundary,_.path);lB0(F,_.scale);let w=await this.boundary.prepareOutputDirectory(_.outDirectory??cB0($.relativePath)),Q=fF(F,c7),[Z,J]=await Promise.all([X$(F,"light",c7),X$(F,"dark",c7)]),X=M8(Z,c7,_.scale),V=M8(J,c7,_.scale),Y={spec:$.absolutePath,tldr:BV(w.absolutePath,`${F.name}.tldr`),lightSvg:BV(w.absolutePath,`${F.name}.light.svg`),darkSvg:BV(w.absolutePath,`${F.name}.dark.svg`),lightPng:BV(w.absolutePath,`${F.name}.light.png`),darkPng:BV(w.absolutePath,`${F.name}.dark.png`)};await Promise.all([p7(Y.tldr,Q),p7(Y.lightSvg,Z.svg),p7(Y.darkSvg,J.svg),p7(Y.lightPng,X),p7(Y.darkPng,V)]);let j={tldr:this.boundary.toRelativePath(Y.tldr),lightSvg:this.boundary.toRelativePath(Y.lightSvg),darkSvg:this.boundary.toRelativePath(Y.darkSvg),lightPng:this.boundary.toRelativePath(Y.lightPng),darkPng:this.boundary.toRelativePath(Y.darkPng)},H=E8(F),K=pa(H),W=na(F,H.length,K.length),O=[`Rendered ${$.relativePath} with built-in assets:`,...Object.values(j).map((L)=>`- ${L}`)].join(`
1775
- `);return s7(O,{ok:!0,source:$.relativePath,scale:_.scale,findings:K,artifacts:j,summary:W})}}var ta="3.2.4";var Qz="2025-11-25",Zz="hraness-slopcamera",ib=1048576;function KZ(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function sB0(_){return typeof _==="string"||typeof _==="number"&&Number.isSafeInteger(_)}function pB0(_){return KZ(_)&&typeof _.protocolVersion==="string"&&KZ(_.capabilities)&&KZ(_.clientInfo)&&typeof _.clientInfo.name==="string"&&typeof _.clientInfo.version==="string"}function nB0(_){if(!KZ(_)||_.jsonrpc!=="2.0"||typeof _.method!=="string"||_.method.length===0||"id"in _&&!sB0(_.id))throw Error("invalid request");return{jsonrpc:"2.0",..."id"in _?{id:_.id}:{},method:_.method,..."params"in _?{params:_.params}:{}}}function wz(_,$){return{jsonrpc:"2.0",id:_,result:$}}function j$(_,$,F){return{jsonrpc:"2.0",id:_,error:{code:$,message:F}}}function rB0(_){if(!KZ(_)||typeof _.name!=="string"||_.arguments!==void 0&&!KZ(_.arguments))throw Error("invalid params");if(Object.keys(_).filter((F)=>F!=="name"&&F!=="arguments").length>0)throw Error("invalid params");return{name:_.name,argumentsValue:_.arguments??{}}}class _t{runtime;serverVersion;state="new";constructor(_,$){this.runtime=_,this.serverVersion=$}async handle(_){let $;try{$=nB0(_)}catch{return j$(null,-32600,"Invalid Request")}let F=$.id===void 0;if($.method==="notifications/initialized"){if(!F)return j$($.id,-32600,"Invalid Request");if(this.state==="initializing")this.state="ready";return null}if(F)return null;let w=$.id;if($.method==="initialize"){if(this.state!=="new"||!pB0($.params))return j$(w,-32602,"Invalid initialize parameters");return this.state="initializing",wz(w,{protocolVersion:Qz,capabilities:{tools:{listChanged:!1}},serverInfo:{name:Zz,version:this.serverVersion},instructions:"Use check_diagram/render_diagram or search_slopcamera followed by execute_slopcamera with an exact registry code and typed JSON. Local paths are root-relative; source code is never accepted or evaluated."})}if(this.state!=="ready")return j$(w,-32002,"Server is not initialized");if($.method==="ping")return wz(w,{});if($.method==="tools/list"){if($.params!==void 0&&(!KZ($.params)||Object.keys($.params).length>0))return j$(w,-32602,"Invalid tools/list parameters");return wz(w,{tools:kV})}if($.method==="tools/call")try{let Q=rB0($.params);if(!kV.some((Z)=>Z.name===Q.name))return j$(w,-32602,"Unknown tool");return wz(w,await this.runtime.call(Q.name,Q.argumentsValue))}catch{return j$(w,-32602,"Invalid tools/call parameters")}return j$(w,-32601,"Method not found")}}async function oB0(_){await new Promise(($,F)=>{process.stdout.write(`${_}
1775
+ `);return s7(O,{ok:!0,source:$.relativePath,scale:_.scale,findings:K,artifacts:j,summary:W})}}var ta="3.2.5";var Qz="2025-11-25",Zz="hraness-slopcamera",ib=1048576;function KZ(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function sB0(_){return typeof _==="string"||typeof _==="number"&&Number.isSafeInteger(_)}function pB0(_){return KZ(_)&&typeof _.protocolVersion==="string"&&KZ(_.capabilities)&&KZ(_.clientInfo)&&typeof _.clientInfo.name==="string"&&typeof _.clientInfo.version==="string"}function nB0(_){if(!KZ(_)||_.jsonrpc!=="2.0"||typeof _.method!=="string"||_.method.length===0||"id"in _&&!sB0(_.id))throw Error("invalid request");return{jsonrpc:"2.0",..."id"in _?{id:_.id}:{},method:_.method,..."params"in _?{params:_.params}:{}}}function wz(_,$){return{jsonrpc:"2.0",id:_,result:$}}function j$(_,$,F){return{jsonrpc:"2.0",id:_,error:{code:$,message:F}}}function rB0(_){if(!KZ(_)||typeof _.name!=="string"||_.arguments!==void 0&&!KZ(_.arguments))throw Error("invalid params");if(Object.keys(_).filter((F)=>F!=="name"&&F!=="arguments").length>0)throw Error("invalid params");return{name:_.name,argumentsValue:_.arguments??{}}}class _t{runtime;serverVersion;state="new";constructor(_,$){this.runtime=_,this.serverVersion=$}async handle(_){let $;try{$=nB0(_)}catch{return j$(null,-32600,"Invalid Request")}let F=$.id===void 0;if($.method==="notifications/initialized"){if(!F)return j$($.id,-32600,"Invalid Request");if(this.state==="initializing")this.state="ready";return null}if(F)return null;let w=$.id;if($.method==="initialize"){if(this.state!=="new"||!pB0($.params))return j$(w,-32602,"Invalid initialize parameters");return this.state="initializing",wz(w,{protocolVersion:Qz,capabilities:{tools:{listChanged:!1}},serverInfo:{name:Zz,version:this.serverVersion},instructions:"Use check_diagram/render_diagram or search_slopcamera followed by execute_slopcamera with an exact registry code and typed JSON. Local paths are root-relative; source code is never accepted or evaluated."})}if(this.state!=="ready")return j$(w,-32002,"Server is not initialized");if($.method==="ping")return wz(w,{});if($.method==="tools/list"){if($.params!==void 0&&(!KZ($.params)||Object.keys($.params).length>0))return j$(w,-32602,"Invalid tools/list parameters");return wz(w,{tools:kV})}if($.method==="tools/call")try{let Q=rB0($.params);if(!kV.some((Z)=>Z.name===Q.name))return j$(w,-32602,"Unknown tool");return wz(w,await this.runtime.call(Q.name,Q.argumentsValue))}catch{return j$(w,-32602,"Invalid tools/call parameters")}return j$(w,-32601,"Method not found")}}async function oB0(_){await new Promise(($,F)=>{process.stdout.write(`${_}
1776
1776
  `,(w)=>{if(w===null||w===void 0)$();else F(w)})})}function iB0(){return process.stdin}async function MV(_,$){await _(JSON.stringify($))}async function ea(_,$,F){if(_.byteLength===0)return;let w;try{let Z=new TextDecoder("utf-8",{fatal:!0}).decode(_);if(Z.trim()==="")return;w=JSON.parse(Z)}catch{await MV(F,j$(null,-32700,"Parse error"));return}if(Array.isArray(w)){await MV(F,j$(null,-32600,"Invalid Request"));return}let Q=await $.handle(w);if(Q!==null)await MV(F,Q)}async function ab(_={}){let $=await WZ.create(_.rootDirectory??process.cwd(),_.generateDependencies),F=new _t($,_.serverVersion??ta),w=_.writeLine??oB0,Q=Buffer.alloc(0);for await(let Z of _.input??iB0()){let J=typeof Z==="string"?Buffer.from(Z,"utf8"):Buffer.from(Z);if(Q=Buffer.concat([Q,J]),Q.byteLength>ib&&!Q.includes(10)){Q=Buffer.alloc(0),await MV(w,j$(null,-32700,"Parse error"));continue}for(;;){let X=Q.indexOf(10);if(X===-1)break;let V=Q.subarray(0,X);if(Q=Q.subarray(X+1),V.at(-1)===13)V=V.subarray(0,-1);if(V.byteLength>ib)await MV(w,j$(null,-32700,"Parse error"));else await ea(V,F,w)}}if(Q.byteLength>0)if(Q.byteLength>ib)await MV(w,j$(null,-32700,"Parse error"));else await ea(Q,F,w)}import{cp as aB0,mkdir as tB0,rm as eB0}from"fs/promises";import{homedir as _T0}from"os";import{dirname as $t,join as Jz,resolve as Ft}from"path";import{fileURLToPath as $T0}from"url";function tb(){return Ft($t($T0(import.meta.url)),"../skills/slopcamera")}function FT0(_,$,F){let w=_==="codex"?".codex":_==="claude"?".claude":".agents";return $==="user"?Jz(_T0(),w,"skills"):Jz(F,w,"skills")}async function wt(_){let $=tb();if(!await Y$($))throw Error(`Bundled skill is missing: ${$}`);let F=FT0(_.target,_.scope,Ft(_.projectDirectory??process.cwd())),w=Jz(F,"diagram");if(await Y$(w))throw Error(`Legacy diagram skill found at ${w}. Remove or move that directory, then rerun "slopcamera skill install --target ${_.target} --scope ${_.scope}". Slopcamera will not install both skills side by side.`);let Q=Jz(F,"slopcamera");if(await Y$(Q)){if(!_.force)throw Error(`Skill already exists at ${Q}; pass --force to replace it`);await eB0(Q,{recursive:!0,force:!0})}return await tB0($t(Q),{recursive:!0}),await aB0($,Q,{recursive:!0,errorOnExist:!0}),Q}uD();var wT0=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u,QT0=/^[A-Za-z0-9]+(?:[._:-][A-Za-z0-9]+)*$/u,ZT0=64,Qt=256;class J5 extends Error{code;completedSteps;failedStep;constructor(_,$,F={}){super(`[${_}] ${$}`,{cause:F.cause});if(this.name="SlopcameraWorkflowError",this.code=_,this.completedSteps=Object.freeze([...F.completedSteps??[]].sort((w,Q)=>w.index-Q.index)),F.failedStep!==void 0)this.failedStep=Object.freeze({...F.failedStep})}}function a7(_,$){throw new J5(_,$)}function JT0(_){if(typeof _!=="string"||_.length<1||_.length>80||!wT0.test(_))a7("INVALID_WORKFLOW","Workflow id must be 1 through 80 lowercase letters, numbers, dots, underscores, or hyphens.")}function XT0(_,$=[]){if(typeof _!=="string"||_.length<1||_.length>80||!QT0.test(_))throw new J5("INVALID_WORKFLOW_STEP","Step id must be 1 through 80 letters, numbers, dots, underscores, colons, or hyphens.",{completedSteps:$})}function eb(_){if(typeof _!=="object"||_===null)a7("INVALID_WORKFLOW","Workflow definition must be an object.");if(JT0(_.id),!Number.isSafeInteger(_.version)||_.version<1)a7("INVALID_WORKFLOW","Workflow version must be a positive safe integer.");if(typeof _.parseInput!=="function"||typeof _.run!=="function")a7("INVALID_WORKFLOW","Workflow definition requires parseInput and run functions.");return Object.freeze({id:_.id,version:_.version,parseInput:_.parseInput,run:_.run})}function VT0(_){let $=_??ZT0;if(!Number.isSafeInteger($)||$<1||$>Qt)a7("INVALID_WORKFLOW",`maximumSteps must be an integer from 1 through ${Qt}.`);return $}function i7(_,$){return new J5("WORKFLOW_ABORTED","Workflow execution was aborted.",{cause:$,completedSteps:_})}async function Zt(_,$,F={}){let w=eb(_),Q=VT0(F.maximumSteps),Z=F.signal??F.dependencies?.signal??new AbortController().signal,J=new Set,X=[],V=[],Y=!0,j=0;if(Z.aborted)throw i7(X);let H;try{H=w.parseInput($)}catch(T){throw new J5("INVALID_WORKFLOW_INPUT","Workflow input did not satisfy its parser.",{cause:T})}let K=F.executor??((T,M,R)=>jZ(T,M,R.hostResourceLease,F.dependencies)),W=F.hostResourceCoordinator??F.dependencies?.hostResourceCoordinator??v9(),O=F.waitTimeoutMilliseconds??F.dependencies?.waitTimeoutMilliseconds;async function L(T,M,R){if(Z.aborted)throw i7(X);if(XT0(T,X),!ya(M))throw new J5("INVALID_WORKFLOW_STEP",`Workflow step ${T} names an unknown Slopcamera operation.`,{completedSteps:X});if(J.has(T))throw new J5("INVALID_WORKFLOW_STEP",`Duplicate workflow step id: ${T}.`,{completedSteps:X});if(j>=Q)throw new J5("INVALID_WORKFLOW_STEP",`Workflow exceeds its ${String(Q)}-step limit.`,{completedSteps:X});let g=j;j+=1,J.add(T);let U;try{U=b8(M,R)}catch(E){throw new J5("INVALID_WORKFLOW_STEP",`Workflow step ${T} has invalid input for ${M}.`,{cause:E,completedSteps:X})}try{let E=await W.withLease(aD(M),async(f)=>await K(M,U,{hostResourceLease:f,signal:Z,stepId:T}),{signal:Z,...O===void 0?{}:{waitTimeoutMilliseconds:O}});if(X.push(Object.freeze({id:T,index:g,operation:M})),Z.aborted)throw i7(X);return E}catch(E){if(E instanceof J5&&E.code==="WORKFLOW_ABORTED")throw E;if(Z.aborted)throw i7(X,E);throw new J5("WORKFLOW_STEP_FAILED",`Workflow step ${T} (${M}) failed.`,{cause:E,completedSteps:X,failedStep:{id:T,operation:M}})}}let G=Object.freeze({signal:Z,operation(T,M,R){if(!Y){let U=Promise.reject(new J5("INVALID_WORKFLOW_STEP","Workflow operations cannot start after authored workflow code has settled.",{completedSteps:X}));return U.catch(()=>{return}),U}let g=L(T,M,R);return V.push(g),g.catch(()=>{return}),g}}),D,z=!1,C;try{D=await w.run(G,H)}catch(T){z=!0,C=T}finally{Y=!1}let A=await Promise.allSettled(V);if(Z.aborted)throw i7(X,z?C:void 0);if(z){if(C instanceof J5)throw C;throw new J5("WORKFLOW_FAILED",`Workflow ${w.id} failed in authored code.`,{cause:C,completedSteps:X})}let B=A.find((T)=>T.status==="rejected");if(B!==void 0){let T=B.reason;if(T instanceof J5)throw T;throw new J5("WORKFLOW_STEP_FAILED","A dispatched workflow operation failed.",{cause:T,completedSteps:X})}return Object.freeze({workflow:Object.freeze({id:w.id,version:w.version}),output:D,steps:Object.freeze([...X].sort((T,M)=>T.index-M.index))})}import{z as w0}from"zod";import{z as Jt}from"zod";var P1=Object.freeze({documentBytes:33554432,documentDepth:32,documentValues:500000,sourceFiles:512,sourceBytes:4294967296,outputSpecifications:32,outputFiles:25000,outputBytes:68719476736,timeoutSeconds:21600,frames:25000,frameIndexExclusive:1e6,dimension:8192,pixels:33554432,parameterBytes:262144,parameterDepth:16,parameterValues:20000});function J3(_,$){return Jt.preprocess((F)=>F===void 0?void 0:Z1(F,P1.documentBytes,$,{maximumDepth:P1.documentDepth,maximumValues:P1.documentValues}).value,_)}function lF(_,$){try{return l0(_.parse($))}catch(F){if(F instanceof B0)throw F;throw new B0("invalid-data",F instanceof Jt.ZodError?F.issues[0]?.message??"Invalid studio document.":"Invalid studio document.")}}function t7(_,$){return p_({domain:_,value:$},{maximumBytes:P1.documentBytes,maximumDepth:P1.documentDepth+2,maximumValues:P1.documentValues+4})}var OZ=nA;function u4(_,$){if(!_)throw new B0("invalid-data",$)}function YT0(_){return _.toLowerCase()}function e7(_){let $=new Set(_.map(YT0));u4($.size===_.length,"Studio paths collide.");for(let F of $)for(let w=F.indexOf("/");w!==-1;w=F.indexOf("/",w+1))u4(!$.has(F.slice(0,w)),"Studio paths use a file as an ancestor.")}var c5=w0.string().regex(/^[a-f0-9]{64}$/u),Xz=w0.enum(["blender","manim","cadquery"]),U4=w0.string().min(1).max(1024).refine((_)=>_.normalize("NFC")===_&&!_.startsWith("/")&&!/[\\:\u0000-\u001f\u007f]/u.test(_)&&_.split("/").every(($)=>$!==""&&$!=="."&&$!==".."&&!/[. ]$/u.test($)),"Studio paths must be normalized, contained POSIX-relative names."),Xt=w0.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u),Ht=w0.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/u),jT0=w0.strictObject({path:U4,sha256:c5,bytes:w0.number().int().safe().nonnegative().max(P1.sourceBytes)}),Vt=w0.strictObject({kind:w0.literal("slopcamera.studio-source-bundle"),schemaVersion:w0.literal(1),engine:Xz,entrypoint:w0.discriminatedUnion("kind",[w0.strictObject({kind:w0.literal("python"),path:U4.refine((_)=>_.endsWith(".py"))}),w0.strictObject({kind:w0.literal("blend"),path:U4.refine((_)=>_.endsWith(".blend"))})]),files:w0.array(jT0).min(1).max(P1.sourceFiles)}).superRefine((_,$)=>{let F=(w)=>$.addIssue({code:"custom",message:w});try{e7(_.files.map((w)=>w.path))}catch{F("Source paths must be distinct and cannot have file ancestors.")}if(_.files.reduce((w,Q)=>w+Q.bytes,0)>P1.sourceBytes)F("Source bundle exceeds four GiB.");if(!_.files.some((w)=>w.path===_.entrypoint.path&&w.bytes>0))F("Entrypoint must name a declared nonempty source file.");if(_.entrypoint.kind==="blend"&&_.engine!=="blender")F("Blend entrypoints require Blender.")}),NT0=Vt.transform((_)=>({..._,files:[..._.files].sort(($,F)=>OZ($.path,F.path))})).pipe(Vt),Vz=J3(NT0,"studio source bundle"),X3=(_)=>lF(Vz,_),HT0=w0.strictObject({units:w0.enum(["meters","millimeters","centimeters"]),upAxis:w0.enum(["x","y","z"]),handedness:w0.enum(["right","left"])}),Yz=w0.enum(["native-source","model","beauty","auxiliary","simulation-cache","audio"]),jz=w0.enum(["py","blend","usd","usda","usdc","glb","step","png","exr","mp4","mov","webm","wav","flac","mp3","cache"]),WT0=w0.strictObject({kind:w0.literal("raster"),colorSpace:w0.enum(["srgb","linear-rec709","data","unspecified"]),alpha:w0.enum(["opaque","straight","premultiplied","none"]),dataType:w0.enum(["uint8","uint16","float16","float32"]),channels:w0.array(w0.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u)).min(1).max(32),semantic:w0.enum(["color","depth","normal","object-id","mask","custom"]),unit:w0.enum(["unitless","meters","millimeters","centimeters"])}).superRefine((_,$)=>{if(new Set(_.channels).size!==_.channels.length)$.addIssue({code:"custom",message:"Raster channels must be unique."});if(_.semantic!=="color"&&_.colorSpace!=="data")$.addIssue({code:"custom",message:"Non-color raster passes must declare data color space."});if(_.semantic==="color"&&_.colorSpace==="data")$.addIssue({code:"custom",message:"Color output cannot declare data color space."});if(_.semantic!=="depth"&&_.unit!=="unitless")$.addIssue({code:"custom",message:"Only depth passes declare distance units."})}),KT0=w0.discriminatedUnion("kind",[WT0,w0.strictObject({kind:w0.literal("model"),sourceSpace:HT0}),w0.strictObject({kind:w0.literal("native-source")}),w0.strictObject({kind:w0.literal("cache"),semantics:w0.literal("opaque-native")}),w0.strictObject({kind:w0.literal("audio"),sampleRate:w0.number().int().min(8000).max(384000),channels:w0.number().int().min(1).max(32)})]),_P={id:Ht,role:Yz,format:jz,interpretation:KT0},OT0=w0.string().max(1024).refine((_)=>_.split("%06d").length===2&&!_.replace("%06d","").includes("%")&&U4.safeParse(_.replace("%06d","000000")).success,"Sequence paths require exactly one %06d placeholder in a safe relative path.");function LT0(_){if(_.role==="native-source")return["py","blend"].includes(_.format)&&_.interpretation.kind==="native-source";if(_.role==="model")return["blend","usd","usda","usdc","glb","step"].includes(_.format)&&_.interpretation.kind==="model";if(_.role==="simulation-cache")return _.format==="cache"&&_.interpretation.kind==="cache";if(_.role==="audio")return["wav","flac","mp3"].includes(_.format)&&_.interpretation.kind==="audio";return["png","exr","mp4","mov","webm"].includes(_.format)&&_.interpretation.kind==="raster"&&(_.role!=="beauty"||_.interpretation.semantic==="color")}var GT0=w0.discriminatedUnion("kind",[w0.strictObject({..._P,kind:w0.literal("file"),path:U4}),w0.strictObject({..._P,kind:w0.literal("sequence"),pathPattern:OT0}),w0.strictObject({..._P,kind:w0.literal("directory"),path:U4})]).superRefine((_,$)=>{let F=(w)=>$.addIssue({code:"custom",message:w});if(!LT0(_))F("Output role, format, and interpretation disagree.");if(_.kind==="directory"!==(_.format==="cache"))F("Only native cache outputs use directory declarations.");if(_.kind==="sequence"&&!["png","exr"].includes(_.format))F("Numbered sequences support PNG or EXR only.");if(_.kind!=="directory"){let w=_.kind==="sequence"?_.pathPattern:_.path;if(!w.endsWith(`.${_.format}`)&&!(_.format==="step"&&w.endsWith(".stp")))F("Output extension must agree with its declared format.")}if(_.interpretation.kind==="raster"){if(_.format==="png"&&!["uint8","uint16"].includes(_.interpretation.dataType))F("PNG declares integer sample data.");if(_.format==="exr"&&!["float16","float32"].includes(_.interpretation.dataType))F("The admitted EXR profile declares floating point sample data.")}}),Yt=w0.strictObject({numerator:w0.number().int().min(1).max(1e6),denominator:w0.number().int().min(1).max(1e6)}).refine((_)=>_.numerator/_.denominator<=240,"Studio cadence exceeds 240 fps."),DT0=Yt.transform((_)=>{let{numerator:$,denominator:F}=_;while(F!==0){let w=$%F;$=F,F=w}return{numerator:_.numerator/$,denominator:_.denominator/$}}).pipe(Yt),$P=w0.strictObject({width:w0.number().int().min(1).max(P1.dimension),height:w0.number().int().min(1).max(P1.dimension),frameRate:DT0,startFrame:w0.number().int().nonnegative().max(P1.frameIndexExclusive-1),endFrameExclusive:w0.number().int().positive().max(P1.frameIndexExclusive)}).refine((_)=>_.endFrameExclusive>_.startFrame&&_.endFrameExclusive-_.startFrame<=P1.frames&&_.width*_.height<=P1.pixels,"Render requires a bounded, nonempty half-open frame interval and pixel area."),zT0=w0.discriminatedUnion("engine",[w0.strictObject({engine:w0.literal("blender"),renderer:w0.enum(["cycles","eevee"]),device:w0.enum(["cpu","gpu"]),samples:w0.number().int().min(1).max(4096),transparent:w0.boolean(),viewTransform:w0.enum(["AgX","Standard"]),denoise:w0.boolean(),seed:w0.number().int().min(0).max(4294967295)}),w0.strictObject({engine:w0.literal("manim"),scene:Xt,renderer:w0.literal("cairo"),transparent:w0.boolean()}),w0.strictObject({engine:w0.literal("cadquery"),exportVariable:Xt,tolerance:w0.number().finite().positive().max(1),angularTolerance:w0.number().finite().positive().max(Math.PI)})]),CT0=w0.preprocess((_)=>_===void 0?void 0:Z1(_,P1.parameterBytes,"studio parameters",{maximumDepth:P1.parameterDepth,maximumValues:P1.parameterValues}).value,w0.record(w0.string(),w0.unknown())),AT0=w0.strictObject({trust:w0.literal("trusted-current-user"),isolation:w0.literal("none"),hermetic:w0.literal(!1)}),jt=w0.strictObject({kind:w0.literal("slopcamera.studio-job"),schemaVersion:w0.literal(1),jobId:w0.string().regex(/^studio_[a-zA-Z0-9][a-zA-Z0-9_-]{0,120}$/u),bundleSha256:c5,stage:w0.enum(["build","bake","render"]),parameters:CT0,engine:zT0,render:$P.optional(),outputs:w0.array(GT0).min(1).max(P1.outputSpecifications),limits:w0.strictObject({timeoutSeconds:w0.number().int().min(1).max(P1.timeoutSeconds),maximumOutputBytes:w0.number().int().safe().min(1).max(P1.outputBytes),maximumOutputFiles:w0.number().int().min(1).max(P1.outputFiles)}),execution:AT0}).superRefine((_,$)=>{if(_.render===void 0&&(_.stage==="render"&&_.engine.engine!=="cadquery"||_.outputs.some((w)=>w.kind==="sequence"||w.interpretation.kind==="raster")))$.addIssue({code:"custom",message:"Raster outputs, render stage, and numbered sequences require explicit dimensions and a frame interval."});if(new Set(_.outputs.map((w)=>w.id)).size!==_.outputs.length)$.addIssue({code:"custom",message:"Output IDs must be unique."});if(_.outputs.reduce((w,Q)=>w+(Q.kind==="sequence"&&_.render!==void 0?_.render.endFrameExclusive-_.render.startFrame:1),0)>_.limits.maximumOutputFiles)$.addIssue({code:"custom",message:"Declared outputs exceed the job's output-file limit."})}),BT0=jt.transform((_)=>({..._,outputs:[..._.outputs].sort(($,F)=>OZ($.id,F.id))})).pipe(jt),RV=J3(BT0,"studio job"),V3=(_)=>lF(RV,_),EV=w0.enum(["python-authoring","blend-authoring","build","bake","render","gpu-render","image-sequence","beauty-video","model-export","auxiliary-passes","native-cache","audio-output"]),TT0=w0.strictObject({name:EV,support:w0.enum(["available","unavailable","unverified"]),evidence:w0.enum(["probe","qualification"]),receiptSha256:c5.optional()}).refine((_)=>_.evidence!=="qualification"||_.receiptSha256!==void 0,"Qualification evidence requires a retained receipt digest."),Nt=w0.strictObject({kind:w0.literal("slopcamera.studio-runtime"),schemaVersion:w0.literal(1),engine:Xz,tool:w0.strictObject({name:w0.string().min(1).max(128),version:w0.string().min(1).max(512),executableSha256:c5}),driverSha256:c5,environment:w0.strictObject({fingerprintSha256:c5,evidence:w0.literal("observed-package-environment"),hermetic:w0.literal(!1)}),capabilities:w0.array(TT0).max(12)}).refine((_)=>new Set(_.capabilities.map(($)=>$.name)).size===_.capabilities.length,"Runtime capability names must be unique."),UT0=Nt.transform((_)=>({..._,capabilities:[..._.capabilities].sort(($,F)=>OZ($.name,F.name))})).pipe(Nt),_H=J3(UT0,"studio runtime identity"),Nz=(_)=>lF(_H,_),Wt=w0.strictObject({outputId:Ht,path:U4,sha256:c5,bytes:w0.number().int().safe().positive().max(P1.outputBytes),role:Yz,format:jz,frame:w0.number().int().nonnegative().max(P1.frameIndexExclusive-1).optional()});import{z as m1}from"zod";var LZ=(_)=>t7("slopcamera.studio-source-bundle/v1",X3(_)),kT0=(_)=>t7("slopcamera.studio-job/v1",V3(_)),Hz=(_)=>t7("slopcamera.studio-runtime/v1",Nz(_));function wP(_,$){if(_.kind==="sequence")return u4(Number.isInteger($)&&$>=0&&$<P1.frameIndexExclusive,"Sequence output requires an admitted frame index."),_.pathPattern.replace("%06d",String($).padStart(6,"0"));return u4($===void 0,"Only sequence outputs have a frame index."),_.path}function Lt(_){let $=[],F=[];for(let w of _.outputs)if(w.kind==="directory")F.push({id:w.id,path:w.path});else if(w.kind==="file")$.push({id:w.id,path:w.path});else{u4(_.render!==void 0,"Sequence requires a render interval.");for(let Q=_.render.startFrame;Q<_.render.endFrameExclusive;Q++)$.push({id:w.id,path:wP(w,Q),frame:Q})}return u4($.length+F.length<=_.limits.maximumOutputFiles,"Declared outputs exceed the output-file budget."),e7([...$,...F].map((w)=>w.path)),{files:$,directories:F}}function MT0(_,$){let F=new Set([_.entrypoint.kind==="blend"?"blend-authoring":"python-authoring",$.stage]);if($.engine.engine==="blender"&&$.engine.device==="gpu"&&$.stage==="render")F.add("gpu-render");for(let w of $.outputs){if(w.kind==="sequence")F.add("image-sequence");if(w.role==="beauty"&&["mov","mp4","webm"].includes(w.format))F.add("beauty-video");if(w.role==="model")F.add("model-export");if(w.role==="auxiliary")F.add("auxiliary-passes");if(w.role==="simulation-cache")F.add("native-cache");if(w.role==="audio")F.add("audio-output")}return[...F].sort(OZ)}function Gt(_){let{bundle:$,job:F,runtime:w}=_,Q=LZ($),Z=kT0(F);u4(Q===F.bundleSha256,"Job does not bind the exact source bundle."),u4($.engine===F.engine.engine&&(w===void 0||w.engine===$.engine),"Bundle, job, and runtime must use one engine."),u4($.entrypoint.kind!=="blend"||F.stage==="render","Blend entrypoints support render stage only; explicit Python authoring owns builds and bakes.");let J=Lt(F),X=MT0($,F),V=X.map((H)=>({name:H,support:w===void 0?"unbound":w.capabilities.find((K)=>K.name===H)?.support??"unverified"})),Y=w===void 0?"runtime-unbound":V.some((H)=>H.support==="unavailable")?"capability-unavailable":V.some((H)=>H.support==="unverified")?"capability-unverified":"authorization-required",j={kind:"slopcamera.studio-plan",schemaVersion:1,bundle:$,job:F,...w===void 0?{}:{runtime:w,runtimeSha256:Hz(w)},bundleSha256:Q,jobSha256:Z,sourceBytes:$.files.reduce((H,K)=>H+K.bytes,0),frameCount:F.render===void 0?0:F.render.endFrameExclusive-F.render.startFrame,outputCount:{minimum:J.files.length+J.directories.length,maximum:J.directories.length===0?J.files.length:F.limits.maximumOutputFiles},requiredCapabilities:X,capabilityChecks:V,readiness:Y};return{...j,planSha256:t7("slopcamera.studio-plan/v1",j)}}var RT0=m1.strictObject({kind:m1.literal("slopcamera.studio-plan"),schemaVersion:m1.literal(1),bundle:Vz,job:RV,runtime:_H.optional(),runtimeSha256:c5.optional(),bundleSha256:c5,jobSha256:c5,planSha256:c5,sourceBytes:m1.number().int().safe().nonnegative().max(P1.sourceBytes),frameCount:m1.number().int().nonnegative().max(P1.frames),outputCount:m1.strictObject({minimum:m1.number().int().positive().max(P1.outputFiles),maximum:m1.number().int().positive().max(P1.outputFiles)}),requiredCapabilities:m1.array(EV).min(1).max(12),capabilityChecks:m1.array(m1.strictObject({name:EV,support:m1.enum(["available","unavailable","unverified","unbound"])})).min(1).max(12),readiness:m1.enum(["runtime-unbound","capability-unavailable","capability-unverified","authorization-required"])}).superRefine((_,$)=>{try{let F=Gt({bundle:_.bundle,job:_.job,..._.runtime===void 0?{}:{runtime:_.runtime}});if(k(F)!==k(_))$.addIssue({code:"custom",message:"Studio plan differs from its canonical source, job, runtime, or admission derivation."})}catch(F){$.addIssue({code:"custom",message:F instanceof Error?F.message:"Invalid studio plan."})}}),$H=J3(RT0,"studio plan"),O_=(_)=>lF($H,_);function FH(_){let $=lF(J3(m1.strictObject({bundle:Vz,job:RV,runtime:_H.optional()}),"studio planning input"),_);return O_(Gt($))}var Kt=m1.strictObject({code:m1.enum(["subprocess","cancelled","deadline","validation","custody","publication","unavailable"]),message:m1.string().min(1).max(2048)}),FP={kind:m1.literal("slopcamera.studio-receipt"),schemaVersion:m1.literal(1),jobId:m1.string().regex(/^studio_[a-zA-Z0-9][a-zA-Z0-9_-]{0,120}$/u),attemptId:m1.string().regex(/^attempt_[a-zA-Z0-9][a-zA-Z0-9_-]{0,120}$/u),planSha256:c5,bundleSha256:c5,jobSha256:c5,runtime:_H,runtimeSha256:c5,startedAt:m1.iso.datetime({offset:!0}),finishedAt:m1.iso.datetime({offset:!0}),outputs:m1.array(Wt).max(P1.outputFiles)},Ot=m1.discriminatedUnion("state",[m1.strictObject({...FP,state:m1.literal("succeeded"),custody:m1.literal("closed"),exitCode:m1.literal(0)}),m1.strictObject({...FP,state:m1.literal("failed"),custody:m1.literal("closed"),exitCode:m1.number().int().min(-255).max(255).nullable(),failure:Kt}),m1.strictObject({...FP,state:m1.literal("unknown-custody"),custody:m1.literal("unknown"),exitCode:m1.number().int().min(-255).max(255).nullable(),failure:Kt})]).superRefine((_,$)=>{if(Hz(_.runtime)!==_.runtimeSha256)$.addIssue({code:"custom",message:"Receipt runtime digest differs from its evidence."});if(Date.parse(_.finishedAt)<Date.parse(_.startedAt))$.addIssue({code:"custom",message:"Receipt finishes before it starts."});try{e7(_.outputs.map((F)=>F.path))}catch{$.addIssue({code:"custom",message:"Receipt output paths collide."})}if(_.outputs.reduce((F,w)=>F+w.bytes,0)>P1.outputBytes)$.addIssue({code:"custom",message:"Receipt exceeds the global output byte bound."})}),ET0=Ot.transform((_)=>({..._,outputs:[..._.outputs].sort(($,F)=>OZ($.path,F.path))})).pipe(Ot),QP=J3(ET0,"studio receipt");function S_(_){let $=lF(J3(m1.strictObject({plan:$H,receipt:QP}),"studio receipt validation input"),_),{plan:F,receipt:w}=$;if(u4(w.jobId===F.job.jobId&&w.planSha256===F.planSha256&&w.jobSha256===F.jobSha256&&w.bundleSha256===F.bundleSha256,"Receipt identity differs from the exact planned job."),u4(F.runtime!==void 0&&w.runtimeSha256===F.runtimeSha256&&k(w.runtime)===k(F.runtime),"Execution receipt requires the exact planned runtime binding."),w.state==="succeeded")u4(F.readiness==="authorization-required","A successful receipt requires available observed runtime capabilities; consent remains host-owned.");u4(w.outputs.length<=F.job.limits.maximumOutputFiles&&w.outputs.reduce((X,V)=>X+V.bytes,0)<=F.job.limits.maximumOutputBytes,"Receipt exceeds the planned output budget.");let Q=Lt(F.job),Z=new Map(Q.files.map((X)=>[X.path,X])),J=new Map;for(let X of w.outputs){let V=F.job.outputs.find((Y)=>Y.id===X.outputId);if(u4(V!==void 0,"Receipt contains an undeclared output ID."),u4(X.role===V.role&&X.format===V.format,"Receipt output role or format differs from its declaration."),V.kind==="directory")u4(X.path.startsWith(`${V.path}/`)&&X.frame===void 0,"Cache artifact must be a file inside its declared directory.");else{let Y=Z.get(X.path);u4(Y!==void 0&&Y.id===X.outputId&&X.frame===Y.frame,"Receipt contains an undeclared file or incorrect frame index."),Z.delete(X.path)}J.set(X.outputId,(J.get(X.outputId)??0)+1)}if(w.state==="succeeded")u4(Z.size===0&&Q.directories.every((X)=>(J.get(X.id)??0)>0),"Successful receipt must cover every declared file, frame, and cache directory.");return l0(w)}var l91=Object.freeze({artifactSummary:xo,builtInIcons:W_,bundledSkillPath:tb,checkDiagramFile:ho,desktopDownloadPage:oq,desktopStatus:po,defineSlopcameraWorkflow:eb,DiagramValidationError:rQ,findDesktopApplication:qD,generateSlopcameraImage:_i,generateSlopcameraImageFile:KV,getLatestDesktopRelease:aq,slopcameraGatewayCredentialStatus:to,slopcameraMcpProtocolVersion:Qz,slopcameraMcpServerName:Zz,slopcameraMcpTools:kV,slopcameraOperationRegistry:d7,SlopcameraMcpToolRuntime:WZ,installDesktop:so,installSkill:wt,lintDiagram:E8,mcpMaximumRenderedPixels:n7,mcpMaximumScale:TV,mcpSourceByteLimit:x9,openInDesktop:no,parseDiagramSource:sE,parseDiagramSpec:b9,readDiagramFile:ED,renderDiagramFile:vo,renderPng:M8,renderSvg:X$,resolveEdge:iQ,resolveDiagramSource:uG,resolveStackLayout:dE,runSlopcameraWorkflow:Zt,runMcpServer:ab,searchSlopcameraOperations:tD,selectDesktopAsset:iq,serializeTldr:fF,stackLayoutDefaults:_7,StackLayoutError:eX,SlopcameraWorkflowError:J5,vectorizeImage:Q3,WorkspaceBoundary:HZ,WorkspaceBoundaryError:a1,executeSlopcameraOperation:NZ});import{z as g0}from"zod";import{randomUUID as qT0}from"crypto";import{constants as Wz}from"fs";import{open as bT0,rm as ZP}from"fs/promises";import{join as Kz}from"path";var c$=1048576,zz=67108864,Oz=67108864,JP=g0.strictObject({code:g0.string().min(1).max(128),message:g0.string().min(1).max(2048),shapeIds:g0.array(g0.string().min(1).max(128)).max(256)}),zt=g0.union([X0,Q_]),wH=g0.strictObject({path:zt}),PT0=wH.extend({path:N0}).strict(),Lz=g0.strictObject({findings:g0.array(JP).max(256),source:N0}),Gz=wH.extend({scale:g0.number().finite().positive().max(4).optional()}).strict(),Cz=Gz.extend({path:N0}).strict(),XP=g0.strictObject({darkPng:N0,darkSvg:N0,lightPng:N0,lightSvg:N0,tldr:N0}),GZ=g0.strictObject({artifacts:XP,created:g0.strictObject({darkPng:g0.boolean(),darkSvg:g0.boolean(),lightPng:g0.boolean(),lightSvg:g0.boolean(),tldr:g0.boolean()}),findings:g0.array(JP).max(256),receipt:N0,source:N0}),VP=g0.strictObject({artifacts:XP,createdAt:g0.string().datetime({offset:!0}),exactInputSha256:g0.string().regex(/^[a-f0-9]{64}$/u),findings:g0.array(JP).max(256),kind:g0.union([g0.literal("slopcamera.visual-artifact-receipt")]),operation:g0.union([g0.literal("slopcamera.diagram.render")]),scale:g0.number().finite().positive().max(4),schemaVersion:g0.literal(1),source:N0}),Dt=g0.string().regex(/^#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$/u),Dz=g0.strictObject({alphaCutoff:g0.number().int().min(1).max(64).optional(),duotone:g0.tuple([Dt,Dt]).optional(),inputPath:zt,timeoutMs:g0.number().int().min(1).max(300000).optional()}),Az=Dz.extend({inputPath:N0}).strict(),IT0=g0.strictObject({alphaRmse:g0.number().finite().nonnegative(),colorRmse:g0.number().finite().nonnegative(),outsideAlphaRatio:g0.number().finite().min(0).max(1),sampleHeight:g0.number().int().positive(),sampleWidth:g0.number().int().positive(),supportRecall:g0.number().finite().min(0).max(1)}),YP=g0.strictObject({alphaCutoff:g0.number().int().min(1).max(64),bytes:g0.number().int().positive(),candidatesEvaluated:g0.number().int().positive(),format:g0.string().min(1).max(64),height:g0.number().int().positive(),inputBytes:g0.number().int().positive(),outputMode:g0.enum(["color","duotone"]),pathCount:g0.number().int().nonnegative(),profile:g0.enum(["balanced","detailed","photo"]),provenance:g0.strictObject({arch:g0.string().min(1).max(64),platform:g0.string().min(1).max(64),sharp:g0.string().min(1).max(128),sharpVersions:g0.record(g0.string().min(1).max(128),g0.string().min(1).max(128)).superRefine((_,$)=>{if(Object.keys(_).length>64)$.addIssue({code:"custom",message:"Sharp provenance is too large."})}),vips:g0.string().min(1).max(128),vtracerSha256:g0.string().regex(/^[a-f0-9]{64}$/u),vtracerSource:g0.enum(["official-release","override"]),vtracerVersion:g0.string().min(1).max(64)}),quality:IT0,receiptVersion:g0.literal(1),representation:g0.enum(["color-paths","alpha-mask"]),sourceSha256:g0.string().regex(/^[a-f0-9]{64}$/u),svgSha256:g0.string().regex(/^[a-f0-9]{64}$/u),width:g0.number().int().positive()}),bV=g0.strictObject({artifact:N0,created:g0.boolean(),receipt:N0,source:N0,vectorizer:YP}),jP=g0.strictObject({artifact:N0,createdAt:g0.string().datetime({offset:!0}),exactInputSha256:g0.string().regex(/^[a-f0-9]{64}$/u),kind:g0.union([g0.literal("slopcamera.visual-artifact-receipt")]),operation:g0.union([g0.literal("slopcamera.image.vectorize")]),schemaVersion:g0.literal(1),source:N0,vectorizer:YP});function qV(_){return typeof _==="string"?{path:_}:_}async function Ct(_,$,F,w=new AbortController().signal){switch($){case"slopcamera.diagram.check":{let Q=wH.parse(F),Z=await A1(_,qV(Q.path),w,c$);return PT0.parse({...Q,path:Z.artifact})}case"slopcamera.diagram.render":{let Q=Gz.parse(F),Z=await A1(_,qV(Q.path),w,c$);return Cz.parse({...Q,path:Z.artifact})}case"slopcamera.image.vectorize":{let Q=Dz.parse(F),Z=await A1(_,qV(Q.inputPath),w,t_);return Az.parse({...Q,inputPath:Z.artifact})}}}function NP(_,$){if($ instanceof N)throw $;let F=$ instanceof Error?$.message:String($);throw new N("invalid-data",`${_}: ${F.slice(0,1024)}`)}async function fT0(_,$){let F={},w={},Q=[["darkPng",$.darkPng,".png"],["darkSvg",$.darkSvg,".svg"],["lightPng",$.lightPng,".png"],["lightSvg",$.lightSvg,".svg"],["tldr",$.tldr,".tldr"]];for(let[Z,J,X]of Q){let V=await Y6({context:_,extension:X,maximumBytes:zz,stagedPath:J});F[Z]=V.artifact,w[Z]=V.created}return{artifacts:XP.parse(F),created:GZ.shape.created.parse(w)}}function ST0(_,$,F){let w=$.hostResourceLease;return w===void 0?NZ("slopcamera.diagram.check",{path:_},{...F===void 0?{}:{hostResourceCoordinator:F}}):jZ("slopcamera.diagram.check",{path:_},w)}function yT0(_,$,F){let w=$.hostResourceLease;return w===void 0?NZ("slopcamera.diagram.render",_,{...F===void 0?{}:{hostResourceCoordinator:F}}):jZ("slopcamera.diagram.render",_,w)}async function At(_,$){let F=Kz(_,`.diagram-source-${qT0()}.json`),w=await bT0(F,Wz.O_CREAT|Wz.O_EXCL|Wz.O_WRONLY|(Wz.O_NOFOLLOW??0),384);try{return await w.writeFile($),await w.sync(),await w.close(),F}catch(Q){throw await w.close().catch(()=>{return}),await ZP(F,{force:!0}).catch(()=>{return}),Q}}function gT0(_={}){let $=_.checkDiagram;return{inputSchema:wH,inputSchemaId:"slopcamera.operation.diagram.check.input/v1",kind:"slopcamera.diagram.check",lifecycle:{kind:"pure",execute:async(F,w)=>{n(F.abortSignal);let Q=wH.parse(w),Z=await I4(F.application,qV(Q.path),F.abortSignal,c$),J=await W5(F),X;try{X=await At(J.path,Z.data),n(F.abortSignal);let V=await($===void 0?ST0(X,F.application,_.hostResourceCoordinator):$(X));return n(F.abortSignal),await A1(F.application,Z.artifact,F.abortSignal,c$),Lz.parse({findings:V.findings,source:Z.artifact})}catch(V){return NP("Diagram check failed",V)}finally{if(X!==void 0)await ZP(X,{force:!0}).catch(()=>{return});await J.dispose()}}},outputSchema:Lz,outputSchemaId:"slopcamera.operation.diagram.check.output/v1",policy:{cache:"content-addressed",cancellable:!1,effect:"local-read",maxDurationMs:30000,maxFanOut:0,maxInputBytes:4096,maxOutputBytes:262144,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"}],resume:"deterministic"},summarize:(F)=>({fields:{findings:F.findings.length,source:F.source.path,sourceSha256:F.source.sha256},kind:"slopcamera.diagram.check"}),version:1}}function hT0(_={}){let $=_.renderDiagram;return{inputSchema:Gz,inputSchemaId:"slopcamera.operation.diagram.render.input/v1",kind:"slopcamera.diagram.render",lifecycle:{kind:"local-artifact",execute:async(F,w)=>{let Q=Gz.parse(w),Z=await I4(F.application,qV(Q.path),F.abortSignal,c$),J=Cz.parse({...Q,path:Z.artifact}),X=await W5(F),V;try{V=await At(X.path,Z.data),n(F.abortSignal);let Y={outDirectory:Kz(X.path,"diagram"),path:V,...J.scale===void 0?{}:{scale:J.scale}},j=await($===void 0?yT0(Y,F.application,_.hostResourceCoordinator):$(Y));n(F.abortSignal),await A1(F.application,Z.artifact,F.abortSignal,c$);let H=await fT0(F,j.artifacts),K=VP.parse({artifacts:H.artifacts,createdAt:F.application.clock.now().toISOString(),exactInputSha256:S(J),findings:j.findings,kind:"slopcamera.visual-artifact-receipt",operation:"slopcamera.diagram.render",scale:J.scale??2,schemaVersion:1,source:Z.artifact}),W=await _$({context:F,receipt:K,workspace:X}),O=GZ.parse({...H,findings:j.findings,receipt:W,source:Z.artifact});return await K4(F,{inputSchemaId:"slopcamera.operation.diagram.render.input/v1",kind:"slopcamera.diagram.render",outputSchemaId:"slopcamera.operation.diagram.render.output/v1",version:1},O),O}catch(Y){return NP("Diagram render failed",Y)}finally{if(V!==void 0)await ZP(V,{force:!0}).catch(()=>{return});await X.dispose()}}},outputSchema:GZ,outputSchemaId:"slopcamera.operation.diagram.render.output/v1",policy:{cache:"content-addressed",cancellable:!1,effect:"local-derived-write",maxDurationMs:120000,maxFanOut:5,maxInputBytes:4096,maxOutputBytes:5*zz,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(F)=>F.receipt.path,summarize:(F)=>({fields:{darkPng:F.artifacts.darkPng.path,findings:F.findings.length,lightPng:F.artifacts.lightPng.path,receipt:F.receipt.path,sourceSha256:F.source.sha256},kind:"slopcamera.diagram.render"}),version:1}}function vT0(_={}){let $=_.vectorize??Q3;return{inputSchema:Dz,inputSchemaId:"slopcamera.operation.image.vectorize.input/v1",kind:"slopcamera.image.vectorize",lifecycle:{kind:"local-artifact",execute:async(F,w)=>{let Q=Dz.parse(w),Z=await A1(F.application,qV(Q.inputPath),F.abortSignal,t_),J=Az.parse({...Q,inputPath:Z.artifact}),X=await W5(F),V=Kz(X.path,"vectorized.svg");try{await F.application.hostResourceLease?.assertOwned();let Y=await $(Z.absolutePath,{cacheDirectory:Kz(F.application.paths.privateRoot,"vectorize-tool-cache-v1"),...F.application.hostResourceLease===void 0?{}:{inheritedFileDescriptors:F.application.hostResourceLease.inheritedFileDescriptors},outputPath:V,...J.alphaCutoff===void 0?{}:{alphaCutoff:J.alphaCutoff},...J.duotone===void 0?{}:{duotone:J.duotone},...J.timeoutMs===void 0?{}:{limits:{maxDurationMs:J.timeoutMs}}});if(Y.outputPath!==V)throw new N("invalid-data","Vectorization did not publish its exact staged output.");let j=YP.parse(Y.receipt);if(j.sourceSha256!==Z.artifact.sha256||j.inputBytes!==Z.artifact.bytes)throw new N("conflict","Vectorizer receipt source hash or byte length does not match the bound raster input.");let H=J.duotone===void 0?"color":"duotone";if(j.outputMode!==H)throw new N("conflict","Vectorizer receipt output mode does not match the exact color request.");let K=await Y6({context:F,extension:".svg",maximumBytes:Oz,stagedPath:V});if(j.svgSha256!==K.artifact.sha256||j.bytes!==K.artifact.bytes)throw new N("conflict","Vectorizer receipt SVG hash or byte length does not match the staged output.");let W=jP.parse({artifact:K.artifact,createdAt:F.application.clock.now().toISOString(),exactInputSha256:S(J),kind:"slopcamera.visual-artifact-receipt",operation:"slopcamera.image.vectorize",schemaVersion:1,source:Z.artifact,vectorizer:j}),O=await _$({context:F,receipt:W,workspace:X}),L=bV.parse({artifact:K.artifact,created:K.created,receipt:O,source:Z.artifact,vectorizer:j});return await K4(F,{inputSchemaId:"slopcamera.operation.image.vectorize.input/v1",kind:"slopcamera.image.vectorize",outputSchemaId:"slopcamera.operation.image.vectorize.output/v1",version:1},L),L}catch(Y){return NP("Image vectorization failed",Y)}finally{await X.dispose()}}},outputSchema:bV,outputSchemaId:"slopcamera.operation.image.vectorize.output/v1",policy:{cache:"content-addressed",cancellable:!1,effect:"local-derived-write",maxDurationMs:300000,maxFanOut:1,maxInputBytes:8192,maxOutputBytes:Oz,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(F)=>F.receipt.path,summarize:(F)=>({fields:{bytes:F.artifact.bytes,created:F.created,paths:F.vectorizer.pathCount,receipt:F.receipt.path,sha256:F.artifact.sha256,sourceSha256:F.source.sha256},kind:"slopcamera.image.vectorize"}),version:1}}var Bt=gT0(),Tt=hT0(),Ut=vT0();import{z as U1}from"zod";var kt=U1.tuple([U1.number().finite(),U1.number().finite(),U1.number().finite()]),Mt=U1.strictObject({sceneId:U1.string(),sceneSha256:W0,durationUs:x1,entities:U1.array(U1.strictObject({entityId:n2,name:U1.string(),kind:U1.enum(["group","mesh","image","diagram","video","text","light","splat"]),origin:pU,parentId:n2.nullable(),placement:YO,editableControls:U1.array(U1.enum(["color","opacity","transform"])),animatedProperties:U1.array(U1.string()),assetIds:U1.array(U1.string()),bounds:U1.discriminatedUnion("status",[U1.strictObject({status:U1.literal("authored-enclosure"),coordinateDomain:YO,atTimeUs:U1.literal(0),bounds:U1.strictObject({min:kt,max:kt})}),U1.strictObject({status:U1.literal("unknown"),reason:U1.enum(["requires-asset-decoding","requires-text-layout","no-surface"])})])})).max(4096),cameras:U1.array(wQ).max(64),assets:U1.array(U1.strictObject({assetId:U1.string(),manifestSha256:W0,manifest:O5})).max(128),generators:U1.array(jO)}),HP=(_)=>Z1(_,4194304,"scene operation",{maximumDepth:36,maximumValues:400000}).value,xT0=U1.preprocess(HP,U1.strictObject({scene:z6})),mT0=U1.preprocess(HP,U1.strictObject({scene:z6,patch:m3})),Rt=U1.strictObject({scene:z6,sceneSha256:W0,diff:U1.array(U1.strictObject({kind:U1.enum(["added","removed","changed"]),collection:U1.enum(["entities","cameras","animations","generators","overrides","assets"]),id:U1.string(),properties:U1.array(U1.string())}))}),lT0=U1.preprocess(HP,U1.strictObject({scene:z6,timeUs:x1,cameraId:U1.string(),cameraPoseOverride:x3.optional()})),WP=Object.freeze({cache:"content-addressed",cancellable:!0,effect:"pure",maxDurationMs:1e4,maxFanOut:0,maxInputBytes:4194304,maxOutputBytes:8388608,preparation:[],resources:[{amount:1,resource:"cpu"}],resume:"deterministic"}),Et={kind:"scene.inspect",version:1,inputSchema:xT0,inputSchemaId:"slopcamera.operation.scene.inspect.input/v1",outputSchema:Mt,outputSchemaId:"slopcamera.operation.scene.inspect.output/v1",policy:WP,lifecycle:{kind:"pure",execute:(_,$)=>{return n(_.abortSignal),Promise.resolve(Mt.parse(kx($.scene)))}},summarize:(_)=>({kind:"scene.inspect",fields:{sceneSha256:_.sceneSha256,entities:_.entities.length,cameras:_.cameras.length}})},qt={kind:"scene.patch",version:1,inputSchema:mT0,inputSchemaId:"slopcamera.operation.scene.patch.input/v1",outputSchema:Rt,outputSchemaId:"slopcamera.operation.scene.patch.output/v1",policy:WP,lifecycle:{kind:"pure",execute:(_,$)=>{return n(_.abortSignal),Promise.resolve(Rt.parse(OO($.scene,$.patch)))}},summarize:(_)=>({kind:"scene.patch",fields:{sceneSha256:_.sceneSha256,changes:_.diff.length}})},bt={kind:"scene.evaluate",version:1,inputSchema:lT0,inputSchemaId:"slopcamera.operation.scene.evaluate.input/v1",outputSchema:C6,outputSchemaId:"slopcamera.operation.scene.evaluate.output/v1",policy:WP,lifecycle:{kind:"pure",execute:(_,$)=>{return n(_.abortSignal),Promise.resolve(C6.parse(V8($.scene,{timeUs:$.timeUs,cameraId:$.cameraId,...$.cameraPoseOverride===void 0?{}:{cameraPoseOverride:$.cameraPoseOverride}})))}},summarize:(_)=>({kind:"scene.evaluate",fields:{sceneSha256:_.sceneSha256,viewSha256:_.viewSha256,timeUs:_.timeUs}})};import{z as D4}from"zod";import{basename as dT0,resolve as uT0}from"path";async function dF(_,$){let F=e0.parse($),w=_.spatialProjectCustody;if(w===void 0)throw new N("conflict","Spatial project access requires an existing publication lease.");if(w.projectId!==F||dT0(uT0(w.projectDirectory))!==F)throw new N("conflict","Spatial project input does not match its adapter-owned directory and lease.");return await w.assertHeld(),{projectId:F,fileSystem:L0(w.projectDirectory),durability:Z5(w.projectDirectory),custody:{assertHeld:()=>w.assertHeld(),assertLegacyTransactionSettled:()=>w.assertLegacyTransactionSettled()}}}var KP=(_)=>_ instanceof Error?_.message:String(_),cT0=(_)=>_ instanceof Error&&("code"in _)&&_.code==="ENOENT";function Bz(_){if(_?.aborted===!0)throw Error("Spatial publication cancelled before head dispatch.")}async function PV(_,$,F=D1.documentBytes){if(_.inspectFile!==void 0&&(await _.inspectFile($,F)).bytes>F)throw Error("Spatial structured byte budget exceeded.");let w=await _.readText($,F);if(new TextEncoder().encode(w).byteLength>F)throw Error("Spatial structured byte budget exceeded.");return w}async function ZH(_,$){let F=N_.parse($),w=await PV(_,F.path,F.bytes);if(t(w)!==F.sha256||new TextEncoder().encode(w).byteLength!==F.bytes)throw Error("Spatial artifact integrity mismatch.");return w}async function QH(_,$,F){if(await _.custody.assertHeld(),await R3({..._.fileSystem,readText:(w)=>_.fileSystem.readText(w,$.bytes)},$.path,F,$.sha256),await _.durability.syncExactFile($.path,$),await ZH(_.fileSystem,$)!==F)throw Error("Spatial immutable durability readback changed.")}async function Pt(_,$,F){let w=new Map,Q=0,Z=0,J=(X,V)=>{let Y=w.get(X.path);if(Y!==void 0){if(Y.bytes!==X.bytes||Y.sha256!==X.sha256)throw Error("Conflicting physical payload identity.");return}if(w.set(X.path,X),V==="source")Q+=X.bytes;else Z+=X.bytes};for(let X of $.scenes)for(let V of X.document.assets)J(V.payload,"source");for(let X of $.candidates)for(let V of X.outputs)J(V,"output");if(Q>268435456||Z>1073741824)throw Error("Spatial project payload budget exceeded.");if(w.size>0&&_.inspectFile===void 0)throw Error("Physical payload inspection is required for spatial source and candidate publication.");for(let X of w.values()){let V=await _.inspectFile?.(X.path,X.bytes);if(V===void 0||V.bytes!==X.bytes||V.sha256!==X.sha256)throw Error("Spatial physical payload integrity mismatch.");await F?.syncExactFile(X.path,X)}}async function OP(_,$,F){let w=await ZH(_,$.revision),Q=u6.parse(JSON.parse(w));if(w!==f2(Q)||dQ(Q)!==$.projectRevisionSha256||Q.projectId!==$.projectId||Q.transactionId!==$.transactionId)throw Error("Spatial head and revision binding mismatch.");O8(Q.legacy.project,Q.legacy.projectEditPlan);let Z=[];for(let X of Q.scenes){let V=await ZH(_,X.artifact),Y=A2(JSON.parse(V));if(V!==f2(Y)||x5(Y)!==X.sceneSha256)throw Error("Spatial source digest or canonical bytes mismatch.");Z.push({sceneSha256:X.sceneSha256,document:structuredClone(Y)})}let J=aX(Q,Z);return await Pt(_,J),{version:2,basis:{version:2,sha256:$.projectRevisionSha256},headText:F,head:$,revision:Q,contents:J}}async function P8(_){let $=await PV(_.fileSystem,"project.json"),F=JSON.parse($),w=U8.safeParse(F);if(w.success){if(_.projectId!==void 0&&_.projectId!==w.data.projectId)throw Error("Spatial head belongs to another project.");if($!==f2(w.data))throw Error("Noncanonical spatial head.");return await OP(_.fileSystem,w.data,$)}let Q=j1.parse(F);if(_.projectId!==void 0&&_.projectId!==Q.projectId)throw Error("Legacy head belongs to another project.");await _.custody.assertLegacyTransactionSettled();let Z=B1.parse(JSON.parse(await PV(_.fileSystem,"edits/current.json")));return O8(Q,Z),{version:1,basis:{version:1,sha256:H9(Q,Z).generationSha256},headText:$,contents:{legacy:{project:Q,projectEditPlan:Z},scenes:[],shots:[],candidates:[],selections:[]}}}async function DZ(_){let{ports:$}=_,F,w=!1;try{await $.custody.assertHeld(),Bz(_.signal);let Q=H_.parse(_.expected),Z=rX.parse(_.transactionId);if($.fileSystem.writeTextAtomicGuarded===void 0)throw Error("Spatial head publication requires the guarded atomic-replace capability.");let J=await P8($);if(k(J.basis)!==k(Q))return{kind:"conflict",message:"Expected complete project revision is stale."};let X=iX(_.change(J)),V=X.scenes.map((z)=>({sceneSha256:z.sceneSha256,artifact:R9("scenes",f2(z.document))})),Y=u6.parse({kind:"slopcamera.spatial-project-revision",schemaVersion:2,projectId:J.contents.legacy.project.projectId,parent:Q,transactionId:Z,legacy:X.legacy,scenes:V,shots:X.shots,candidates:X.candidates,selections:X.selections});await Pt($.fileSystem,X,$.durability);for(let z of X.scenes){let C=f2(z.document);await QH($,R9("scenes",C),C)}let j=f2(Y),H=R9("revisions",j);await QH($,H,j);let K=U8.parse({kind:"slopcamera.spatial-project-head",schemaVersion:2,projectId:Y.projectId,projectRevisionSha256:dQ(Y),revision:H,transactionId:Z}),W=f2(RE.parse({kind:"slopcamera.spatial-project-attempt",schemaVersion:1,beforeHeadSha256:t(J.headText),expected:Q,after:K}));F=R9("attempts",W),await QH($,F,W),await $.custody.assertHeld(),Bz(_.signal);let O=await P8($);if(k(O.basis)!==k(Q)||O.headText!==J.headText)return{kind:"conflict",attempt:F,message:"Project changed before publication."};let L=f2(K);if(await $.custody.assertHeld(),Bz(_.signal),await $.fileSystem.writeTextAtomicGuarded("project.json",L,async()=>{await $.custody.assertHeld(),Bz(_.signal),w=!0}),await $.durability.syncExactFile("project.json",{bytes:new TextEncoder().encode(L).byteLength,sha256:t(L)}),await PV($.fileSystem,"project.json")!==L)throw Error("Spatial head readback mismatch.");await OP($.fileSystem,K,L);let G=ft(F,L),D=R9("receipts",G);return await QH($,D,G),{kind:"completed",attempt:F,settlement:D,projectRevisionSha256:K.projectRevisionSha256,currentHeadMatches:!0}}catch(Q){if(w&&F!==void 0)return{kind:"ambiguous",attempt:F,message:KP(Q)};return{kind:"precommit",message:KP(Q),...F===void 0?{}:{attempt:F}}}}async function It(_){return await DZ({..._,change($){if($.version!==1)throw Error("Spatial migration requires an existing V1 authority.");return{...$.contents,scenes:_.scenes,shots:_.shots}}})}function ft(_,$){return f2(sp.parse({kind:"slopcamera.spatial-project-settlement",schemaVersion:1,attempt:_,headSha256:t($)}))}async function St(_){let{ports:$}=_,F=N_.parse(_.attempt);try{if(await $.custody.assertHeld(),!F.path.startsWith("spatial/attempts/"))throw Error("Reconciliation requires an immutable attempt reference.");let w=await ZH($.fileSystem,F),Q=RE.parse(JSON.parse(w));if($.projectId!==void 0&&$.projectId!==Q.after.projectId)throw Error("Spatial attempt belongs to another project.");if(w!==f2(Q))throw Error("Noncanonical spatial attempt.");let Z=f2(Q.after),J=ft(F,Z),X=R9("receipts",J),V=await OP($.fileSystem,Q.after,Z);if(k(V.revision.parent)!==k(Q.expected))throw Error("Spatial attempt does not bind its revision parent.");let Y=!1;try{if(await ZH($.fileSystem,X)!==J)throw Error("Spatial settlement receipt mismatch.");await $.durability.syncExactFile(X.path,X),Y=!0}catch(H){if(!cT0(H))throw H}let j=await PV($.fileSystem,"project.json")===Z;if(!Y){if(!j)throw Error("No durable completion proof and current head differs; rollback and replay are forbidden.");if(await $.durability.syncExactFile("project.json",{bytes:new TextEncoder().encode(Z).byteLength,sha256:t(Z)}),await PV($.fileSystem,"project.json")!==Z)throw Error("Spatial head changed during reconciliation.");await QH($,X,J)}return{kind:"completed",attempt:F,settlement:X,projectRevisionSha256:Q.after.projectRevisionSha256,currentHeadMatches:j}}catch(w){return{kind:"ambiguous",attempt:F,message:KP(w)}}}var IV={project:e0,expected:H_,transactionId:rX};function uF(_,$=D1.documentBytes){return D4.preprocess((F)=>Z1(F,$,"spatial operation input",{maximumDepth:48,maximumValues:2000000}).value,_)}var yt=uF(D4.strictObject({project:e0,expected:H_.optional()}),1024),sT0=uF(D4.strictObject({...IV,scenes:D4.array(c6).max(D1.scenes),shots:D4.array(v5).max(D1.shots)})),pT0=uF(D4.strictObject({...IV,patch:m3,retarget:uN})),nT0=uF(D4.strictObject({...IV,expectedSceneSha256:W0,restoreSceneSha256:W0,retarget:uN})),rT0=uF(D4.strictObject({...IV,shot:v5,source:c6.optional()})),oT0=uF(D4.strictObject({...IV,candidate:lQ})),iT0=uF(D4.strictObject({...IV,candidateId:PG})),aT0=uF(D4.strictObject({project:e0,attempt:N_.refine((_)=>_.path.startsWith("spatial/attempts/"))})),gt={projectId:e0,basis:H_,legacy:dN,scenes:D4.array(c6).max(D1.scenes),shots:D4.array(v5).max(D1.shots),candidates:D4.array(lQ).max(D1.candidates),selections:D4.array(oX.extend({status:D4.enum(["current","stale"])})).max(D1.shots)},Tz=D4.discriminatedUnion("version",[D4.strictObject({...gt,version:D4.literal(1)}),D4.strictObject({...gt,version:D4.literal(2),head:U8})]).superRefine((_,$)=>{if(_.basis.version!==_.version||_.version===2&&_.head.projectRevisionSha256!==_.basis.sha256)$.addIssue({code:"custom",message:"Snapshot basis must match its exact authority version and head."})});async function cF(_,$,F="write"){let w=await dF(_.application,$);return{...w,custody:{...w.custody,assertHeld:async()=>{if(await w.custody.assertHeld(),F==="write")await _.workflow?.beforePublication()}}}}function JH(_){if(_.version!==2)throw new N("conflict","This mutation requires V2 spatial authority; migrate the checked V1 project first.");return _.contents}var ht={cache:"none",cancellable:!0,effect:"project-mutation",maxDurationMs:120000,maxFanOut:0,maxInputBytes:D1.documentBytes,maxOutputBytes:2097152,preparation:["project-state"],resources:[{amount:1,resource:"local-io"},{amount:1,resource:"project-publication"}],resume:"ambiguous-after-dispatch"};function zZ(_,$,F){return{kind:_,version:1,inputSchema:$,inputSchemaId:`slopcamera.operation.${_}.input/v1`,outputSchema:T5,outputSchemaId:`slopcamera.operation.${_}.output/v1`,lifecycle:{kind:"project-transaction",execute:async(w,Q)=>await F(w,$.parse(Q))},policy:ht,receiptReference:(w)=>w.kind==="completed"?w.settlement.path:void 0,summarize:(w)=>({kind:_,fields:{disposition:w.kind,...w.kind==="completed"?{projectRevisionSha256:w.projectRevisionSha256}:{message:w.message}}})}}var vt={kind:"spatial.project.snapshot",version:1,inputSchema:yt,inputSchemaId:"slopcamera.operation.spatial.project.snapshot.input/v1",outputSchema:Tz,outputSchemaId:"slopcamera.operation.spatial.project.snapshot.output/v1",lifecycle:{kind:"local-artifact",execute:async(_,$)=>{let F=yt.parse($);if(_.abortSignal.aborted)throw new N("cancelled","Spatial snapshot cancelled.");let w=await cF(_,F.project,"read"),Q=await P8(w);if(await w.custody.assertHeld(),_.abortSignal.aborted)throw new N("cancelled","Spatial snapshot cancelled.");if(F.expected!==void 0&&k(F.expected)!==k(Q.basis))throw new N("conflict","Spatial snapshot basis is stale.");let Z=Tz.parse({projectId:Q.contents.legacy.project.projectId,version:Q.version,basis:Q.basis,...Q.contents,selections:Q.contents.selections.map((J)=>{let X=Q.contents.candidates.find((V)=>V.candidateId===J.candidateId);if(X===void 0)throw new N("invalid-data","Selected spatial candidate is absent.");return{...J,status:pN(Q.contents,X)}}),...Q.version===2?{head:Q.head}:{}});if(new TextEncoder().encode(f2(Z)).byteLength>D1.documentBytes)throw new N("invalid-data","Spatial snapshot exceeds its 32 MiB output budget.");return Z}},policy:{...ht,effect:"local-read",cache:"none",maxInputBytes:1024,maxOutputBytes:D1.documentBytes,resume:"deterministic"},summarize:(_)=>({kind:"spatial.project.snapshot",fields:{projectId:_.projectId,version:_.version,projectRevisionSha256:_.basis.sha256,scenes:_.scenes.length,shots:_.shots.length}})},xt=zZ("spatial.project.migrate",sT0,async(_,$)=>{let F=await cF(_,$.project);return T5.parse({projectId:$.project,...await It({ports:F,expected:$.expected,transactionId:$.transactionId,scenes:$.scenes,shots:$.shots,signal:_.abortSignal})})}),mt=zZ("spatial.project.patch",pT0,async(_,$)=>{let F=await cF(_,$.project),w,Q=await DZ({ports:F,expected:$.expected,transactionId:$.transactionId,signal:_.abortSignal,change:(Z)=>{let J=ep(JH(Z),$.patch,$.retarget);return w=J.diff,J.contents}});return T5.parse({projectId:$.project,...Q,...Q.kind==="completed"&&w!==void 0?{diff:w}:{}})}),lt=zZ("spatial.project.restore",nT0,async(_,$)=>{let F=await cF(_,$.project),w,Q=await DZ({ports:F,expected:$.expected,transactionId:$.transactionId,signal:_.abortSignal,change:(Z)=>{let J=_n(JH(Z),$.expectedSceneSha256,$.restoreSceneSha256,$.retarget);return w=J.diff,J.contents}});return T5.parse({projectId:$.project,...Q,...Q.kind==="completed"&&w!==void 0?{diff:w}:{}})}),dt=zZ("spatial.project.add-shot",rT0,async(_,$)=>{let F=await cF(_,$.project);return T5.parse({projectId:$.project,...await DZ({ports:F,expected:$.expected,transactionId:$.transactionId,signal:_.abortSignal,change:(w)=>{let Q=JH(w);if(Q.shots.some((J)=>J.shotId===$.shot.shotId))throw new N("conflict","Shot identity already exists.");let Z=Q.scenes;if($.source!==void 0){let J=A2($.source.document),X=x5(J);if(X!==$.source.sceneSha256||X!==$.shot.sceneSha256)throw new N("invalid-data","New shot must bind its exact source scene.");if(!Z.some((V)=>V.sceneSha256===X))Z=[...Z,{document:J,sceneSha256:X}]}return{...Q,scenes:Z,shots:[...Q.shots,$.shot]}}})})}),ut=zZ("spatial.project.add-candidate",oT0,async(_,$)=>{let F=await cF(_,$.project);return T5.parse({projectId:$.project,...await DZ({ports:F,expected:$.expected,transactionId:$.transactionId,signal:_.abortSignal,change:(w)=>$n(JH(w),$.candidate)})})}),ct=zZ("spatial.project.select-candidate",iT0,async(_,$)=>{let F=await cF(_,$.project);return T5.parse({projectId:$.project,...await DZ({ports:F,expected:$.expected,transactionId:$.transactionId,signal:_.abortSignal,change:(w)=>Fn(JH(w),$.candidateId)})})}),st=zZ("spatial.project.reconcile",aT0,async(_,$)=>{let F=await cF(_,$.project);return T5.parse({projectId:$.project,...await St({ports:F,attempt:$.attempt})})});import{constants as Uz}from"fs";import{mkdtemp as tT0,open as eT0,rm as _U0}from"fs/promises";import{dirname as rt,join as CZ,posix as pt,relative as kz}from"path";import{z as V2}from"zod";var GP=268435456,ot=V2.strictObject({assetId:w4,artifact:N0}),it=V2.strictObject({source:Q_,assets:V2.array(ot).max(R1.assets).optional(),request:Q7,sceneSha256:W0.optional(),capabilityBindings:C5.optional(),browserRuntime:AF.optional()}),at=(_)=>Z1(_,16777216,"spatial render request",{maximumDepth:48,maximumValues:500000}).value,tt=V2.preprocess(at,it),Mz=V2.preprocess(at,it.extend({source:N0,assets:V2.array(ot).max(R1.assets),sceneSha256:W0,capabilityBindings:C5,browserRuntime:AF}));function BP(_){try{return A2(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(_)))}catch($){throw new N("invalid-data",`Invalid spatial source: ${$ instanceof Error?$.message:String($)}`)}}async function TP(_,$,F=new AbortController().signal,w=BF){let Q=tt.parse($),Z=await I4(_,Q.source,F,R1.sourceBytes),J=BP(Z.data),X=f9(J,Q.request),V=x5(J);if(Q.sceneSha256!==void 0&&Q.sceneSha256!==V)throw new N("conflict","Scene source changed after planning.");if(J.assets.reduce((W,O)=>W+O.payload.bytes,0)>GP)throw new N("invalid-data","Scene asset closure exceeds 256 MiB.");let Y=Q.assets===void 0?void 0:new Map(Q.assets.map((W)=>[W.assetId,W.artifact]));if(Y!==void 0&&(Y.size!==Q.assets.length||Y.size!==J.assets.length||J.assets.some((W)=>!Y.has(W.assetId))))throw new N("invalid-data","Asset bindings must name every declared asset exactly once.");let j=[];for(let W of J.assets){let O=Y?.get(W.assetId)??{...W.payload,path:pt.join(pt.dirname(Z.artifact.path),W.payload.path)};if(O.sha256!==W.payload.sha256||O.bytes!==W.payload.bytes)throw new N("conflict",`Asset ${W.assetId} does not match its source manifest.`);let L=await A1(_,O,F,W.payload.bytes);j.push({assetId:W.assetId,artifact:L.artifact})}let H=await d5(_,QV(X),Q.capabilityBindings),K=await w(w$(H,"html-browser"),F);if(Q.browserRuntime!==void 0&&k(Q.browserRuntime)!==k(K))throw new N("conflict","Browser runtime changed after scene planning.");return Mz.parse({...Q,source:Z.artifact,assets:j,sceneSha256:V,capabilityBindings:H,browserRuntime:K})}async function nt(_,$){let F=await eT0(_,Uz.O_CREAT|Uz.O_EXCL|Uz.O_WRONLY|Uz.O_NOFOLLOW,384);try{await F.writeFile($),await F.sync()}finally{await F.close()}}var XH={kind:"scene.render",version:1,inputSchemaId:"slopcamera.operation.scene.render.input/v1",outputSchemaId:"slopcamera.operation.scene.render.output/v1"},DP="spatial-render-attempt.v1.json",zP="spatial-render-result.v1.json",fV=2097152,Rz=V2.strictObject({kind:V2.literal("scene.render"),version:V2.literal(1),inputSchemaId:V2.literal(XH.inputSchemaId),outputSchemaId:V2.literal(XH.outputSchemaId),nodeKey:V2.string().min(1).max(255),nodePlanSha256:W0,runId:V2.string().min(1).max(256)}),et={schemaVersion:V2.literal(1),identity:Rz,inputSha256:W0},_e=V2.strictObject({...et,kind:V2.literal("slopcamera.spatial-render-operation-attempt"),originalSceneArtifact:N0}),CP=V2.strictObject({...et,kind:V2.literal("slopcamera.spatial-render-operation-result"),output:i6});function AP(_,$){return N0.parse({bytes:$.bytes,sha256:$.sha256,path:kz(_.paths.repositoryRoot,CZ(rt(_.paths.artifactRoot),"generated/media-operations/outputs",`${$.sha256}.json`))})}function $U0(_){let $=_.workflow;return $===void 0?void 0:Rz.parse({...XH,nodeKey:$.nodeKey,nodePlanSha256:$.nodePlanSha256,runId:$.runId})}async function LP(_,$,F,w){let Q=`${k(w)}
1777
1777
  `,Z=new TextEncoder().encode(Q).length;if(Z>fV)throw new N("invalid-data","Spatial render recovery marker exceeds its byte budget.");let J=t(Q),X=await R3(L0($),F,Q,J);return await Z5(_.paths.repositoryRoot).syncExactFile(kz(_.paths.repositoryRoot,CZ($,F)),{bytes:Z,sha256:J}),X}async function FU0(_,$,F={}){if(_.workflow!==void 0)Mz.parse($);let w=await TP(_.application,$,_.abortSignal,F.bindBrowserRuntime),Q=await I4(_.application,w.source,_.abortSignal,R1.sourceBytes),Z=BP(Q.data),J=$U0(_),X=S(w),V,Y,j,H,K="preparation",W,O=!1,L=!1,G=[],D=[],z=async()=>{await _.application.hostResourceLease?.assertOwned(),n(_.abortSignal)};try{if(V=await(F.createWorkspace??W5)(_),J!==void 0){if(await _.workflow.beforePublication(),await z(),await LP(_.application,V.path,DP,_e.parse({kind:"slopcamera.spatial-render-operation-attempt",schemaVersion:1,identity:J,inputSha256:X,originalSceneArtifact:AP(_.application,Q.artifact)}))==="exists")throw new N("ambiguous","This exact spatial render attempt already started; reconcile its retained evidence instead of rendering again.")}Y=await(F.createDirectory??tT0)(CZ(V.path,"spatial-source-"));let C=await I0(Y,"assets"),A=new Map;for(let M of Z.assets){let R=w.assets.find((f)=>f.assetId===M.assetId).artifact,g=await I4(_.application,R,_.abortSignal,M.payload.bytes),U=A.get(M.payload.path);if(U!==void 0){if(U!==R.sha256)throw new N("conflict","Two scene assets declare different bytes at one path.");continue}let E=rt(M.payload.path);if(E!==".")await I0(C,E);await nt(CZ(C,M.payload.path),g.data),A.set(M.payload.path,R.sha256)}let B=CZ(Y,"original.scene.json");await nt(B,Q.data),K="source-publication",H=AP(_.application,Q.artifact);let T=(await(F.publishOriginal??Y6)({context:_,beforePublication:z,extension:".json",stagedPath:B,maximumBytes:R1.sourceBytes})).artifact;if(k(T)!==k(H))throw new N("incompatible","Published original spatial source differs from its prospective content address.");if(await Z5(_.application.paths.repositoryRoot).syncExactFile(T.path,T),D.push(T),H=void 0,K="render",j=i6.parse(Z1(await(F.render??XD)(_,{scene:Z,assetRoot:C,request:w.request,originalSceneArtifact:T,capabilityBindings:w.capabilityBindings,browserRuntime:w.browserRuntime}),fV,"completed spatial render").value),K="checkpoint",J!==void 0)L=!0,await LP(_.application,V.path,zP,CP.parse({kind:"slopcamera.spatial-render-operation-result",schemaVersion:1,identity:J,inputSha256:X,output:j}));await(F.checkpoint??K4)(_,XH,j)}catch(C){if(W=C,O=!0,C instanceof JD){if(H??=C.evidence.uncertainPublication,j===void 0&&C.evidence.completion!==void 0)j=i6.parse(Z1(C.evidence.completion,fV,"spatial failure completion").value)}if(j!==void 0&&J!==void 0&&V!==void 0&&!L){L=!0;try{await LP(_.application,V.path,zP,CP.parse({kind:"slopcamera.spatial-render-operation-result",schemaVersion:1,identity:J,inputSha256:X,output:j}))}catch(A){G.push(A)}}}finally{if(Y!==void 0)try{await(F.removeDirectory??(async(C)=>{await _U0(C,{recursive:!0,force:!0})}))(Y)}catch(C){G.push(C)}if(V!==void 0)try{await V.dispose()}catch(C){G.push(C)}}if(O||G.length>0){let C=G.length===0?W:AggregateError([...O?[W]:[],...G],"Spatial render operation failed during execution or cleanup."),A={stage:O?K:"cleanup",retainedInputArtifacts:D,...H===void 0?{}:{uncertainPublication:H},...j===void 0?{}:{completion:j},...J===void 0||V===void 0?{}:{attemptPath:kz(_.application.paths.repositoryRoot,CZ(V.path,DP))},...W instanceof N?{causeDetails:W.details}:{}},B=new N(H!==void 0||j!==void 0?"ambiguous":W instanceof N?W.code:"internal",C instanceof Error?C.message:"Spatial rendering failed.",{spatialRenderOperation:A,cleanupErrors:G.map((T)=>T instanceof Error?T.message:String(T))});throw B.cause=C,B}if(j===void 0)throw new N("internal","Spatial rendering completed without an output.");return j}async function $e(_,$,F,w,Q){n(Q);let Z=Mz.parse($),J=Rz.parse(Z1(F,2048,"spatial recovery identity").value),X=await W5({application:_,abortSignal:Q,workflow:{...J,workspaceDirectory:w,beforePublication:async()=>{throw new N("internal","Read-only spatial attempt recovery must not publish.")}}}),V=L0(X.path),Y=async(L)=>{let G;try{G=await V.readText(L,fV)}catch(z){if(z instanceof Error&&"code"in z&&z.code==="ENOENT")return;throw z}let D=Z1(JSON.parse(G),fV,"spatial recovery marker").value;if(G!==`${k(D)}
1778
1778
  `)throw new N("incompatible","Spatial recovery marker is not canonical immutable JSON.");return await Z5(_.paths.repositoryRoot).syncExactFile(kz(_.paths.repositoryRoot,CZ(X.path,L)),{bytes:new TextEncoder().encode(G).length,sha256:t(G)}),D},j=await Y(DP);if(j===void 0)return{kind:"retry"};let H=_e.parse(j);if(k(H.identity)!==k(J)||H.inputSha256!==S(Z)||k(H.originalSceneArtifact)!==k(AP(_,Z.source)))throw new N("incompatible","Spatial attempt belongs to another exact execution or input.");let K=await Y(zP);if(n(Q),K===void 0)return{kind:"ambiguous",message:"Spatial rendering started but has no verified completion; preserve its original source and immutable artifacts. Automatic replay is disabled."};let W=CP.parse(K);if(k(W.identity)!==k(J)||W.inputSha256!==H.inputSha256)throw new N("incompatible","Spatial retained result belongs to another exact execution.");let O=await UP(_,Z,W.output,J,Q);return{kind:"completed",output:O,receiptReference:O.receipt.path,summary:{artifactSha256:O.artifact.sha256,frameCount:O.render.frameCount}}}var Fe={...XH,inputSchema:tt,outputSchema:i6,lifecycle:{kind:"local-artifact",execute:FU0},policy:{cache:"exact-run",cancellable:!0,effect:"local-derived-write",maxDurationMs:900000,maxFanOut:0,maxInputBytes:16777216,maxOutputBytes:2097152,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"},{amount:1,resource:"browser"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(_)=>_.receipt.path,summarize:(_)=>({kind:"scene.render",fields:{artifactSha256:_.artifact.sha256,frameCount:_.render.frameCount}})};async function UP(_,$,F,w,Q){n(Q);let Z=Rz.parse(Z1(w,2048,"spatial recovery identity").value),J=Mz.parse($),X=i6.parse(Z1(F,fV,"spatial recovery output").value),V=(A,B,T)=>{if(A===void 0||B===void 0){if(A!==B)throw new N("incompatible",T);return}if(k(A)!==k(B))throw new N("incompatible",T)},Y=Z5(_.paths.repositoryRoot),j=async(A,B)=>{n(Q);let T=await I4(_,A,Q,B),M=new TextDecoder("utf-8",{fatal:!0}).decode(T.data),R=Z1(JSON.parse(M),B,"spatial immutable recovery JSON",{maximumDepth:48,maximumValues:2000000}).value;if(M!==`${k(R)}
@@ -4653,7 +4653,7 @@ def lesson_from_context(context):
4653
4653
  `;function VR0(_){let $=_.startsWith("blender-")?"blender":_==="cadquery-bracket"?"cadquery":"manim",F=$==="blender"?{"scene.py":{"blender-product":v00,"blender-character":II,"blender-shaded-street":x00,"blender-cloth":m00,"blender-fluid":l00}[_],"studio_scene.py":d00,..._==="blender-shaded-street"?{"character.py":II}:{}}:$==="cadquery"?{"scene.py":u00}:{"scene.py":c00,"lesson.json":y1(s00),"lesson.py":p00,"toolkit.py":n00},w={engine:$,entrypoint:{kind:"python",path:"scene.py"},files:Object.keys(F).sort()},Q=X3({kind:"slopcamera.studio-source-bundle",schemaVersion:1,engine:$,entrypoint:w.entrypoint,files:Object.entries(F).map(([j,H])=>({path:j,bytes:Buffer.byteLength(H),sha256:aF(H)}))}),Z={kind:"raster",colorSpace:"srgb",alpha:"opaque",dataType:"uint8",channels:["R","G","B"],semantic:"color",unit:"unitless"},J=_==="blender-cloth"||_==="blender-fluid",X=_==="blender-shaded-street",V=$==="cadquery"?[{id:"solid",kind:"file",role:"model",format:"step",path:"model.step",interpretation:{kind:"model",sourceSpace:{units:"millimeters",upAxis:"z",handedness:"right"}}},{id:"preview",kind:"file",role:"model",format:"glb",path:"model.glb",interpretation:{kind:"model",sourceSpace:{units:"meters",upAxis:"y",handedness:"right"}}}]:J?[{id:"native",kind:"file",role:"native-source",format:"blend",path:"native/scene.blend",interpretation:{kind:"native-source"}},{id:"cache",kind:"directory",role:"simulation-cache",format:"cache",path:"cache",interpretation:{kind:"cache",semantics:"opaque-native"}}]:[{id:"beauty",kind:"sequence",role:"beauty",format:"png",pathPattern:"frames/%06d.png",interpretation:Z},...$==="manim"?[{id:"movie",kind:"file",role:"beauty",format:"mp4",path:"lesson.mp4",interpretation:Z}]:[{id:"native",kind:"file",role:"native-source",format:"blend",path:"native/scene.blend",interpretation:{kind:"native-source"}}]],Y=V3({kind:"slopcamera.studio-job",schemaVersion:1,jobId:`studio_${_.replaceAll("-","_")}_${wR0()}`,bundleSha256:LZ(Q),stage:$==="cadquery"?"build":J?"bake":"render",parameters:$==="manim"?{lessonFile:"lesson.json"}:X?{shot:"establish",motion:"approach"}:{},engine:$==="blender"?{engine:$,renderer:"cycles",device:"gpu",samples:X?16:32,transparent:!1,viewTransform:X?"Standard":"AgX",denoise:!0,seed:0}:$==="manim"?{engine:$,scene:"PythagoreanLesson",renderer:"cairo",transparent:!1}:{engine:$,exportVariable:"model",tolerance:0.05,angularTolerance:0.1},...$==="cadquery"?{}:{render:{width:$==="manim"?480:X?360:640,height:$==="manim"?854:X?640:360,frameRate:{numerator:24,denominator:1},startFrame:J||X?1:0,endFrameExclusive:$==="manim"?240:_==="blender-cloth"?41:_==="blender-fluid"?33:X?73:72}},outputs:V,limits:{timeoutSeconds:900,maximumOutputBytes:2147483648,maximumOutputFiles:2048},execution:{trust:"trusted-current-user",isolation:"none",hermetic:!1}});return{source:w,bundle:Q,job:Y,files:F}}async function o00(_,$,F){let w=XR0(_),Q=await JR0(r00(w)),Z=wC(Q,w.slice(r00(w).length+1));if(await F(),await ZR0(Z,{mode:448}),!(await QR0(Z)).isDirectory())throw Error("Studio scaffold directory changed.");let J=VR0($),X=L0(Z);for(let[V,Y]of Object.entries(J.files))await X.writeTextNoReplace(V,Y,F);return await X.writeTextNoReplace("source.json",y1(J.source),F),await X.writeTextNoReplace("job.json",y1(J.job),F),{directory:Z,template:$,jobId:J.job.jobId,bundleSha256:J.job.bundleSha256,executed:!1,source:wC(Z,"source.json"),job:wC(Z,"job.json"),next:["Edit the retained source and job as needed.",`slopcamera studio bundle ${JSON.stringify(wC(Z,"source.json"))} --json`,"After editing source, bind the returned bundleSha256 into a new job ID before running."]}}var NR0=QC.strictObject({engine:Xz,entrypoint:QC.strictObject({kind:QC.enum(["python","blend"]),path:U4}),files:QC.array(U4).min(1).max(512)});async function i00(_,$,F){let w=async()=>{await _.hostResourceLease?.assertOwned()};if(F.aborted)throw new N("cancelled","Studio command cancelled.");if($.action==="assets"){let X=await I0(_.paths.repositoryRoot,"artifacts/slopcamera/generated/studio-assets/poly-haven"),V=C00({storageRoot:X,signal:F,beforePublication:w});if($.operation==="describe")return await V.describe($.path);let Y=await s5(Fw(_.paths.repositoryRoot,$.path),16777216);return $.operation==="search"?await V.search(Y):$.operation==="plan"?await V.plan(Y):await V.importAsset(Y)}if($.action==="init")return await o00(Fw(_.paths.repositoryRoot,$.path),$.template,w);if($.action==="bundle"){let X=Fw(_.paths.repositoryRoot,$.path),V=NR0.parse(await s5(X,1048576)),Y=$.sourceRoot===void 0?YR0(X):Fw(_.paths.repositoryRoot,$.sourceRoot),j=await W00({...V,sourceRoot:Y}),H=await W$(_),K=await K00({studioRoot:H,sourceRoot:Y,bundle:j,fence:w});return{bundle:K.bundle,bundleSha256:K.bundleSha256,manifest:jR0(_.paths.repositoryRoot,Fw(K.sourceRoot,"../bundle.json")),executed:!1,next:"Bind bundleSha256 into a new job ID after source edits, then use studio plan and studio run."}}let Q={threads:1,...$.action!=="probe"&&$.action!=="run"?{}:{...$.blender===void 0?{}:{blender:Fw(_.paths.repositoryRoot,$.blender)},...$.python===void 0?{}:{python:Fw(_.paths.repositoryRoot,$.python)}}},Z=_C({application:_,selection:Q});if($.action==="asset")return await h00({application:_,service:Z,selection:{jobId:$.id,outputId:$.outputId,representation:$.representation,...$.frame===void 0?{}:{frame:$.frame}},assetId:$.assetId,signal:F,beforePublication:w});if($.action==="assemble")return await P00({application:_,service:Z,jobId:$.id,outputId:$.outputId,signal:F,beforePublication:w,...$.title===void 0?{}:{title:$.title}});if($.action==="encode")return await $C({application:_,service:Z,jobId:$.id,outputId:$.outputId,signal:F,beforePublication:w});if($.action==="inspect")return await Z.inspect($.id);if($.action==="reconcile")return await Z.reconcile($.id,w);let J=await s5(Fw(_.paths.repositoryRoot,$.path),1048576);if($.action==="plan")return await Z.plan(J);if($.action==="probe")return await Z.bind(J,F);if(!$.allowTrustedCode)throw new N("authorization-required","Studio execution requires explicit trusted-code authorization.");return await Z.run(J,{signal:F,allowTrustedCode:!0,beforePublication:w,..._.hostResourceLease===void 0?{}:{inheritedFileDescriptors:_.hostResourceLease.inheritedFileDescriptors}})}import{resolve as a00}from"path";function oV(_,$){let F=$.studio;if(F===void 0)return _;let w=_C({application:_,selection:{threads:1,...F.python===void 0?{}:{python:a00(_.paths.repositoryRoot,F.python)},...F.blender===void 0?{}:{blender:a00(_.paths.repositoryRoot,F.blender)}}});return{..._,studioPort:w.port,...F.allowTrustedCode?{studioAuthorization:{authorize:async(Q)=>/^studio_[a-zA-Z0-9][a-zA-Z0-9_-]{0,120}$/u.test(Q.jobId)&&/^[a-f0-9]{64}$/u.test(Q.planSha256)&&/^[a-f0-9]{64}$/u.test(Q.bundleSha256)}}:{}}}import{randomUUID as B10}from"crypto";import{lstat as rR0,mkdir as oR0,readFile as iR0,rename as aR0,rm as aV,stat as tR0,writeFile as eR0}from"fs/promises";import{join as lI}from"path";import{z as u}from"zod";var g8=4,$10="0.4.0",t00=65536,fI=16,HR0=32,WR0=64,JC=128;var F10=u.string().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u),w10=(_)=>new TextEncoder().encode(_).byteLength,VC=(_)=>u.string().min(1).refine(($)=>w10($)<=_&&!$.includes("\x00"),`Expected a non-NUL string of at most ${String(_)} UTF-8 bytes.`),KR0=VC(512),OR0=u.string().min(1).regex(/^[1-9][0-9]*$/u).refine((_)=>w10(_)<=32&&!_.includes("\x00"),"Expected a positive decimal window ID of at most 32 UTF-8 bytes."),LR0=VC(256),Q10=u.string().min(1).max(4096),X4=u.number().int().safe().nonnegative(),p$=X4.positive(),XC=u.number().int().safe(),Z10=u.number().int().positive().max(2147483647),GR0=u.string().min(1).max(4096).superRefine((_,$)=>{if(!_.startsWith("/")||_.includes("\x00")){$.addIssue({code:"custom",message:"Expected an absolute macOS path."});return}if(_.split("/").some((F)=>F==="."||F===".."))$.addIssue({code:"custom",message:"Absolute paths may not contain dot segments."})}),YC=u.string().min(1).max(1024).superRefine((_,$)=>{if(_.startsWith("/")||_.startsWith("\\")||_.includes("\\")||_.includes("\x00")||_.split("/").some((F)=>F.length===0||F==="."||F===".."))$.addIssue({code:"custom",message:"Expected a normalized session-relative output path."})}),J10={protocolVersion:u.literal(g8),requestId:F10},DR0=u.strictObject({fieldId:KR0,processId:Z10,windowId:OR0,windowTitle:LR0}),qH=u.array(DR0).max(16).superRefine((_,$)=>{let F=_.map((w)=>`${w.processId}\x00${w.windowId}\x00${w.fieldId}\x00${w.windowTitle}`);if(new Set(F).size!==F.length)$.addIssue({code:"custom",message:"Typed-text focus identities must be unique."})}),bH=u.discriminatedUnion("kind",[u.strictObject({kind:u.literal("all")}),u.strictObject({displayIds:u.array(VC(64)).min(1).max(fI).superRefine((_,$)=>{if(new Set(_).size!==_.length)$.addIssue({code:"custom",message:"Selected display IDs must be unique."})}),kind:u.literal("selected")})]),Qw=u.discriminatedUnion("kind",[u.strictObject({kind:u.literal("disabled")}),u.strictObject({kind:u.literal("default")}),u.strictObject({deviceId:VC(256),kind:u.literal("device")})]),X10=u.strictObject({camera:Qw.default({kind:"default"}),displays:bH.default({kind:"all"}),metadata:u.boolean().default(!0),microphone:Qw.default({kind:"default"}),interactionEventProcessIdentifier:Z10.nullable().default(null),strictSources:u.boolean().default(!1),systemAudio:u.boolean().default(!0),typedText:u.boolean().default(!1),typedTextFocusIdentities:qH.nullable().default(null),excludedBundleIdentifiers:u.array(u.string().min(1).max(256)).max(16).default(["com.hraness.slopcamera"])}),zR0=u.strictObject({...J10,command:u.literal("configure"),options:X10.optional(),sessionDirectory:GR0}),bZ=(_)=>u.strictObject({...J10,command:u.literal(_)}),CR0=u.discriminatedUnion("command",[zR0,bZ("start"),bZ("pause"),bZ("resume"),bZ("snapshot"),bZ("status"),bZ("stop"),bZ("shutdown")]),PZ=u.enum(["not-determined","authorized","denied","restricted","unavailable"]),ww=u.strictObject({accessibility:PZ,camera:PZ,inputMonitoring:PZ,microphone:PZ,screenCapture:PZ,systemAudio:PZ,windowMetadata:PZ}),V10=u.strictObject({height:u.number().finite().positive(),width:u.number().finite().positive(),x:u.number().finite(),y:u.number().finite()}),AR0=u.strictObject({bounds:V10,displayId:u.string().min(1).max(64),isPrimary:u.boolean(),pixelHeight:p$,pixelWidth:p$,scaleFactor:u.number().finite().positive().max(8)}),s$=u.strictObject({audio:u.array(u.discriminatedUnion("kind",[u.strictObject({audioSourceId:u.string().min(1).max(256),channels:u.number().int().positive().max(64),kind:u.literal("system"),label:u.string().min(1).max(512),sampleRateHz:u.number().int().positive().max(768000)}),u.strictObject({audioSourceId:u.string().min(1).max(256),channels:u.number().int().positive().max(64),kind:u.literal("microphone"),label:u.string().min(1).max(512),sampleRateHz:u.number().int().positive().max(768000)})])).max(WR0),cameras:u.array(u.strictObject({cameraId:u.string().min(1).max(256),frameRate:u.number().finite().positive().max(1000),label:u.string().min(1).max(512),pixelSize:u.strictObject({height:p$,width:p$}),position:u.enum(["front","back","external","unspecified"])})).max(HR0),displays:u.array(u.strictObject({bounds:V10,displayId:u.string().min(1).max(64),isPrimary:u.boolean(),label:u.string().min(1).max(512),pixelSize:u.strictObject({height:p$,width:p$}),refreshRateHz:u.number().finite().positive().max(1000),scaleFactor:u.number().finite().positive().max(8)})).max(fI)}).superRefine((_,$)=>{let F=(w,Q)=>{let Z=w.map(Q);return new Set(Z).size!==Z.length};if(F(_.audio,({audioSourceId:w})=>w))$.addIssue({code:"custom",message:"Capture audio source IDs must be unique."});if(F(_.cameras,({cameraId:w})=>w))$.addIssue({code:"custom",message:"Capture camera IDs must be unique."});if(F(_.displays,({displayId:w})=>w))$.addIssue({code:"custom",message:"Capture display IDs must be unique."});if(_.displays.length>0&&_.displays.filter(({isPrimary:w})=>w).length!==1)$.addIssue({code:"custom",message:"Capture displays must identify exactly one primary display."})}),BR0=u.strictObject({code:u.string().min(1).max(128),message:Q10,recoverable:u.boolean(),source:u.enum(["camera","helper","metadata","microphone","screen","system-audio"])}),e00=u.strictObject({nativeTimeUs:X4,ptsUs:XC,uncertaintyUs:X4.max(1e6)}),TR0=u.strictObject({bufferCount:p$,clockAnchors:u.strictObject({end:e00,first:e00}),presentation:u.strictObject({endPtsUs:XC,firstPtsUs:XC,lastPtsUs:XC,maximumSampleDurationUs:p$}),sampleCount:p$}).superRefine((_,$)=>{let{endPtsUs:F,firstPtsUs:w,lastPtsUs:Q,maximumSampleDurationUs:Z}=_.presentation;if(Q<w)$.addIssue({code:"custom",message:"Stream lastPtsUs cannot precede firstPtsUs."});if(F<=Q)$.addIssue({code:"custom",message:"Stream endPtsUs must be after lastPtsUs."});if(F-Q>Z)$.addIssue({code:"custom",message:"Stream final sample exceeds maximumSampleDurationUs."});if(_.clockAnchors.first.ptsUs!==w||_.clockAnchors.end.ptsUs!==F)$.addIssue({code:"custom",message:"Stream clock anchors must bind the first and exclusive-end PTS."});if(_.clockAnchors.end.nativeTimeUs<=_.clockAnchors.first.nativeTimeUs)$.addIssue({code:"custom",message:"Stream native clock anchors must increase."});let J=F-w,X=_.clockAnchors.end.nativeTimeUs-_.clockAnchors.first.nativeTimeUs,V=_.clockAnchors.first.uncertaintyUs+_.clockAnchors.end.uncertaintyUs+2;if(Math.abs(X-J)>V)$.addIssue({code:"custom",message:"Stream native clock anchors exceed their recorded mapping uncertainty."});if(_.sampleCount<_.bufferCount)$.addIssue({code:"custom",message:"Stream sampleCount cannot be smaller than bufferCount."})}),ZC={channels:u.number().int().positive().max(64).optional(),codec:u.string().min(1).max(64),mapping:u.enum(["exact","provisional"]),sampleRateHz:u.number().int().positive().max(768000).optional(),streamIndex:X4,timing:TR0,trackId:X4.optional()},SI=u.discriminatedUnion("role",[u.strictObject({...ZC,role:u.literal("camera-video")}),u.strictObject({...ZC,role:u.literal("display-video")}),u.strictObject({...ZC,role:u.literal("microphone-audio")}),u.strictObject({...ZC,role:u.literal("system-audio")}),u.strictObject({channels:u.number().int().positive().max(64).optional(),codec:u.string().min(1).max(64),mapping:u.literal("provisional"),role:u.literal("unclassified-audio"),sampleRateHz:u.number().int().positive().max(768000).optional(),streamIndex:X4,timing:u.never().optional(),trackId:X4.optional()})]),UR0=u.strictObject({containerDurationUs:p$,container:u.literal("mp4"),display:AR0,path:YC,streams:u.array(SI).min(1).max(3)}),kR0=u.discriminatedUnion("availability",[u.strictObject({availability:u.literal("recorded"),containerDurationUs:p$,container:u.enum(["mov","mp4"]),deviceId:u.string().min(1).max(256),label:u.string().min(1).max(512),path:YC,streams:u.array(SI).length(1)}),u.strictObject({availability:u.literal("unavailable"),reason:u.enum(["disabled","denied","missing","restricted","start-failed","finalization-failed","inspection-failed"])})]),MR0=u.discriminatedUnion("availability",[u.strictObject({availability:u.literal("recorded"),containerDurationUs:p$,container:u.literal("m4a"),deviceId:u.string().min(1).max(256),label:u.string().min(1).max(512),path:YC,streams:u.array(SI).length(1)}),u.strictObject({availability:u.literal("unavailable"),reason:u.enum(["disabled","denied","missing","restricted","start-failed","finalization-failed","inspection-failed"])})]),RR0=u.strictObject({droppedEvents:X4,eventKinds:u.array(u.enum(["cursor.sample","display.topology","focus.changed","key.activity","lifecycle.marker","mouse.click","typing.input","window.changed","window.snapshot","diagnostic.dropped-events"])).min(1).max(10),path:YC,recordCount:X4}),ER0=u.strictObject({camera:kR0,clock:u.strictObject({end:u.strictObject({nativeTimeUs:X4,sourceTimeUs:X4}),kind:u.literal("mach-continuous-microseconds"),start:u.strictObject({nativeTimeUs:X4,sourceTimeUs:X4})}),diagnostics:u.array(BR0).max(128),displays:u.array(UR0).min(1).max(fI),index:X4.max(JC-1),metadata:u.array(RR0).max(8),microphone:MR0,sources:s$}).superRefine((_,$)=>{let F=_.clock.end.sourceTimeUs-_.clock.start.sourceTimeUs,w=_.clock.end.nativeTimeUs-_.clock.start.nativeTimeUs;if(F<=0||w<=0)$.addIssue({code:"custom",message:"Segment clock anchors must increase."});else if(F!==w)$.addIssue({code:"custom",message:"Segment source and native clock durations must agree."});let Q=[..._.displays.map(({path:V})=>V),..._.camera.availability==="recorded"?[_.camera.path]:[],..._.microphone.availability==="recorded"?[_.microphone.path]:[],..._.metadata.map(({path:V})=>V)];if(new Set(Q).size!==Q.length)$.addIssue({code:"custom",message:"Segment output paths must be unique."});let Z=_.displays.map(({display:V})=>V.displayId);if(new Set(Z).size!==Z.length)$.addIssue({code:"custom",message:"Segment display output IDs must be unique."});if(_.displays.filter(({display:V})=>V.isPrimary).length!==1)$.addIssue({code:"custom",message:"Segment outputs must identify exactly one primary display."});let J=new Set(_.sources.displays.map(({displayId:V})=>V));if(Z.some((V)=>!J.has(V)))$.addIssue({code:"custom",message:"Segment display outputs must exist in the source inventory."});let X=0;for(let V of _.displays){let Y=V.streams.filter(({role:j})=>j==="display-video");if(Y.length!==1||Y[0]?.mapping!=="exact")$.addIssue({code:"custom",message:"Each display file must identify one exact display-video stream."});if(V.streams.some(({role:j})=>j==="camera-video"||j==="microphone-audio"))$.addIssue({code:"custom",message:"Display files may not claim camera or microphone streams."});for(let j of V.streams)if(j.role==="system-audio"){if(X+=1,j.mapping!=="exact")$.addIssue({code:"custom",message:"The isolated ScreenCaptureKit audio stream must have exact system-audio identity."})}}if(X>1)$.addIssue({code:"custom",message:"A segment may contain only one system-audio stream."});if(_.camera.availability==="recorded"&&(_.camera.streams[0]?.role!=="camera-video"||_.camera.streams[0].mapping!=="exact"))$.addIssue({code:"custom",message:"Recorded camera media must identify one exact camera-video stream."});if(_.microphone.availability==="recorded"&&(_.microphone.streams[0]?.role!=="microphone-audio"||_.microphone.streams[0].mapping!=="exact"))$.addIssue({code:"custom",message:"Recorded microphone media must identify one exact microphone-audio stream."})}),Y10={protocolVersion:u.literal(g8)},IZ={...Y10,requestId:F10},_10=u.enum(["unconfigured","ready","recording","paused","stopped","shutting-down"]),j10=u.strictObject({availableSources:u.boolean(),camera:u.boolean(),displayRecording:u.boolean(),interruptionDiagnostics:u.boolean(),metadata:u.boolean(),microphone:u.boolean(),minimumMacOSMajorVersion:u.literal(15),systemAudio:u.boolean(),typedTextOptIn:u.boolean()}),cX1=u.strictObject({availableSources:s$,capabilities:j10,helperVersion:u.literal($10),permissions:ww,protocolVersion:u.literal(g8)}),qR0=u.discriminatedUnion("event",[u.strictObject({...Y10,capabilities:j10,event:u.literal("ready"),helperVersion:u.literal($10)}),u.strictObject({...IZ,availableSources:s$,event:u.literal("configured"),lastInterruption:i_.nullable(),options:X10,permissions:ww,sources:s$,state:u.literal("ready")}),u.strictObject({...IZ,event:u.literal("status"),activeSegmentIndex:X4.nullable(),availableSources:s$,completedSegmentCount:X4.max(JC),lastInterruption:i_.nullable(),logicalTimeUs:X4,permissions:ww,sources:s$,state:_10}),u.strictObject({...IZ,event:u.literal("segment-started"),index:X4.max(JC-1),nativeStartUs:X4,permissions:ww,sources:s$,startUs:X4}),u.strictObject({...IZ,event:u.literal("segment-completed"),interruption:i_.nullable(),segment:ER0}),u.strictObject({...IZ,durationUs:X4,event:u.literal("session-completed"),segmentCount:X4.max(JC),state:u.literal("stopped")}),u.strictObject({...IZ,code:u.string().min(1).max(128),event:u.literal("error"),interruption:i_.nullable(),message:Q10,recoverable:u.boolean(),state:_10}),u.strictObject({...IZ,event:u.literal("shutdown")})]),bR0=qR0.superRefine((_,$)=>{if(_.event==="configured"&&_.lastInterruption!==null)$.addIssue({code:"custom",message:"A newly configured capture session cannot have a prior interruption."});if(_.event==="segment-completed"&&_.interruption!==null){if(_.interruption.segmentIndex!==_.segment.index||_.interruption.nativeTimeUs!==_.segment.clock.end.nativeTimeUs||_.interruption.sourceTimeUs!==_.segment.clock.end.sourceTimeUs)$.addIssue({code:"custom",message:"A segment-completed interruption must match the segment index and clock-end anchors."});if(!_.interruption.recoverable)$.addIssue({code:"custom",message:"A completed interruption must be recoverable."})}if(_.event==="error"&&_.interruption!==null&&_.interruption.recoverable!==_.recoverable)$.addIssue({code:"custom",message:"An error interruption must agree with the error recovery state."})});function PR0(_){if(new TextEncoder().encode(_).byteLength>t00)throw Error(`Capture protocol line exceeds ${t00} bytes.`);if(_.trim().length===0)throw Error("Capture protocol line is empty.");try{return JSON.parse(_)}catch($){let F=$ instanceof Error?$.message:"unknown JSON error";throw Error(`Capture protocol line is not valid JSON: ${F}`)}}function IR0(_){return CR0.parse(_)}function fR0(_){return bR0.parse(_)}function yI(_){return fR0(PR0(_))}function N10(_){return`${JSON.stringify(IR0(_))}
4654
4654
  `}import{createHash as G10}from"crypto";import{constants as H10}from"fs";import{lstat as SR0,open as yR0}from"fs/promises";import{release as gR0}from"os";var hR0=1048576,vR0=30000,xR0=16;function jC(_,$){return`${_==="event"?"events":_}_${G10("sha256").update($).digest("hex").slice(0,16)}`}async function mR0(_,$){if(!Number.isSafeInteger($)||$<=0)throw new N("invalid-data","Capture output has an invalid byte length.");let F=G10("sha256"),w=Buffer.allocUnsafe(Math.min(hR0,$)),Q=0;while(Q<$){let Z=Math.min(w.byteLength,$-Q),J=await _.read(w,0,Z,Q);if(!Number.isSafeInteger(J.bytesRead)||J.bytesRead<=0||J.bytesRead>Z)throw new N("invalid-data","Capture output ended or changed while its integrity was being recorded.");F.update(w.subarray(0,J.bytesRead)),Q+=J.bytesRead}return F.digest("hex")}function W10(_,$){return _.dev===$.dev&&_.ino===$.ino&&_.size===$.size&&_.mtimeMs===$.mtimeMs&&_.ctimeMs===$.ctimeMs}async function K10(_){let $=await SR0(_);if($.isSymbolicLink()||!$.isFile()||!Number.isSafeInteger($.size)||$.size<=0)throw new N("invalid-data",`Capture output is not a stable physical regular file: ${_}`);let F=await yR0(_,H10.O_RDONLY|H10.O_NOFOLLOW);try{let w=await F.stat();if(!w.isFile()||!W10($,w))throw new N("conflict",`Capture output changed before its integrity could be recorded: ${_}`);let Q=await mR0(F,w.size),Z=await F.stat();if(!W10(w,Z))throw new N("conflict",`Capture output changed while its integrity was being recorded: ${_}`);return{bytes:w.size,sha256:Q,state:"verified"}}finally{await F.close()}}function lR0(_){let $;try{$=JSON.parse(_)}catch{throw new N("invalid-data","FFprobe stream output is not valid JSON.")}if(typeof $!=="object"||$===null||Array.isArray($))throw new N("invalid-data","FFprobe stream output must be an object.");let F=$.streams;if(!Array.isArray(F))throw new N("invalid-data","FFprobe stream output omits streams.");let w=F.flatMap((Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new N("invalid-data","FFprobe stream entry must be an object.");let Z=Q;if(typeof Z.index!=="number"||!Number.isSafeInteger(Z.index)||Z.index<0)throw new N("invalid-data","FFprobe stream index is invalid.");let J=typeof Z.codec_name==="string"&&Z.codec_name!==""?Z.codec_name:"unknown",X=Z.codec_type==="video"?"video":Z.codec_type==="audio"?"audio":"unknown";if(X==="unknown")return[];let V=typeof Z.id==="string"||typeof Z.id==="number"?String(Z.id):void 0,Y=D10(Z.start_pts,Z.time_base)??O10(Z.start_time),j=uR0(Z.time_base),H=dR0(Z.duration_ts,Z.time_base)??O10(Z.duration);if(Y===null||H===null||H<=0||j===null)throw new N("invalid-data",`FFprobe stream ${Z.index} omits finite first/end PTS evidence.`);let K=Y+H;if(!Number.isSafeInteger(K))throw new N("invalid-data",`FFprobe stream ${Z.index} PTS exceeds the supported range.`);return[{codec:J,endPtsUs:K,firstPtsUs:Y,id:V,index:Z.index,tickUs:j,type:X}]});if(new Set(w.map(({index:Q})=>Q)).size!==w.length)throw new N("invalid-data","FFprobe audio/video stream indices must be unique.");return w}function dR0(_,$){let F=D10(_,$);return F!==null&&F>0?F:null}function D10(_,$){if(typeof _!=="string"&&typeof _!=="number"||typeof $!=="string")return null;let F=Number(_),w=/^(?<numerator>[1-9][0-9]*)\/(?<denominator>[1-9][0-9]*)$/u.exec($);if(w?.groups===void 0)return null;let Q=Math.round(F*Number(w.groups.numerator)*1e6/Number(w.groups.denominator));return Number.isSafeInteger(F)&&Number.isSafeInteger(Q)?Q:null}function O10(_){if(typeof _!=="string"||_.trim()==="")return null;let $=Number(_),F=Math.round($*1e6);return Number.isFinite($)&&Number.isSafeInteger(F)?F:null}function uR0(_){if(typeof _!=="string")return null;let $=/^(?<numerator>[1-9][0-9]*)\/(?<denominator>[1-9][0-9]*)$/u.exec(_);if($?.groups===void 0)return null;let F=Number($.groups.numerator)/Number($.groups.denominator),w=Math.ceil(Math.abs(F)*1e6);return Number.isFinite(F)&&Number.isSafeInteger(w)&&w>0?w:null}function gI(_){if(_===void 0)return;let $=_.startsWith("0x")?Number.parseInt(_.slice(2),16):Number(_);return Number.isSafeInteger($)&&$>=0?$:void 0}class NC{#_;#$;constructor(_={}){this.#_=_.ffprobe??"ffprobe",this.#$=_.runner??new F8}async verify(_,$){let F=await this.#$.run([this.#_,"-v","error","-show_entries","stream=index,id,codec_name,codec_type,start_time,start_pts,duration,duration_ts,time_base","-of","json",_],{maxOutputBytes:1e6,timeoutMs:vR0});if(F.exitCode!==0)throw new N("subprocess",`Could not verify finalized capture timing for ${_}: ${F.stderr.trim()||`exit ${F.exitCode}`}`);let w=lR0(F.stdout);if(w.length===0)throw new N("invalid-data",`FFprobe found no timed audio/video stream in ${_}.`);let Q=Math.min(...w.map(({firstPtsUs:V})=>V)),Z=new Set($.flatMap((V)=>{if(V.role!=="unclassified-audio")return[];let Y=w.find((j)=>j.type==="audio"&&(j.index===V.streamIndex||V.trackId!==void 0&&gI(j.id)===V.trackId));return Y===void 0?[]:[Y.index]})),J=[],X=$.map((V)=>{if(V.role==="unclassified-audio")return J.push({code:"unclassified-audio-stream",level:"warning",message:`Ignored unclassified audio stream ${V.streamIndex} in ${_}.`}),null;let Y=V.role.endsWith("video")?"video":"audio",j=V.trackId===void 0?void 0:w.find((z)=>gI(z.id)===V.trackId&&z.type===Y&&!Z.has(z.index)),H=w.find((z)=>z.index===V.streamIndex&&z.type===Y&&!Z.has(z.index)),K=w.find((z)=>z.type===Y&&!Z.has(z.index)),W=j??H??K;if(W===void 0)throw new N("invalid-data",`FFprobe found no ${Y} timing evidence for ${V.role} in ${_}.`,{diagnosticCode:"timing-evidence-mismatch",emittedStreamIndex:V.streamIndex,role:V.role});Z.add(W.index);let O=PB(W.tickUs,V.timing.presentation.maximumSampleDurationUs);if(O===null)throw new N("invalid-data",`Finalized PTS tolerance for ${V.role} in ${_} is outside the supported range.`);let L=V.timing.presentation.endPtsUs-V.timing.presentation.firstPtsUs,G=W.endPtsUs-W.firstPtsUs;if(Math.abs(G-L)>O)throw new N("invalid-data",`Finalized PTS span for ${V.role} in ${_} disagrees with the capture helper.`,{diagnosticCode:"timing-evidence-mismatch",emittedSpanUs:L,probedSpanUs:G,streamIndex:W.index,toleranceUs:O});let D=V.trackId!==void 0&&gI(W.id)===V.trackId;if(!D)J.push({code:"ffprobe-track-id-mismatch",level:V.mapping==="exact"?"error":"warning",message:`Corrected ${V.role} from emitted index ${V.streamIndex} to FFmpeg stream ${W.index} in ${_}.`});return{codec:W.codec==="unknown"?V.codec:W.codec,containerTrackIdentity:D&&W.id!==void 0?{containerTrackId:W.id,kind:"verified"}:{diagnosticCode:"ffprobe-track-id-mismatch",expectedRole:V.role,kind:"provisional"},filePresentation:{endPtsUs:W.endPtsUs,firstPtsUs:W.firstPtsUs,spanToleranceUs:O,tickUs:W.tickUs},streamIndex:W.index,timing:V.timing}});return{diagnostics:J,fileOriginPtsUs:Q,streams:X}}}function cR0(_){let $=_.now().toISOString();return t9.parse({capture:{cursor:_.captureOptions.metadata?"metadata":"disabled",typedText:_.captureOptions.typedText?"enabled":"disabled",windowMetadata:_.captureOptions.metadata?"titles-and-bounds":"disabled"},coordinateSpace:{kind:"global-display-points",origin:"top-left",xAxis:"right",yAxis:"down"},createdAt:$,diagnostics:[],eventStreams:[],interruptions:[],kind:"slopcamera.recording-bundle",permissions:_.configured.permissions,platform:{architecture:process.arch,os:process.platform==="darwin"?"macos":process.platform==="linux"?"linux":process.platform==="win32"?"windows":"unknown",osVersion:gR0()},recordingId:_.recordingId,schemaVersion:3,sources:_.configured.sources,state:"preparing",timeline:{durationUs:0,nativeClock:{kind:"mach-continuous-microseconds",segments:[]},timebase:"microseconds"},tool:{captureVersion:_.helperVersion,name:"slopcamera",version:_.toolVersion},tracks:[],updatedAt:$})}function g_(_,$,F){let w=_.diagnostics.find(({code:Q,message:Z,level:J})=>Q===$.code&&Z===$.message&&J===$.level);if(w===void 0)return[..._.diagnostics,{code:$.code,count:1,firstSourceTimeUs:F,lastSourceTimeUs:F,level:$.level,message:$.message.slice(0,4096)}];return _.diagnostics.map((Q)=>Q===w?{...Q,count:Q.count+1,lastSourceTimeUs:F}:Q)}function hI(_,$){let F=(Z,J)=>[...new Map(Z.map((X)=>[J(X),X])).values()],w=F([..._.displays,...$.displays],({displayId:Z})=>Z),Q=_.displays.find(({isPrimary:Z})=>Z)?.displayId??$.displays.find(({isPrimary:Z})=>Z)?.displayId??w[0]?.displayId;return{audio:F([..._.audio,...$.audio],({audioSourceId:Z})=>Z),cameras:F([..._.cameras,...$.cameras],({cameraId:Z})=>Z),displays:w.map((Z)=>({...Z,isPrimary:Z.displayId===Q}))}}function sR0(_){return _.tracks.flatMap(($)=>$.segments.flatMap((F)=>{if(F.timing.kind!=="measured"||F.timing.status!=="out-of-tolerance")return[];return[{captureSegmentIndex:F.timing.captureSegmentIndex,durationDriftUs:F.timing.durationDriftUs,durationDriftToleranceUs:F.timing.tolerance.durationDriftUs,endUs:F.endUs,kind:$.kind,onsetSkewUs:F.timing.onsetSkewUs,onsetSkewToleranceUs:F.timing.tolerance.onsetSkewUs,path:F.path,segmentId:F.segmentId,trackId:$.trackId}]}))}function vI(_){return{code:`capture-interruption-${_.code}`.slice(0,128),level:_.recoverable?"warning":"error",message:[`${_.source} capture interruption ${_.code}`,`closed segment ${_.segmentIndex} at source time`,`${_.sourceTimeUs} microseconds.`].join(" ").slice(0,4096)}}function L10(_,$){return _.code===$.code&&_.nativeTimeUs===$.nativeTimeUs&&_.recoverable===$.recoverable&&_.segmentIndex===$.segmentIndex&&_.source===$.source&&_.sourceId===$.sourceId&&_.sourceTimeUs===$.sourceTimeUs}function pR0(_,$){let F=$ instanceof N?$.code:"internal";return{code:"capture-segment-publication-failed",level:"error",message:[`Capture segment ${_.index} completed at source time`,`${_.clock.end.sourceTimeUs} microseconds, but its outputs were not admitted`,`because ${F} finalization verification failed.`].join(" ")}}function nR0(_,$){return _.index===$.index&&_.nativeRange.endUs===$.nativeRange.endUs&&_.nativeRange.startUs===$.nativeRange.startUs&&_.sourceRange.endUs===$.sourceRange.endUs&&_.sourceRange.startUs===$.sourceRange.startUs}class xI{#_;#$;#Q;#J;#F;constructor(_){this.#_=_.bundleRoot,this.#$=L0(_.bundleRoot),this.#Q=_.now,this.#J=_.verifier??new NC,this.#F=cR0(_)}get manifest(){return this.#F}async initialize(){await J1(this.#_),await E3(this.#$,this.#F)}async setCaptureEnvironment(_,$){let F=this.#F.timeline.nativeClock.segments.length===0?$:hI(this.#F.sources,$);this.#F=t9.parse({...this.#F,permissions:_,sources:F,updatedAt:this.#Q().toISOString()}),await E3(this.#$,this.#F)}async setState(_,$){let F=$??this.#F.timeline.durationUs;if(_==="stopped"){let w=sR0(this.#F);if(w.length>0){let Q=w[0],Z=[`Recording publication rejected because ${w.length} stream segment(s) exceeded capture synchronization tolerance.`,`First: ${Q.kind} ${Q.segmentId} (onset ${Q.onsetSkewUs}/${Q.onsetSkewToleranceUs} us,`,`duration drift ${Q.durationDriftUs}/${Q.durationDriftToleranceUs} us).`].join(" "),J=g_(this.#F,{code:"capture-sync-publication-rejected",level:"error",message:Z},w.reduce((X,V)=>Math.max(X,V.endUs),0));throw this.#F=t9.parse({...this.#F,diagnostics:J,state:"failed",timeline:{...this.#F.timeline,durationUs:F},updatedAt:this.#Q().toISOString()}),await E3(this.#$,this.#F),new N("invalid-data",Z,{diagnosticCode:"capture-sync-publication-rejected",violationCount:w.length,violations:w.slice(0,xR0)})}}this.#F=t9.parse({...this.#F,state:_,timeline:{...this.#F.timeline,durationUs:F},updatedAt:this.#Q().toISOString()}),await E3(this.#$,this.#F)}async appendSegment(_,$){let F=this.#F.diagnostics,w=[...this.#F.tracks],Q=[...this.#F.eventStreams],Z=new Set,J=_.clock.start.sourceTimeUs,X=_.clock.end.sourceTimeUs,V=_.displays.find(({display:L})=>L.isPrimary),Y=V?.streams.find(({role:L})=>L==="display-video"),j=Y?.timing;if(V===void 0||Y===void 0||j===void 0)throw new N("invalid-data",`Capture segment ${_.index} has no primary display timing reference.`);let H=A_.parse(jC("track",`display-video:${JSON.stringify({displayId:V.display.displayId})}`)),K=async(L,G,D,z,C,A,B)=>{let T=await a_(this.#_,L),[M,R]=await Promise.all([K10(T),this.#J.verify(T,D)]);for(let U of R.diagnostics)F=g_({...this.#F,diagnostics:F},U,X);if(R.streams.every((U)=>U===null))throw new N("invalid-data",`Capture output ${L} has no verified media stream timing.`);let g=R.fileOriginPtsUs;for(let U=0;U<D.length;U+=1){let E=D[U],f=R.streams[U];if(f===void 0||f===null||E.role==="unclassified-audio")continue;if(!(B==="display"?E.role==="display-video"||E.role==="system-audio":B==="camera"?E.role==="camera-video":E.role==="microphone-audio")){F=g_({...this.#F,diagnostics:F},{code:"capture-role-origin-mismatch",level:"error",message:`Ignored ${E.role} from ${B} output ${L}.`},X);continue}if((E.role==="system-audio"||E.role==="microphone-audio")&&Z.has(E.role))continue;if(E.role==="system-audio"||E.role==="microphone-audio")Z.add(E.role);let m=E.role==="display-video"?z!==null&&"displayId"in z?z:(()=>{throw new N("internal",`Display output ${L} has no display source.`)})():E.role==="camera-video"?z!==null&&"cameraId"in z?z:(()=>{throw new N("internal",`Camera output ${L} has no camera source.`)})():{audioSourceId:this.#F.sources.audio.find(({kind:t0})=>t0===(E.role==="system-audio"?"system":"microphone"))?.audioSourceId??_.sources.audio.find(({kind:t0})=>t0===(E.role==="system-audio"?"system":"microphone"))?.audioSourceId??`missing-${E.role}`},y=`${E.role}:${JSON.stringify(m)}`,l=A_.parse(jC("track",y)),r=f.timing.clockAnchors.first.nativeTimeUs,o=f.timing.clockAnchors.end.nativeTimeUs,G0=j.clockAnchors.end.nativeTimeUs-j.clockAnchors.first.nativeTimeUs,a=bB({clockNativeStartUs:_.clock.start.nativeTimeUs,clockSourceEndUs:X,clockSourceStartUs:J,fileContainerOriginPtsUs:g,fileEndPtsUs:f.filePresentation.endPtsUs,fileFirstPtsUs:f.filePresentation.firstPtsUs,helperNativeStartUs:r});if(a===null)throw new N("invalid-data",`Capture timing for ${E.role} in ${L} does not overlap segment ${_.index}.`);let{endUs:c,fileRangeEndUs:T0,fileRangeStartUs:Q0,rawEndUs:E0,rawStartUs:V0,startUs:C0}=a,D0=r-j.clockAnchors.first.nativeTimeUs,H0=o-j.clockAnchors.end.nativeTimeUs-D0,_0=fB(H0,G0),z0=IB({referenceDurationUs:G0,referenceEndUncertaintyUs:j.clockAnchors.end.uncertaintyUs,referenceFirstUncertaintyUs:j.clockAnchors.first.uncertaintyUs,referenceMaximumSampleDurationUs:j.presentation.maximumSampleDurationUs,subjectEndUncertaintyUs:f.timing.clockAnchors.end.uncertaintyUs,subjectFirstUncertaintyUs:f.timing.clockAnchors.first.uncertaintyUs,subjectMaximumSampleDurationUs:f.timing.presentation.maximumSampleDurationUs});if(_0===null||z0===null)throw new N("invalid-data",`Capture synchronization policy for ${E.role} in ${L} exceeds the supported range.`);let{durationDriftUs:A0,onsetSkewUs:E1}=z0,$1=Math.abs(D0)>E1||Math.abs(H0)>A0?"out-of-tolerance":"within-tolerance";if(C0!==V0||c!==E0)F=g_({...this.#F,diagnostics:F},{code:"capture-track-trimmed-to-segment",level:"warning",message:`Trimmed ${E.role} in ${L} to segment ${_.index}'s native-clock range.`},C0);if(Math.abs(D0)>E1)F=g_({...this.#F,diagnostics:F},{code:"capture-track-onset-skew",level:"warning",message:`${E.role} in ${L} starts ${D0} microseconds from the primary-display reference.`},C0);if(Math.abs(H0)>A0)F=g_({...this.#F,diagnostics:F},{code:"capture-track-duration-drift",level:"warning",message:`${E.role} in ${L} drifted ${H0} microseconds against the native capture clock.`},c);let y2=yB.parse({codec:f.codec,container:G,containerTrackIdentity:f.containerTrackIdentity,endUs:c,fileRange:{endUs:T0,startUs:Q0},integrity:M,path:L,segmentId:jC("segment",`${l}:${_.index}:${L}:${f.streamIndex}`),startUs:C0,streamIndex:f.streamIndex,timing:{captureSegmentIndex:_.index,durationDriftPpm:_0,durationDriftUs:H0,evidence:{file:{containerOriginPtsUs:g,endPtsUs:f.filePresentation.endPtsUs,firstPtsUs:f.filePresentation.firstPtsUs,spanToleranceUs:f.filePresentation.spanToleranceUs,tickUs:f.filePresentation.tickUs},helper:{...f.timing,containerDurationUs:A}},kind:"measured",nativeRange:{endUs:o,startUs:r},onsetSkewUs:D0,policy:"capture-sync-v1",presentation:{endPtsUs:f.timing.presentation.endPtsUs,firstPtsUs:f.timing.presentation.firstPtsUs,lastPtsUs:f.timing.presentation.lastPtsUs},referenceTrackId:H,status:$1,tolerance:{durationDriftUs:A0,onsetSkewUs:E1}}}),g2=w.findIndex(({trackId:t0})=>t0===l);if(g2===-1)w.push(gB.parse({enabled:!0,kind:E.role,label:E.role==="display-video"||E.role==="camera-video"?C:E.role,segments:[y2],source:m,trackId:l}));else{let t0=w[g2];w[g2]={...t0,segments:[...t0.segments,y2]}}}},W=hI(this.#F.sources,_.sources);for(let L of[..._.displays].sort((G,D)=>Number(D.display.isPrimary)-Number(G.display.isPrimary))){let G=W.displays.find(({displayId:D})=>D===L.display.displayId);await K(L.path,L.container,L.streams,{displayId:L.display.displayId},G?.label??L.display.displayId,L.containerDurationUs,"display")}if(_.camera.availability==="recorded"){let L=_.camera,G=W.cameras.find(({cameraId:D})=>D===L.deviceId);await K(L.path,L.container,L.streams,{cameraId:L.deviceId},G?.label??L.label,L.containerDurationUs,"camera")}else if(_.camera.reason!=="disabled")F=g_({...this.#F,diagnostics:F},{code:`camera-${_.camera.reason}`,level:_.camera.reason.endsWith("failed")?"error":"warning",message:`Camera was unavailable for segment ${_.index}: ${_.camera.reason}.`},X);if(_.microphone.availability==="recorded"){let L=_.microphone,G=W.audio.find(({kind:D})=>D==="microphone");await K(L.path,L.container,L.streams,null,G?.label??L.label,L.containerDurationUs,"microphone")}else if(_.microphone.reason!=="disabled")F=g_({...this.#F,diagnostics:F},{code:`microphone-${_.microphone.reason}`,level:_.microphone.reason.endsWith("failed")?"error":"warning",message:`Microphone was unavailable for segment ${_.index}: ${_.microphone.reason}.`},X);for(let L of _.metadata){let G=await a_(this.#_,L.path);if(Q.push(vB.parse({endUs:X,eventKinds:L.eventKinds,eventStreamId:jC("event",`${_.index}:${L.path}`),integrity:await K10(G),path:L.path,recordCount:L.recordCount,startUs:J})),L.droppedEvents>0)F=g_({...this.#F,diagnostics:F},{code:"metadata-dropped-events",level:"warning",message:`${L.droppedEvents} metadata event(s) were dropped in ${L.path}.`},X)}for(let L of _.diagnostics)F=g_({...this.#F,diagnostics:F},{code:L.code,level:L.recoverable?"warning":"error",message:`${L.source}: ${L.message}`},X);if($!==null)F=g_({...this.#F,diagnostics:F},vI($),$.sourceTimeUs);let O=t9.parse({...this.#F,diagnostics:F,eventStreams:Q,interruptions:$===null?this.#F.interruptions:[...this.#F.interruptions,$],sources:W,timeline:{durationUs:Math.max(this.#F.timeline.durationUs,X),nativeClock:{kind:"mach-continuous-microseconds",segments:[...this.#F.timeline.nativeClock.segments,{index:_.index,nativeRange:{endUs:_.clock.end.nativeTimeUs,startUs:_.clock.start.nativeTimeUs},sourceRange:{endUs:X,startUs:J}}]},timebase:"microseconds"},tracks:w,updatedAt:this.#Q().toISOString()});await E3(this.#$,O),this.#F=O}async recordFailedSegmentCompletion(_,$,F){let w={index:_.index,nativeRange:{endUs:_.clock.end.nativeTimeUs,startUs:_.clock.start.nativeTimeUs},sourceRange:{endUs:_.clock.end.sourceTimeUs,startUs:_.clock.start.sourceTimeUs}},Q=this.#F.timeline.nativeClock.segments.find((j)=>j.index===_.index);if(Q!==void 0&&!nR0(Q,w))throw new N("invalid-data",`Capture segment ${_.index} emitted conflicting completion-clock evidence.`);let Z=$===null?void 0:this.#F.interruptions.find((j)=>j.segmentIndex===$.segmentIndex);if($!==null&&Z!==void 0&&!L10(Z,$))throw new N("invalid-data",`Capture segment ${$.segmentIndex} emitted conflicting interruption evidence.`);let J=this.#F.diagnostics;if($!==null&&Z===void 0)J=g_({...this.#F,diagnostics:J},vI($),$.sourceTimeUs);let X=pR0(_,F);if(!J.some(({code:j,level:H,message:K})=>j===X.code&&H===X.level&&K===X.message))J=g_({...this.#F,diagnostics:J},X,_.clock.end.sourceTimeUs);let Y=t9.parse({...this.#F,diagnostics:J,interruptions:$!==null&&Z===void 0?[...this.#F.interruptions,$]:this.#F.interruptions,sources:hI(this.#F.sources,_.sources),state:"failed",timeline:{...this.#F.timeline,durationUs:Math.max(this.#F.timeline.durationUs,_.clock.end.sourceTimeUs),nativeClock:{...this.#F.timeline.nativeClock,segments:Q===void 0?[...this.#F.timeline.nativeClock.segments,w]:this.#F.timeline.nativeClock.segments}},updatedAt:this.#Q().toISOString()});await E3(this.#$,Y),this.#F=Y}async recordFailureInterruption(_){let $=this.#F.interruptions.find((w)=>w.segmentIndex===_.segmentIndex);if($!==void 0&&!L10($,_))throw new N("invalid-data",`Capture segment ${_.segmentIndex} emitted conflicting interruption evidence.`);let F=$===void 0?g_(this.#F,vI(_),_.sourceTimeUs):this.#F.diagnostics;this.#F=t9.parse({...this.#F,diagnostics:F,interruptions:$===void 0?[...this.#F.interruptions,_]:this.#F.interruptions,state:"failed",updatedAt:this.#Q().toISOString()}),await E3(this.#$,this.#F)}}var _E0={configure:[["configured"]],pause:[["segment-completed"]],resume:[["segment-started"],["segment-completed","segment-started"]],shutdown:[["shutdown"],["session-completed","shutdown"],["segment-completed","session-completed","shutdown"]],snapshot:[["status"],["segment-completed","status"],["session-completed","status"],["segment-completed","session-completed","status"]],start:[["segment-started"]],status:[["status"],["segment-completed","status"],["session-completed","status"],["segment-completed","session-completed","status"]],stop:[["session-completed"],["segment-completed","session-completed"]]},$E0=24576;class mI extends N{constructor(_,$){super(_,`Capture helper ${$.code}: ${$.message}`,{helperCode:$.code,recoverable:!0,state:$.state});this.name="NonFatalCaptureCommandError"}}function FE0(_,$){return $.every((F,w)=>_[w]===F.event)}function wE0(_){return _.map(({event:$})=>$).join(" -> ")}function e2(_,$,F){let w=F===void 0?"":` ${F}`;return new N("invalid-data",`Capture helper emitted an invalid ${_.command} response sequence: ${wE0($)}.${w}`)}function T10(_){return _.find(($)=>$.event==="segment-completed")}function QE0(_){return _.find(($)=>$.event==="session-completed")}function KC(_,$){if(_===null||$===null)return _===$;return _.code===$.code&&_.nativeTimeUs===$.nativeTimeUs&&_.recoverable===$.recoverable&&_.segmentIndex===$.segmentIndex&&_.source===$.source&&_.sourceId===$.sourceId&&_.sourceTimeUs===$.sourceTimeUs}function ZE0(_,$){return JSON.stringify(_)===JSON.stringify($)}function JE0(_){if(_.event==="configured"||_.event==="segment-started"||_.event==="status")return _.sources;return _.event==="segment-completed"?_.segment.sources:void 0}function XE0(_,$,F,w){let Q=F.interruption;if(Q===null)return"none";if(_.command==="configure")throw e2(_,[F],"Configure errors cannot carry segment interruption evidence.");if(KC(Q,w.lastInterruption))return"persisted";let Z=T10($);if(Z!==void 0&&Q.segmentIndex===Z.segment.index){if(Z.interruption===null||!KC(Q,Z.interruption))throw e2(_,[...$,F],"An error cannot replace same-segment completion interruption evidence.");return"persisted"}let J=w.completedSegmentCount+(Z===void 0?0:1),X=Z?.segment.clock.end.sourceTimeUs??w.logicalTimeUs,V=Z?.segment.clock.end.nativeTimeUs??0;if(Q.segmentIndex!==J||Q.sourceTimeUs!==X||Q.nativeTimeUs<V)throw e2(_,[...$,F],"An unmatched error interruption must identify the next segment and the persisted source-time frontier.");return"new-frontier"}function z10(_,$,F){let w=T10($),Q=QE0($);if(F.sessionCompletionPersisted&&Q!==void 0)throw e2(_,$,"A completed session may not emit session-completed again.");let Z=w===void 0?0:1,J=F.completedSegmentCount+Z,X=w?.segment.clock.end.sourceTimeUs??F.logicalTimeUs;if(w!==void 0&&w.segment.index!==F.completedSegmentCount)throw e2(_,$,"Segment completion indices must advance from the persisted bundle frontier.");if(w!==void 0&&w.segment.clock.start.sourceTimeUs!==F.logicalTimeUs)throw e2(_,$,"Segment completion must begin at the persisted bundle frontier.");if(Q!==void 0&&(Q.segmentCount!==J||Q.durationUs!==X))throw e2(_,$,"Session completion must equal the persisted bundle plus its optional segment completion.");if(_.command==="resume"||_.command==="start"){let H=$.find((K)=>K.event==="segment-started");if(H!==void 0&&(H.index!==J||H.startUs!==X))throw e2(_,$,"A started segment must use the next index and begin at the completed bundle frontier.")}if(_.command!=="configure")for(let H of $){let K=JE0(H);if(K!==void 0&&!(H.event==="segment-started"&&(_.command==="start"||_.command==="resume"))&&!ZE0(K,F.sources))throw e2(_,$,"Completion and status events must retain the current selected capture sources.")}if(_.command!=="snapshot"&&_.command!=="status")return;let V=$.at(-1);if(V?.event!=="status")throw e2(_,$,"The response did not end with status.");if(V.state!=="recording"&&V.state!=="paused"&&V.state!=="stopped")throw e2(_,$,"An active recording may report only recording, paused, or proven stopped status.");if(F.sessionCompletionPersisted&&V.state!=="stopped")throw e2(_,$,"A completed session may report only stopped status.");if(V.state==="stopped"&&Q===void 0&&!F.sessionCompletionPersisted||V.state!=="stopped"&&Q!==void 0)throw e2(_,$,"A stopped status requires session-completed proof, and no other status may follow same-request completion.");if(w!==void 0&&Q===void 0&&V.state!=="paused")throw e2(_,$,"A segment completion without session completion must reconcile to paused.");if(V.state==="paused"&&(V.completedSegmentCount!==J||V.logicalTimeUs!==X))throw e2(_,$,"Paused status counters must equal the persisted bundle plus its optional segment completion.");let Y=V.state==="recording"?J:null;if(V.activeSegmentIndex!==Y)throw e2(_,$,"Status activeSegmentIndex must match the capture frontier and lifecycle state.");let j=w?.interruption??F.lastInterruption;if(!KC(V.lastInterruption,j))throw e2(_,$,"Status lastInterruption must match the latest accepted interruption evidence.");if(V.state==="recording"&&(V.completedSegmentCount!==F.completedSegmentCount||V.logicalTimeUs<F.logicalTimeUs||V.logicalTimeUs<F.priorSnapshotLogicalTimeUs))throw e2(_,$,"Recording status must preserve the persisted segment count and advance monotonically from both bundle and live frontiers.");if(V.state==="stopped"&&(V.completedSegmentCount!==J||V.logicalTimeUs!==X))throw e2(_,$,"Stopped status counters must equal the completed bundle frontier.");if(Q!==void 0&&(V.completedSegmentCount!==Q.segmentCount||V.logicalTimeUs!==Q.durationUs))throw e2(_,$,"Status counters must match the preceding session completion.")}function VE0(_){return Bun.spawn([_],{env:uw(process.env),stdin:"pipe",stdout:"pipe",stderr:"pipe"})}var YE0=30000;class U10{#_;#$;#Q=new TextDecoder;#J="";#F=!1;#X="";constructor(_){this.#_=VE0(_),this.#$=this.#_.stdout.getReader(),this.#Y()}async#Y(){try{for await(let _ of this.#_.stderr)this.#X=`${this.#X}${new TextDecoder().decode(_)}`.slice(-16384)}catch{}}async readLine(_){let $=Date.now()+_;while(!0){let F=this.#J.indexOf(`
4655
4655
  `);if(F!==-1){let Z=this.#J.slice(0,F);return this.#J=this.#J.slice(F+1),Z}let w=$-Date.now();if(w<=0)throw new N("subprocess","Capture helper response timed out.");let Q=await Promise.race([this.#$.read(),new Promise((Z,J)=>{setTimeout(()=>J(new N("subprocess","Capture helper response timed out.")),w)})]);if(Q.done)throw new N("subprocess",`Capture helper closed its protocol stream${this.#X===""?".":`: ${this.#X.trim()}`}`);if(this.#J+=this.#Q.decode(Q.value,{stream:!0}),new TextEncoder().encode(this.#J).byteLength>65536)throw new N("invalid-data","Capture helper emitted an oversized protocol line.")}}async write(_){if(this.#F)throw new N("conflict","Capture helper transport is closed.");this.#_.stdin.write(_),await this.#_.stdin.flush()}stderrTail(){return this.#X}async close(){if(this.#F)return;this.#F=!0,this.#_.stdin.end();try{await this.#$.cancel()}catch{}let _,$=await Promise.race([this.#_.exited.then(()=>!0),new Promise((F)=>{_=setTimeout(()=>F(!1),YE0)})]);if(_!==void 0)clearTimeout(_);if(!$)this.#_.kill()}}class k10{spawn(_){return Promise.resolve(new U10(_))}}function C10(){return{audio:[],cameras:[],displays:[]}}function WC(_){return{availableSources:C10(),completedSegmentCount:0,effectiveConfig:null,lastInterruption:null,logicalTimeUs:0,permissions:null,recordingId:null,recordingRoot:null,sources:C10(),state:"idle",updatedAt:_.toISOString()}}function tV(_){return lI(_,".active-recording.json")}function jE0(_){if(_===null)return null;if(typeof _!=="object"||_===null||Array.isArray(_))throw new N("invalid-data","Recording effective config is invalid.");let $=_,F=(K)=>{let W=$[K];if(typeof W!=="boolean")throw new N("invalid-data",`Recording effective config ${K} is invalid.`);return W};if(!F("metadata"))throw new N("invalid-data","Recording metadata cannot be disabled.");let Q=$.interactionEventProcessIdentifier,Z=Q===void 0?void 0:Q===null?null:typeof Q==="number"&&Number.isInteger(Q)&&Q>0&&Q<=2147483647?Q:(()=>{throw new N("invalid-data","Recording effective config interaction event process ID is invalid.")})(),J=$.typedTextFocusIdentities,X=J===void 0?void 0:qH.nullable().safeParse(J);if(X!==void 0&&!X.success)throw new N("invalid-data","Recording effective config typed-text focus identities are invalid.");let V=X?.data,Y=Qw.safeParse($.camera);if(!Y.success)throw new N("invalid-data","Recording effective config camera selection is invalid.");let j=bH.safeParse($.displays);if(!j.success)throw new N("invalid-data","Recording effective config display selection is invalid.");let H=Qw.safeParse($.microphone);if(!H.success)throw new N("invalid-data","Recording effective config microphone selection is invalid.");return{camera:Y.data,displays:j.data,...Z===void 0?{}:{interactionEventProcessIdentifier:Z},metadata:!0,microphone:H.data,strictInputs:F("strictInputs"),systemAudio:F("systemAudio"),typedText:F("typedText"),...V===void 0?{}:{typedTextFocusIdentities:V===null?null:V.map((K)=>({...K}))}}}function dI(_){if(typeof _!=="object"||_===null||Array.isArray(_))throw new N("invalid-data","Active recording state must be a JSON object.");let $=_;if($.state!=="idle"&&$.state!=="recording"&&$.state!=="paused")throw new N("invalid-data","Active recording state has an unknown phase.");if(typeof $.completedSegmentCount!=="number"||!Number.isSafeInteger($.completedSegmentCount)||$.completedSegmentCount<0||typeof $.logicalTimeUs!=="number"||!Number.isSafeInteger($.logicalTimeUs)||$.logicalTimeUs<0||typeof $.updatedAt!=="string")throw new N("invalid-data","Active recording state has invalid counters or timestamp.");let{recordingId:F,recordingRoot:w}=$,Q=ww.nullable().safeParse($.permissions),Z=s$.safeParse($.sources),J=s$.safeParse($.availableSources),X=i_.nullable().safeParse($.lastInterruption);if(F!==null&&typeof F!=="string"||w!==null&&typeof w!=="string"||!Q.success||!Z.success||!J.success||!X.success)throw new N("invalid-data","Active recording state has invalid identity, permissions, sources, or interruption evidence.");return{availableSources:J.data,completedSegmentCount:$.completedSegmentCount,effectiveConfig:jE0($.effectiveConfig),lastInterruption:X.data,logicalTimeUs:$.logicalTimeUs,permissions:Q.data,recordingId:F,recordingRoot:w,sources:Z.data,state:$.state,updatedAt:$.updatedAt}}async function PH(_,$=()=>new Date){try{let F=await iR0(tV(_),"utf8"),w;try{w=JSON.parse(F)}catch{throw new N("invalid-data","Active recording state is not valid JSON.")}return dI(w)}catch(F){if(F instanceof Error&&"code"in F&&F.code==="ENOENT")return WC($());throw F}}async function iV(_,$){await J1(_);let F=tV(_);try{if((await rR0(F)).isSymbolicLink())throw new N("unsafe-path",`Active recording state is a symlink: ${F}`)}catch(Q){if(!(Q instanceof Error&&("code"in Q)&&Q.code==="ENOENT"))throw Q}let w=lI(_,`.active-recording.${B10()}.tmp`);try{await eR0(w,`${JSON.stringify($)}
4656
- `,{flag:"wx",mode:384}),await aR0(w,F)}finally{await aV(w,{force:!0})}}function HC(_){return{..._.permissions}}function A10(_,$){if(_===void 0)return;try{_(structuredClone($))}catch{}}class uI{#_;#$;#Q;#J;#F;#X;#Y;#V;#w;#j=null;#W=!1;#U=0;#Z="unknown";#H=!1;#L;#G;#N;constructor(_){this.#_=_.artifactRoot,this.#$=_.executable,this.#Q=_.io.now,this.#J=_.onCaptureEvent,this.#F=_.requestTimeoutMs??240000,this.#X=_.transportFactory??new k10,this.#N=new NC({..._.ffprobeExecutable===void 0?{}:{ffprobe:_.ffprobeExecutable},..._.runner===void 0?{}:{runner:_.runner}}),this.#w=WC(this.#Q())}async#z(){if(this.#W)throw new N("conflict","Recording controller is closed.");if(this.#Y!==void 0)return this.#Y;try{if(!(await tR0(this.#$)).isFile())throw new N("unavailable",`Capture helper is not a file: ${this.#$}`)}catch(F){if(F instanceof N)throw F;throw new N("unavailable",`Capture helper is unavailable at ${this.#$}. Run: bun run build:desktop:capture:macos`)}let _=await this.#X.spawn(this.#$);this.#Y=_;let $=yI(await _.readLine(this.#F));if(A10(this.#J,$),$.event!=="ready")throw await _.close(),this.#Y=void 0,new N("invalid-data",`Capture helper emitted ${$.event} before ready.`);return this.#Z=$.helperVersion,_}#K(_){return this.#U+=1,`cli:${_}:${this.#U}`}async#k(_){let $=this.#w.recordingId??this.#V?.manifest.recordingId??null,F=this.#w.recordingRoot,w=this.#G,Q=w??this.#w.lastInterruption,Z=structuredClone(this.#w.sources),J=Buffer.byteLength(JSON.stringify(Z))<=$E0,X={lastInterruption:Q===null?null:structuredClone(Q),logicalTimeUs:this.#w.logicalTimeUs,permissions:this.#w.permissions===null?null:structuredClone(this.#w.permissions),...J?{sources:Z}:{}},V=[],Y=this.#L,j=Y===void 0,H=async(z)=>{if(Y===void 0||this.#V===void 0)return;try{await this.#V.recordFailedSegmentCompletion(Y.segment,Y.interruption,Y.failure),j=!0;for(let C=V.length-1;C>=0;C-=1)if(V[C]?.startsWith("completion frontier"))V.splice(C,1)}catch(C){V.push(`${z}${P5(C)}`)}};await H("completion frontier: ");let K=w===void 0,W=async(z)=>{if(w===void 0||this.#V===void 0)return;try{await this.#V.recordFailureInterruption(w),K=!0;for(let C=V.length-1;C>=0;C-=1)if(V[C]?.startsWith("failure interruption"))V.splice(C,1)}catch(C){V.push(`${z}${P5(C)}`)}};await W("failure interruption: ");let O=this.#H?"stopped":"unsettled";if(this.#V!==void 0&&!this.#H){let z=this.#V.manifest.timeline.durationUs;try{await this.#V.setState("failed",z),O="failed"}catch(C){V.push(`manifest: ${P5(C)}`)}}let L=this.#Y;if(this.#Y=void 0,L!==void 0)try{await L.close()}catch(z){V.push(`helper: ${P5(z)}`)}if(!j)await H("completion frontier retry: ");if(!K)await W("failure interruption retry: ");if(O==="unsettled"&&this.#V!==void 0)try{await this.#V.setState("failed",this.#V.manifest.timeline.durationUs),O="failed";let z=V.findIndex((C)=>C.startsWith("manifest: "));if(z!==-1)V.splice(z,1)}catch(z){let C=`manifest retry: ${P5(z)}`;if(!V.includes(C))V.push(C)}try{await aV(tV(this.#_),{force:!0})}catch(z){V.push(`active state: ${P5(z)}`)}if(this.#V=void 0,this.#j=null,this.#L=void 0,this.#G=void 0,this.#H=!1,this.#w=WC(this.#Q()),V.length>0)this.#W=!0;let G=n_(_),D={controllerReusable:V.length===0,recordingId:$,recordingRoot:F,snapshot:X,terminalManifestState:O};if(V.length>0)throw new N("internal",`${G.message} Capture recovery was incomplete: ${V.join("; ")}`,{captureFailure:{code:G.code,details:G.details??null},recovery:D,recoveryErrors:V});throw new N(G.code,G.message,{...G.details??{},recovery:D})}async#M(_,$){let F=[],w=this.#Y;if(this.#Y=void 0,w!==void 0)try{await w.close()}catch(Z){F.push(`helper: ${P5(Z)}`)}try{await aV(_,{force:!0,recursive:!0}),await aV(tV(this.#_),{force:!0})}catch(Z){F.push(`recording cleanup: ${P5(Z)}`)}if(this.#V=void 0,this.#j=null,this.#L=void 0,this.#G=void 0,this.#H=!1,this.#w=WC(this.#Q()),F.length>0)this.#W=!0;let Q=n_($);if(F.length>0)throw new N("internal",`${Q.message} Capture recovery was incomplete: ${F.join("; ")}`,{captureFailure:{code:Q.code,details:Q.details??null},recoveryErrors:F});throw Q}async#D(_){try{return await _()}catch($){if($ instanceof mI)throw $;return await this.#k($)}}#A(){let _=this.#V?.manifest;return{completedSegmentCount:_?.timeline.nativeClock.segments.length??this.#w.completedSegmentCount,lastInterruption:this.#w.lastInterruption,logicalTimeUs:_?.timeline.durationUs??this.#w.logicalTimeUs,priorSnapshotLogicalTimeUs:this.#w.logicalTimeUs,sessionCompletionPersisted:this.#H,sources:this.#w.sources}}async#R(_){if(_.event==="segment-completed"){try{await this.#V?.appendSegment(_.segment,_.interruption)}catch($){throw this.#L={failure:$,interruption:_.interruption,segment:_.segment},this.#w={...this.#w,completedSegmentCount:this.#w.completedSegmentCount+1,lastInterruption:_.interruption??this.#w.lastInterruption,logicalTimeUs:Math.max(this.#w.logicalTimeUs,_.segment.clock.end.sourceTimeUs),updatedAt:this.#Q().toISOString()},$}this.#w={...this.#w,completedSegmentCount:this.#w.completedSegmentCount+1,lastInterruption:_.interruption??this.#w.lastInterruption,logicalTimeUs:Math.max(this.#w.logicalTimeUs,_.segment.clock.end.sourceTimeUs),updatedAt:this.#Q().toISOString()}}if(_.event==="session-completed"){if(this.#V===void 0)throw new N("internal","Capture helper completed a session without an initialized recording bundle.");await this.#V.setState("stopped",_.durationUs),this.#H=!0,this.#w={...this.#w,completedSegmentCount:_.segmentCount,logicalTimeUs:_.durationUs,state:"idle",updatedAt:this.#Q().toISOString()}}}async#C(_){let $=await this.#z();await $.write(N10(_));let F=[],w=_E0[_.command],Q=this.#A();while(!0){let Z=yI(await $.readLine(this.#F));if(!("requestId"in Z)||Z.requestId!==_.requestId)throw new N("invalid-data",`Capture helper response ID ${"requestId"in Z?Z.requestId:"<missing>"} did not match ${_.requestId}.`);if(A10(this.#J,Z),Z.event==="error"){let V=_.command==="resume"&&F.length===1&&F[0]?.event==="segment-completed";if(F.length>0&&!V)throw e2(_,[...F,Z],"Errors may not follow completion evidence.");let Y=[...F,Z],j=XE0(_,F,Z,Q);if(F.length>0)z10(_,Y,Q);let K=Z.recoverable&&(_.command==="resume"||Z.code==="invalid-state")&&j!=="new-frontier";if(!K&&Z.interruption!==null)this.#G=Z.interruption;for(let W of F)await this.#R(W);if(Z.interruption!==null)this.#w={...this.#w,lastInterruption:Z.interruption,updatedAt:this.#Q().toISOString()};if(Z.interruption!==null&&this.#V!==void 0){let W=this.#V.manifest.interruptions.some((O)=>KC(O,Z.interruption));if(K&&!W)throw e2(_,Y,"A recoverable error cannot introduce interruption evidence that was not persisted by completion.");if(!K)await this.#V.recordFailureInterruption(Z.interruption)}if(_.command==="resume"&&K&&Z.state==="paused"){if(this.#V===void 0)throw new N("internal","Capture helper rejected resume without a recording bundle.");this.#w={...this.#w,state:"paused",updatedAt:this.#Q().toISOString()},await this.#V.setState("paused",this.#w.logicalTimeUs),await iV(this.#_,this.#w)}else if(K&&this.#w.recordingId!==null)await iV(this.#_,this.#w);if(K)throw new mI(Z.code==="invalid-state"?"conflict":"unavailable",Z);throw new N(Z.recoverable?"unavailable":"subprocess",`Capture helper ${Z.code}: ${Z.message}`,{helperCode:Z.code,interruption:Z.interruption,recoverable:Z.recoverable,state:Z.state})}F.push(Z);let J=w.filter((V)=>FE0(V,F));if(J.length===0)throw e2(_,F);if(J.find((V)=>V.length===F.length)!==void 0){z10(_,F,Q);for(let V of F)await this.#R(V);return Z}}}async start(_){if(this.#w.state!=="idle")throw new N("conflict",`Cannot start while recording is ${this.#w.state}.`);let $=`rec_${this.#Q().toISOString().replaceAll(/[-:.TZ]/gu,"")}_${B10().slice(0,8)}`,F=lI(this.#_,$);this.#V=void 0,this.#j=null,this.#L=void 0,this.#G=void 0,this.#H=!1,await J1(this.#_),await oR0(F,{mode:448,recursive:!1});let w={..._,metadata:!0},Q={camera:{..._.camera},displays:_.displays.kind==="all"?{kind:"all"}:{displayIds:[..._.displays.displayIds],kind:"selected"},excludedBundleIdentifiers:["com.hraness.slopcamera"],interactionEventProcessIdentifier:_.interactionEventProcessIdentifier??null,metadata:!0,microphone:{..._.microphone},strictSources:_.strictInputs,systemAudio:_.systemAudio,typedText:_.typedText,typedTextFocusIdentities:_.typedTextFocusIdentities===void 0||_.typedTextFocusIdentities===null?null:_.typedTextFocusIdentities.map((Z)=>({...Z}))};try{let Z=await this.#C({command:"configure",options:Q,protocolVersion:g8,requestId:this.#K("configure"),sessionDirectory:F});if(Z.event!=="configured")throw new N("invalid-data","Capture helper did not acknowledge configuration.");this.#j=w,this.#V=new xI({bundleRoot:F,captureOptions:Q,configured:Z,helperVersion:this.#Z,now:this.#Q,recordingId:$,toolVersion:"3.2.4",verifier:this.#N}),await this.#V.initialize(),this.#w={availableSources:Z.availableSources,completedSegmentCount:0,effectiveConfig:w,lastInterruption:Z.lastInterruption,logicalTimeUs:0,permissions:HC(Z),recordingId:$,recordingRoot:F,sources:Z.sources,state:"paused",updatedAt:this.#Q().toISOString()};let J=await this.#C({command:"start",protocolVersion:g8,requestId:this.#K("start")});if(J.event!=="segment-started")throw new N("invalid-data","Capture helper did not start a segment.");return await this.#V.setCaptureEnvironment(J.permissions,J.sources),this.#w={...this.#w,logicalTimeUs:J.startUs,permissions:HC(J),sources:J.sources,state:"recording",updatedAt:this.#Q().toISOString()},await this.#V.setState("recording",J.startUs),await iV(this.#_,this.#w),this.#w}catch(Z){if(this.#V===void 0)return await this.#M(F,Z);return await this.#k(Z)}}async pause(){if(this.#w.state!=="recording")throw new N("conflict",`Cannot pause while recording is ${this.#w.state}.`);return await this.#D(async()=>{if((await this.#C({command:"pause",protocolVersion:g8,requestId:this.#K("pause")})).event!=="segment-completed")throw new N("invalid-data","Capture helper did not complete the active segment.");return this.#w={...this.#w,state:"paused",updatedAt:this.#Q().toISOString()},await this.#V?.setState("paused",this.#w.logicalTimeUs),await iV(this.#_,this.#w),this.#w})}async resume(){if(this.#w.state==="idle"||this.#w.recordingId===null)throw new N("conflict",`Cannot resume while recording is ${this.#w.state}.`);return await this.#D(async()=>{let _=await this.#C({command:"resume",protocolVersion:g8,requestId:this.#K("resume")});if(_.event!=="segment-started")throw new N("invalid-data","Capture helper did not resume capture.");return await this.#V?.setCaptureEnvironment(_.permissions,_.sources),this.#w={...this.#w,logicalTimeUs:_.startUs,permissions:HC(_),sources:_.sources,state:"recording",updatedAt:this.#Q().toISOString()},await this.#V?.setState("recording",this.#w.logicalTimeUs),await iV(this.#_,this.#w),this.#w})}async status(){if(this.#Y===void 0)return this.#w=await PH(this.#_,this.#Q),this.#w;return await this.#D(async()=>{let _=await this.#C({command:"status",protocolVersion:g8,requestId:this.#K("status")});if(_.event!=="status")throw new N("invalid-data","Capture helper omitted status.");let $=_.state==="recording"?"recording":_.state==="paused"?"paused":"idle";if(_.state==="paused"||_.state==="stopped"){if(this.#V===void 0)throw new N("internal",`Capture helper reported ${_.state} without a recording bundle.`);await this.#V.setState(_.state,_.logicalTimeUs)}return this.#w={...this.#w,availableSources:_.availableSources,completedSegmentCount:_.completedSegmentCount,effectiveConfig:$==="idle"?null:this.#j,lastInterruption:_.lastInterruption,logicalTimeUs:_.logicalTimeUs,permissions:HC(_),recordingId:$==="idle"?null:this.#w.recordingId,recordingRoot:$==="idle"?null:this.#w.recordingRoot,sources:_.sources,state:$,updatedAt:this.#Q().toISOString()},await iV(this.#_,this.#w),this.#w})}async stop(){if(this.#w.state==="idle")throw new N("conflict","No recording is active.");return await this.#D(async()=>{let _=await this.#C({command:"stop",protocolVersion:g8,requestId:this.#K("stop")});if(_.event!=="session-completed")throw new N("invalid-data","Capture helper did not complete the session.");let $={...this.#w,completedSegmentCount:_.segmentCount,logicalTimeUs:_.durationUs,state:"idle",updatedAt:this.#Q().toISOString()};return this.#w=$,await aV(tV(this.#_),{force:!0}),$})}async close(){if(this.#W)return;let _=this.#Y;if(_===void 0){this.#W=!0;return}try{try{let $=this.#V!==void 0&&!this.#H,F=await this.#C({command:"shutdown",protocolVersion:g8,requestId:this.#K("shutdown")});if(F.event!=="shutdown")throw new N("invalid-data",`Capture helper emitted ${F.event} while shutting down.`);if($&&!this.#H)throw new N("invalid-data","Capture helper shut down without completing the active session.");if(this.#H)await aV(tV(this.#_),{force:!0})}catch($){return await this.#k($)}}finally{this.#W=!0,this.#Y=void 0,await _.close()}}}async function IH(_,$,F){switch($){case"start":if(F===void 0)throw new N("internal","Start options are missing.");return await _.start(F);case"pause":return await _.pause();case"resume":return await _.resume();case"stop":return await _.stop();case"status":return await _.status()}}function O2(_,$){let F=/^([0-9]+)f$/u.exec(_.trim());if(F!==null){if($===void 0)throw new N("usage",`Frame time ${_} requires --fps.`);if(!Number.isFinite($)||$<=0||$>1000)throw new N("usage","--fps must be a finite number greater than 0 and at most 1000.");let w=Number(F[1]),Q=Math.round(w*1e6/$);if(!Number.isSafeInteger(w)||!Number.isSafeInteger(Q))throw new N("usage",`Frame time is outside the safe range: ${_}`);return Q}try{return Hl(_)}catch(w){throw new N("usage",w instanceof Error?w.message:String(w))}}import{z as n5}from"zod";var cI=n5.string().min(1).max(512).refine((_)=>!/[\r\n]/u.test(_),"Next command must fit on one line.");function OC(_,$){return{remove:`slopcamera project edit ${_} camera remove ${$} --json`,show:`slopcamera project edit ${_} camera show --json`}}var NE0=n5.strictObject({kind:n5.enum(["all","explicit","largest"]),requireAllSelected:n5.boolean(),trackIds:n5.array(__).min(1).max(64)}).superRefine((_,$)=>{if(new Set(_.trackIds).size!==_.trackIds.length)$.addIssue({code:"custom",message:"Camera receipt track IDs must be unique."});if(_.kind==="largest"&&_.requireAllSelected)$.addIssue({code:"custom",message:"Dynamic largest-visible selection cannot require every candidate track."})}),sI=n5.strictObject({cameraMoveId:B$,cameraMoves:n5.number().int().safe().positive().max(4096),keyframeCount:n5.number().int().safe().min(2).max(4096),nextCommands:n5.strictObject({remove:cI,show:cI}),operation:n5.enum(["follow-faces","path","push","reframe"]),planHash:P,projectId:e0,selection:NE0.nullable()}).superRefine((_,$)=>{if(_.operation==="follow-faces"!==(_.selection!==null))$.addIssue({code:"custom",message:"Only face-follow camera receipts carry a face selection."});let F=OC(_.projectId,_.cameraMoveId);if(_.nextCommands.show!==F.show)$.addIssue({code:"custom",message:"Camera receipt show command must exactly match its project ID.",path:["nextCommands","show"]});if(_.nextCommands.remove!==F.remove)$.addIssue({code:"custom",message:"Camera receipt remove command must exactly match its project and camera move IDs.",path:["nextCommands","remove"]})}),pI=n5.strictObject({cameraMoveId:B$,cameraMoves:n5.number().int().safe().nonnegative().max(4096),keyframeCount:n5.number().int().safe().min(2).max(4096),nextCommands:n5.strictObject({show:cI}),operation:n5.literal("remove"),planHash:P,projectId:e0}).superRefine((_,$)=>{let F=OC(_.projectId,_.cameraMoveId);if(_.nextCommands.show!==F.show)$.addIssue({code:"custom",message:"Camera receipt show command must exactly match its project ID.",path:["nextCommands","show"]})}),GV1=n5.union([sI,pI]);import{randomUUID as HE0}from"crypto";import{constants as yH}from"fs";import{lstat as R10,mkdtemp as WE0,open as E10,rm as KE0}from"fs/promises";import{join as fH}from"path";var M10="slopcamera-whisper-cpp-word-timestamps-v1",OE0="pcm-s16le-16000hz-mono-wav-v1",fZ=16000,LE0=8589934592,q10=67108864,GE0=1e6,b10=1048576;function eV(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function LC(_){return typeof _==="string"&&_.length>0&&!_.includes("\x00")}function GC(_){if(typeof _!=="string")return null;let $=_.trim().replaceAll("_","-").toLocaleLowerCase("en-US");if($==="auto")return $;if(!/^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/u.test($))return null;return $}function nI(_){let $=GC(_);return $===null||$==="auto"?$:$.split("-")[0]??null}function P10(_){if(GC(_.language)===null)throw new N("usage","Speech language must be auto or a BCP-47-style language tag.");if(!Number.isSafeInteger(_.threads)||_.threads<1||_.threads>256)throw new N("usage","whisper.cpp threads must be an integer from 1 through 256.");if(!Number.isSafeInteger(_.processors)||_.processors<1||_.processors>64)throw new N("usage","whisper.cpp processors must be an integer from 1 through 64.");if(!Number.isFinite(_.minimumFillerConfidence)||_.minimumFillerConfidence<0||_.minimumFillerConfidence>1)throw new N("usage","Minimum filler confidence must be between zero and one.");if(!Number.isSafeInteger(_.speechHandleUs)||_.speechHandleUs<0)throw new N("usage","Speech handle must be a nonnegative integer number of microseconds.")}function DE0(_){P10(_.config);for(let F of[_.runtime.executable,_.runtime.modelPath,_.inputWavPath,_.outputPrefix])if(!LC(F)||F.length>8192)throw new N("usage","whisper.cpp executable, model, and media paths must be bounded, nonempty, and NUL-free.");if(!LC(_.runtime.version)||_.runtime.version.length>128)throw new N("usage","whisper.cpp version must be a nonempty, NUL-free string of at most 128 characters.");let $=nI(_.config.language);if($===null)throw new N("usage","Speech language is invalid.");return[_.runtime.executable,"--model",_.runtime.modelPath,"--file",_.inputWavPath,"--language",$,"--threads",String(_.config.threads),"--processors",String(_.config.processors),..._.config.useGpu?[]:["--no-gpu"],"--split-on-word","--max-len","1","--output-json-full","--output-file",_.outputPrefix,"--no-prints"]}function n4(_){return new N("invalid-data",`whisper.cpp word timestamps are unavailable: ${_}. Use a whisper.cpp build that supports full JSON word output.`)}function zE0(_){if(typeof _!=="string")return null;let $=_.normalize("NFKC").trim();if($.length===0||$.length>256||/[\r\n\0]/u.test($))return null;return $}function CE0(_){let $=_.trim();return/^\[_.*_\]$/u.test($)||/^<\|.*\|>$/u.test($)}function AE0(_,$){if(!Array.isArray(_)||_.length===0||_.length>4096)return null;let F=[];for(let Q of _){if(!eV(Q)||typeof Q.text!=="string")return null;if(CE0(Q.text)||Q.text.trim()==="")continue;if(typeof Q.p!=="number"||!Number.isFinite(Q.p)||Q.p<0||Q.p>1)return null;F.push({confidence:Q.p,text:Q.text})}if(F.length===0)return null;if(F.map((Q)=>Q.text).join("").normalize("NFKC").replace(/\s+/gu,"")!==$.replace(/\s+/gu,""))return null;return Math.min(...F.map((Q)=>Q.confidence))}function BE0(_,$){if(!Number.isSafeInteger($)||$<=0)throw new N("invalid-data","Speech analysis duration must be a positive integer number of microseconds.");let F=_;if(typeof _==="string"){if(new TextEncoder().encode(_).byteLength>q10)throw n4("full JSON output exceeds the 64 MiB limit");try{F=JSON.parse(_)}catch{throw n4("full JSON output is malformed")}}if(!eV(F)||!Array.isArray(F.transcription))throw n4("full JSON output has no transcription array");if(F.transcription.length>GE0)throw n4("full JSON output exceeds the one-million-word limit");let Q=[F.language,eV(F.result)?F.result.language:void 0,eV(F.transcription_info)?F.transcription_info.language:void 0].filter((V)=>V!==void 0).map((V)=>GC(V));if(Q.some((V)=>V===null||V==="auto"))throw n4("detected language is invalid");let Z=[...new Set(Q)];if(Z.length>1)throw n4("detected language fields disagree");let J=[],X=0;for(let V of F.transcription){if(!eV(V)||!eV(V.offsets))throw n4("a transcription item has no numeric offsets");let Y=zE0(V.text);if(Y===null||/\s/u.test(Y))throw n4("the output contains a segment that is not one word");let j=V.offsets.from,H=V.offsets.to;if(!Number.isSafeInteger(j)||!Number.isSafeInteger(H)||j<0||H<=j)throw n4("a word has invalid millisecond offsets");let K=j*1000,W=H*1000;if(!Number.isSafeInteger(K)||!Number.isSafeInteger(W)||K<X||W>$)throw n4("word offsets overlap, exceed the asset, or are not safely representable");let O=AE0(V.tokens,Y);if(O===null)throw n4("a word has no matching token probability");J.push({confidence:O,range:{endUs:W,startUs:K},speaker:null,text:Y}),X=W}if(J.length>0&&Z[0]===void 0)throw n4("full JSON output does not identify the detected language");return{detectedLanguage:Z[0]??null,words:J}}function SH(_){return(_/1e6).toFixed(6).replace(/0+$/u,"").replace(/\.$/u,"")}async function TE0(_,$,F,w){let Q;try{Q=await R10(_)}catch{throw new N("subprocess","FFmpeg speech decode did not create its WAV output.")}if(!Q.isFile()||Q.isSymbolicLink()||Q.size<44||Q.size>w||!Number.isSafeInteger(Q.size))throw new N("invalid-data","FFmpeg speech decode produced an unsafe or unexpectedly sized WAV output.");let Z=await E10(_,yH.O_RDONLY|yH.O_NOFOLLOW);try{let J=await Z.stat();if(!J.isFile()||J.dev!==Q.dev||J.ino!==Q.ino||J.size!==Q.size)throw new N("conflict","Decoded speech WAV changed before validation.");let X=async(D,z)=>{let C=Buffer.allocUnsafe(D);if((await Z.read(C,0,D,z)).bytesRead!==D)throw new N("invalid-data","Decoded speech WAV has a truncated chunk header.");return C},V=await X(12,0);if(V.toString("ascii",0,4)!=="RIFF"||V.toString("ascii",8,12)!=="WAVE")throw new N("invalid-data","FFmpeg speech decode did not produce a RIFF/WAVE file.");if(V.readUInt32LE(4)+8!==J.size)throw new N("invalid-data","Decoded speech WAV declares an incomplete or trailing RIFF payload.");let Y=null,j=!1,H=12,K=0;while(H+8<=J.size&&K<256){let D=await X(8,H),z=D.toString("ascii",0,4),C=D.readUInt32LE(4),A=H+8,B=A+C+C%2;if(!Number.isSafeInteger(B)||B>J.size)throw new N("invalid-data","Decoded speech WAV contains a truncated chunk.");if(z==="fmt "){if(C<16)throw new N("invalid-data","Decoded speech WAV has an incomplete format chunk.");let T=await X(16,A);j=T.readUInt16LE(0)===1&&T.readUInt16LE(2)===1&&T.readUInt32LE(4)===fZ&&T.readUInt16LE(12)===2&&T.readUInt16LE(14)===16}else if(z==="data")Y=C;H=B,K+=1}if(!j||Y===null||Y%2!==0)throw new N("invalid-data","Decoded speech WAV does not contain 16 kHz mono signed-16 PCM data.");let W=Math.round($*fZ/1e6),O=Y/2,L=Math.max(2,F*2);if(Math.abs(O-W)>L)throw new N("invalid-data","FFmpeg speech decode produced incomplete PCM timeline coverage.",{actualSamples:O,expectedSamples:W,sampleTolerance:L});let G=await Z.stat();if(G.dev!==J.dev||G.ino!==J.ino||G.size!==J.size||G.mtimeMs!==J.mtimeMs||G.ctimeMs!==J.ctimeMs)throw new N("conflict","Decoded speech WAV changed during validation.")}finally{await Z.close()}}async function UE0(_){if(!LC(_.ffmpeg)||!LC(_.outputPath))throw new N("usage","FFmpeg and decoded audio paths must be nonempty and NUL-free.");let $=Math.ceil(_.assetDurationUs*fZ*2/1e6)+1048576;if(!Number.isSafeInteger($)||$>LE0)throw new N("invalid-data","Decoded speech PCM would exceed its 8 GiB limit.");let F=[],w=[],Q=[],Z=0;for(let[X,V]of _.stream.segments.entries()){if(V.assetRange.startUs>Z){let j=`gap_${X}`;w.push(`anullsrc=r=${fZ}:cl=mono:d=${SH(V.assetRange.startUs-Z)}[${j}]`),Q.push(j)}F.push("-i",await f1({expected:{bytes:V.bytes,sha256:V.sha256},label:`Speech segment ${V.path}:${V.streamIndex}`,path:V.path,repositoryRoot:_.repositoryRoot}));let Y=`speech_${X}`;w.push(`[${X}:${V.streamIndex}]atrim=start=${SH(V.fileRange.startUs)}:end=${SH(V.fileRange.endUs)},asetpts=PTS-STARTPTS,aresample=${fZ},aformat=sample_fmts=s16:channel_layouts=mono[${Y}]`),Q.push(Y),Z=V.assetRange.endUs}if(Z<_.assetDurationUs)w.push(`anullsrc=r=${fZ}:cl=mono:d=${SH(_.assetDurationUs-Z)}[gap_tail]`),Q.push("gap_tail");if(Q.length===0)throw new N("invalid-data",`Audio stream ${_.stream.streamId} has no media segments.`);w.push(`${Q.map((X)=>`[${X}]`).join("")}concat=n=${Q.length}:v=0:a=1[decoded]`);let J=await _.runner.run([_.ffmpeg,"-hide_banner","-nostdin","-y",...F,"-filter_complex",w.join(";"),"-map","[decoded]","-vn","-c:a","pcm_s16le","-ac","1","-ar",String(fZ),"-t",SH(_.assetDurationUs),"-fs",String($),_.outputPath],{maxOutputBytes:b10});if(J.exitCode!==0)throw new N("subprocess",`FFmpeg speech decode failed: ${J.stderr.trim().slice(-4000)||`exit ${J.exitCode}`}`);await TE0(_.outputPath,_.assetDurationUs,_.stream.segments.length,$)}async function kE0(_,$){try{let F=await R10(_);if(!F.isFile()||F.isSymbolicLink()||F.size<=0)throw n4("full JSON output is missing or unsafe");if(F.size>$)throw n4("full JSON output exceeds the 64 MiB limit");let w=await E10(_,yH.O_RDONLY|yH.O_NOFOLLOW|yH.O_NONBLOCK);try{let Q=await w.stat();if(!Q.isFile()||Q.size!==F.size||Q.dev!==F.dev||Q.ino!==F.ino)throw n4("full JSON output changed before it could be read");let Z=await w.readFile(),J=await w.stat();if(Z.byteLength!==Q.size||J.size!==Q.size||J.mtimeMs!==Q.mtimeMs)throw n4("full JSON output changed while it was being read");try{return new TextDecoder("utf-8",{fatal:!0}).decode(Z)}catch{throw n4("full JSON output is not valid UTF-8")}}finally{await w.close()}}catch(F){if(F instanceof N)throw F;throw n4("full JSON output could not be read safely")}}async function ME0(_){let $=[..._.project.analyses].filter((J)=>J.kind==="music"&&J.assetId===_.subject.assetId&&J.streamId===_.subject.streamId).sort((J,X)=>X.createdAt.localeCompare(J.createdAt)||String(X.analysisId).localeCompare(String(J.analysisId)))[0];if($===void 0)return null;let F;try{F=a4.parse(await EJ(_.fileSystem,$.path))}catch(J){throw new N("invalid-data",`Latest music analysis ${$.analysisId} cannot be loaded: ${String(J)}`)}if(F.analysisId!==$.analysisId||F.subject.assetId!==_.subject.assetId||F.subject.streamId!==_.subject.streamId||F.subject.integritySha256!==_.subject.integritySha256)throw new N("conflict",`Latest music analysis ${$.analysisId} is stale for the selected audio stream.`);let Q=_.project.assets.find((J)=>J.assetId===_.subject.assetId)?.streams.find((J)=>J.streamId===_.subject.streamId);if(Q?.kind!=="audio")throw new N("invalid-data",`Music analysis ${$.analysisId} has no current audio stream.`);if(NN(F,Q),t(`${k(F)}
4656
+ `,{flag:"wx",mode:384}),await aR0(w,F)}finally{await aV(w,{force:!0})}}function HC(_){return{..._.permissions}}function A10(_,$){if(_===void 0)return;try{_(structuredClone($))}catch{}}class uI{#_;#$;#Q;#J;#F;#X;#Y;#V;#w;#j=null;#W=!1;#U=0;#Z="unknown";#H=!1;#L;#G;#N;constructor(_){this.#_=_.artifactRoot,this.#$=_.executable,this.#Q=_.io.now,this.#J=_.onCaptureEvent,this.#F=_.requestTimeoutMs??240000,this.#X=_.transportFactory??new k10,this.#N=new NC({..._.ffprobeExecutable===void 0?{}:{ffprobe:_.ffprobeExecutable},..._.runner===void 0?{}:{runner:_.runner}}),this.#w=WC(this.#Q())}async#z(){if(this.#W)throw new N("conflict","Recording controller is closed.");if(this.#Y!==void 0)return this.#Y;try{if(!(await tR0(this.#$)).isFile())throw new N("unavailable",`Capture helper is not a file: ${this.#$}`)}catch(F){if(F instanceof N)throw F;throw new N("unavailable",`Capture helper is unavailable at ${this.#$}. Run: bun run build:desktop:capture:macos`)}let _=await this.#X.spawn(this.#$);this.#Y=_;let $=yI(await _.readLine(this.#F));if(A10(this.#J,$),$.event!=="ready")throw await _.close(),this.#Y=void 0,new N("invalid-data",`Capture helper emitted ${$.event} before ready.`);return this.#Z=$.helperVersion,_}#K(_){return this.#U+=1,`cli:${_}:${this.#U}`}async#k(_){let $=this.#w.recordingId??this.#V?.manifest.recordingId??null,F=this.#w.recordingRoot,w=this.#G,Q=w??this.#w.lastInterruption,Z=structuredClone(this.#w.sources),J=Buffer.byteLength(JSON.stringify(Z))<=$E0,X={lastInterruption:Q===null?null:structuredClone(Q),logicalTimeUs:this.#w.logicalTimeUs,permissions:this.#w.permissions===null?null:structuredClone(this.#w.permissions),...J?{sources:Z}:{}},V=[],Y=this.#L,j=Y===void 0,H=async(z)=>{if(Y===void 0||this.#V===void 0)return;try{await this.#V.recordFailedSegmentCompletion(Y.segment,Y.interruption,Y.failure),j=!0;for(let C=V.length-1;C>=0;C-=1)if(V[C]?.startsWith("completion frontier"))V.splice(C,1)}catch(C){V.push(`${z}${P5(C)}`)}};await H("completion frontier: ");let K=w===void 0,W=async(z)=>{if(w===void 0||this.#V===void 0)return;try{await this.#V.recordFailureInterruption(w),K=!0;for(let C=V.length-1;C>=0;C-=1)if(V[C]?.startsWith("failure interruption"))V.splice(C,1)}catch(C){V.push(`${z}${P5(C)}`)}};await W("failure interruption: ");let O=this.#H?"stopped":"unsettled";if(this.#V!==void 0&&!this.#H){let z=this.#V.manifest.timeline.durationUs;try{await this.#V.setState("failed",z),O="failed"}catch(C){V.push(`manifest: ${P5(C)}`)}}let L=this.#Y;if(this.#Y=void 0,L!==void 0)try{await L.close()}catch(z){V.push(`helper: ${P5(z)}`)}if(!j)await H("completion frontier retry: ");if(!K)await W("failure interruption retry: ");if(O==="unsettled"&&this.#V!==void 0)try{await this.#V.setState("failed",this.#V.manifest.timeline.durationUs),O="failed";let z=V.findIndex((C)=>C.startsWith("manifest: "));if(z!==-1)V.splice(z,1)}catch(z){let C=`manifest retry: ${P5(z)}`;if(!V.includes(C))V.push(C)}try{await aV(tV(this.#_),{force:!0})}catch(z){V.push(`active state: ${P5(z)}`)}if(this.#V=void 0,this.#j=null,this.#L=void 0,this.#G=void 0,this.#H=!1,this.#w=WC(this.#Q()),V.length>0)this.#W=!0;let G=n_(_),D={controllerReusable:V.length===0,recordingId:$,recordingRoot:F,snapshot:X,terminalManifestState:O};if(V.length>0)throw new N("internal",`${G.message} Capture recovery was incomplete: ${V.join("; ")}`,{captureFailure:{code:G.code,details:G.details??null},recovery:D,recoveryErrors:V});throw new N(G.code,G.message,{...G.details??{},recovery:D})}async#M(_,$){let F=[],w=this.#Y;if(this.#Y=void 0,w!==void 0)try{await w.close()}catch(Z){F.push(`helper: ${P5(Z)}`)}try{await aV(_,{force:!0,recursive:!0}),await aV(tV(this.#_),{force:!0})}catch(Z){F.push(`recording cleanup: ${P5(Z)}`)}if(this.#V=void 0,this.#j=null,this.#L=void 0,this.#G=void 0,this.#H=!1,this.#w=WC(this.#Q()),F.length>0)this.#W=!0;let Q=n_($);if(F.length>0)throw new N("internal",`${Q.message} Capture recovery was incomplete: ${F.join("; ")}`,{captureFailure:{code:Q.code,details:Q.details??null},recoveryErrors:F});throw Q}async#D(_){try{return await _()}catch($){if($ instanceof mI)throw $;return await this.#k($)}}#A(){let _=this.#V?.manifest;return{completedSegmentCount:_?.timeline.nativeClock.segments.length??this.#w.completedSegmentCount,lastInterruption:this.#w.lastInterruption,logicalTimeUs:_?.timeline.durationUs??this.#w.logicalTimeUs,priorSnapshotLogicalTimeUs:this.#w.logicalTimeUs,sessionCompletionPersisted:this.#H,sources:this.#w.sources}}async#R(_){if(_.event==="segment-completed"){try{await this.#V?.appendSegment(_.segment,_.interruption)}catch($){throw this.#L={failure:$,interruption:_.interruption,segment:_.segment},this.#w={...this.#w,completedSegmentCount:this.#w.completedSegmentCount+1,lastInterruption:_.interruption??this.#w.lastInterruption,logicalTimeUs:Math.max(this.#w.logicalTimeUs,_.segment.clock.end.sourceTimeUs),updatedAt:this.#Q().toISOString()},$}this.#w={...this.#w,completedSegmentCount:this.#w.completedSegmentCount+1,lastInterruption:_.interruption??this.#w.lastInterruption,logicalTimeUs:Math.max(this.#w.logicalTimeUs,_.segment.clock.end.sourceTimeUs),updatedAt:this.#Q().toISOString()}}if(_.event==="session-completed"){if(this.#V===void 0)throw new N("internal","Capture helper completed a session without an initialized recording bundle.");await this.#V.setState("stopped",_.durationUs),this.#H=!0,this.#w={...this.#w,completedSegmentCount:_.segmentCount,logicalTimeUs:_.durationUs,state:"idle",updatedAt:this.#Q().toISOString()}}}async#C(_){let $=await this.#z();await $.write(N10(_));let F=[],w=_E0[_.command],Q=this.#A();while(!0){let Z=yI(await $.readLine(this.#F));if(!("requestId"in Z)||Z.requestId!==_.requestId)throw new N("invalid-data",`Capture helper response ID ${"requestId"in Z?Z.requestId:"<missing>"} did not match ${_.requestId}.`);if(A10(this.#J,Z),Z.event==="error"){let V=_.command==="resume"&&F.length===1&&F[0]?.event==="segment-completed";if(F.length>0&&!V)throw e2(_,[...F,Z],"Errors may not follow completion evidence.");let Y=[...F,Z],j=XE0(_,F,Z,Q);if(F.length>0)z10(_,Y,Q);let K=Z.recoverable&&(_.command==="resume"||Z.code==="invalid-state")&&j!=="new-frontier";if(!K&&Z.interruption!==null)this.#G=Z.interruption;for(let W of F)await this.#R(W);if(Z.interruption!==null)this.#w={...this.#w,lastInterruption:Z.interruption,updatedAt:this.#Q().toISOString()};if(Z.interruption!==null&&this.#V!==void 0){let W=this.#V.manifest.interruptions.some((O)=>KC(O,Z.interruption));if(K&&!W)throw e2(_,Y,"A recoverable error cannot introduce interruption evidence that was not persisted by completion.");if(!K)await this.#V.recordFailureInterruption(Z.interruption)}if(_.command==="resume"&&K&&Z.state==="paused"){if(this.#V===void 0)throw new N("internal","Capture helper rejected resume without a recording bundle.");this.#w={...this.#w,state:"paused",updatedAt:this.#Q().toISOString()},await this.#V.setState("paused",this.#w.logicalTimeUs),await iV(this.#_,this.#w)}else if(K&&this.#w.recordingId!==null)await iV(this.#_,this.#w);if(K)throw new mI(Z.code==="invalid-state"?"conflict":"unavailable",Z);throw new N(Z.recoverable?"unavailable":"subprocess",`Capture helper ${Z.code}: ${Z.message}`,{helperCode:Z.code,interruption:Z.interruption,recoverable:Z.recoverable,state:Z.state})}F.push(Z);let J=w.filter((V)=>FE0(V,F));if(J.length===0)throw e2(_,F);if(J.find((V)=>V.length===F.length)!==void 0){z10(_,F,Q);for(let V of F)await this.#R(V);return Z}}}async start(_){if(this.#w.state!=="idle")throw new N("conflict",`Cannot start while recording is ${this.#w.state}.`);let $=`rec_${this.#Q().toISOString().replaceAll(/[-:.TZ]/gu,"")}_${B10().slice(0,8)}`,F=lI(this.#_,$);this.#V=void 0,this.#j=null,this.#L=void 0,this.#G=void 0,this.#H=!1,await J1(this.#_),await oR0(F,{mode:448,recursive:!1});let w={..._,metadata:!0},Q={camera:{..._.camera},displays:_.displays.kind==="all"?{kind:"all"}:{displayIds:[..._.displays.displayIds],kind:"selected"},excludedBundleIdentifiers:["com.hraness.slopcamera"],interactionEventProcessIdentifier:_.interactionEventProcessIdentifier??null,metadata:!0,microphone:{..._.microphone},strictSources:_.strictInputs,systemAudio:_.systemAudio,typedText:_.typedText,typedTextFocusIdentities:_.typedTextFocusIdentities===void 0||_.typedTextFocusIdentities===null?null:_.typedTextFocusIdentities.map((Z)=>({...Z}))};try{let Z=await this.#C({command:"configure",options:Q,protocolVersion:g8,requestId:this.#K("configure"),sessionDirectory:F});if(Z.event!=="configured")throw new N("invalid-data","Capture helper did not acknowledge configuration.");this.#j=w,this.#V=new xI({bundleRoot:F,captureOptions:Q,configured:Z,helperVersion:this.#Z,now:this.#Q,recordingId:$,toolVersion:"3.2.5",verifier:this.#N}),await this.#V.initialize(),this.#w={availableSources:Z.availableSources,completedSegmentCount:0,effectiveConfig:w,lastInterruption:Z.lastInterruption,logicalTimeUs:0,permissions:HC(Z),recordingId:$,recordingRoot:F,sources:Z.sources,state:"paused",updatedAt:this.#Q().toISOString()};let J=await this.#C({command:"start",protocolVersion:g8,requestId:this.#K("start")});if(J.event!=="segment-started")throw new N("invalid-data","Capture helper did not start a segment.");return await this.#V.setCaptureEnvironment(J.permissions,J.sources),this.#w={...this.#w,logicalTimeUs:J.startUs,permissions:HC(J),sources:J.sources,state:"recording",updatedAt:this.#Q().toISOString()},await this.#V.setState("recording",J.startUs),await iV(this.#_,this.#w),this.#w}catch(Z){if(this.#V===void 0)return await this.#M(F,Z);return await this.#k(Z)}}async pause(){if(this.#w.state!=="recording")throw new N("conflict",`Cannot pause while recording is ${this.#w.state}.`);return await this.#D(async()=>{if((await this.#C({command:"pause",protocolVersion:g8,requestId:this.#K("pause")})).event!=="segment-completed")throw new N("invalid-data","Capture helper did not complete the active segment.");return this.#w={...this.#w,state:"paused",updatedAt:this.#Q().toISOString()},await this.#V?.setState("paused",this.#w.logicalTimeUs),await iV(this.#_,this.#w),this.#w})}async resume(){if(this.#w.state==="idle"||this.#w.recordingId===null)throw new N("conflict",`Cannot resume while recording is ${this.#w.state}.`);return await this.#D(async()=>{let _=await this.#C({command:"resume",protocolVersion:g8,requestId:this.#K("resume")});if(_.event!=="segment-started")throw new N("invalid-data","Capture helper did not resume capture.");return await this.#V?.setCaptureEnvironment(_.permissions,_.sources),this.#w={...this.#w,logicalTimeUs:_.startUs,permissions:HC(_),sources:_.sources,state:"recording",updatedAt:this.#Q().toISOString()},await this.#V?.setState("recording",this.#w.logicalTimeUs),await iV(this.#_,this.#w),this.#w})}async status(){if(this.#Y===void 0)return this.#w=await PH(this.#_,this.#Q),this.#w;return await this.#D(async()=>{let _=await this.#C({command:"status",protocolVersion:g8,requestId:this.#K("status")});if(_.event!=="status")throw new N("invalid-data","Capture helper omitted status.");let $=_.state==="recording"?"recording":_.state==="paused"?"paused":"idle";if(_.state==="paused"||_.state==="stopped"){if(this.#V===void 0)throw new N("internal",`Capture helper reported ${_.state} without a recording bundle.`);await this.#V.setState(_.state,_.logicalTimeUs)}return this.#w={...this.#w,availableSources:_.availableSources,completedSegmentCount:_.completedSegmentCount,effectiveConfig:$==="idle"?null:this.#j,lastInterruption:_.lastInterruption,logicalTimeUs:_.logicalTimeUs,permissions:HC(_),recordingId:$==="idle"?null:this.#w.recordingId,recordingRoot:$==="idle"?null:this.#w.recordingRoot,sources:_.sources,state:$,updatedAt:this.#Q().toISOString()},await iV(this.#_,this.#w),this.#w})}async stop(){if(this.#w.state==="idle")throw new N("conflict","No recording is active.");return await this.#D(async()=>{let _=await this.#C({command:"stop",protocolVersion:g8,requestId:this.#K("stop")});if(_.event!=="session-completed")throw new N("invalid-data","Capture helper did not complete the session.");let $={...this.#w,completedSegmentCount:_.segmentCount,logicalTimeUs:_.durationUs,state:"idle",updatedAt:this.#Q().toISOString()};return this.#w=$,await aV(tV(this.#_),{force:!0}),$})}async close(){if(this.#W)return;let _=this.#Y;if(_===void 0){this.#W=!0;return}try{try{let $=this.#V!==void 0&&!this.#H,F=await this.#C({command:"shutdown",protocolVersion:g8,requestId:this.#K("shutdown")});if(F.event!=="shutdown")throw new N("invalid-data",`Capture helper emitted ${F.event} while shutting down.`);if($&&!this.#H)throw new N("invalid-data","Capture helper shut down without completing the active session.");if(this.#H)await aV(tV(this.#_),{force:!0})}catch($){return await this.#k($)}}finally{this.#W=!0,this.#Y=void 0,await _.close()}}}async function IH(_,$,F){switch($){case"start":if(F===void 0)throw new N("internal","Start options are missing.");return await _.start(F);case"pause":return await _.pause();case"resume":return await _.resume();case"stop":return await _.stop();case"status":return await _.status()}}function O2(_,$){let F=/^([0-9]+)f$/u.exec(_.trim());if(F!==null){if($===void 0)throw new N("usage",`Frame time ${_} requires --fps.`);if(!Number.isFinite($)||$<=0||$>1000)throw new N("usage","--fps must be a finite number greater than 0 and at most 1000.");let w=Number(F[1]),Q=Math.round(w*1e6/$);if(!Number.isSafeInteger(w)||!Number.isSafeInteger(Q))throw new N("usage",`Frame time is outside the safe range: ${_}`);return Q}try{return Hl(_)}catch(w){throw new N("usage",w instanceof Error?w.message:String(w))}}import{z as n5}from"zod";var cI=n5.string().min(1).max(512).refine((_)=>!/[\r\n]/u.test(_),"Next command must fit on one line.");function OC(_,$){return{remove:`slopcamera project edit ${_} camera remove ${$} --json`,show:`slopcamera project edit ${_} camera show --json`}}var NE0=n5.strictObject({kind:n5.enum(["all","explicit","largest"]),requireAllSelected:n5.boolean(),trackIds:n5.array(__).min(1).max(64)}).superRefine((_,$)=>{if(new Set(_.trackIds).size!==_.trackIds.length)$.addIssue({code:"custom",message:"Camera receipt track IDs must be unique."});if(_.kind==="largest"&&_.requireAllSelected)$.addIssue({code:"custom",message:"Dynamic largest-visible selection cannot require every candidate track."})}),sI=n5.strictObject({cameraMoveId:B$,cameraMoves:n5.number().int().safe().positive().max(4096),keyframeCount:n5.number().int().safe().min(2).max(4096),nextCommands:n5.strictObject({remove:cI,show:cI}),operation:n5.enum(["follow-faces","path","push","reframe"]),planHash:P,projectId:e0,selection:NE0.nullable()}).superRefine((_,$)=>{if(_.operation==="follow-faces"!==(_.selection!==null))$.addIssue({code:"custom",message:"Only face-follow camera receipts carry a face selection."});let F=OC(_.projectId,_.cameraMoveId);if(_.nextCommands.show!==F.show)$.addIssue({code:"custom",message:"Camera receipt show command must exactly match its project ID.",path:["nextCommands","show"]});if(_.nextCommands.remove!==F.remove)$.addIssue({code:"custom",message:"Camera receipt remove command must exactly match its project and camera move IDs.",path:["nextCommands","remove"]})}),pI=n5.strictObject({cameraMoveId:B$,cameraMoves:n5.number().int().safe().nonnegative().max(4096),keyframeCount:n5.number().int().safe().min(2).max(4096),nextCommands:n5.strictObject({show:cI}),operation:n5.literal("remove"),planHash:P,projectId:e0}).superRefine((_,$)=>{let F=OC(_.projectId,_.cameraMoveId);if(_.nextCommands.show!==F.show)$.addIssue({code:"custom",message:"Camera receipt show command must exactly match its project ID.",path:["nextCommands","show"]})}),GV1=n5.union([sI,pI]);import{randomUUID as HE0}from"crypto";import{constants as yH}from"fs";import{lstat as R10,mkdtemp as WE0,open as E10,rm as KE0}from"fs/promises";import{join as fH}from"path";var M10="slopcamera-whisper-cpp-word-timestamps-v1",OE0="pcm-s16le-16000hz-mono-wav-v1",fZ=16000,LE0=8589934592,q10=67108864,GE0=1e6,b10=1048576;function eV(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function LC(_){return typeof _==="string"&&_.length>0&&!_.includes("\x00")}function GC(_){if(typeof _!=="string")return null;let $=_.trim().replaceAll("_","-").toLocaleLowerCase("en-US");if($==="auto")return $;if(!/^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/u.test($))return null;return $}function nI(_){let $=GC(_);return $===null||$==="auto"?$:$.split("-")[0]??null}function P10(_){if(GC(_.language)===null)throw new N("usage","Speech language must be auto or a BCP-47-style language tag.");if(!Number.isSafeInteger(_.threads)||_.threads<1||_.threads>256)throw new N("usage","whisper.cpp threads must be an integer from 1 through 256.");if(!Number.isSafeInteger(_.processors)||_.processors<1||_.processors>64)throw new N("usage","whisper.cpp processors must be an integer from 1 through 64.");if(!Number.isFinite(_.minimumFillerConfidence)||_.minimumFillerConfidence<0||_.minimumFillerConfidence>1)throw new N("usage","Minimum filler confidence must be between zero and one.");if(!Number.isSafeInteger(_.speechHandleUs)||_.speechHandleUs<0)throw new N("usage","Speech handle must be a nonnegative integer number of microseconds.")}function DE0(_){P10(_.config);for(let F of[_.runtime.executable,_.runtime.modelPath,_.inputWavPath,_.outputPrefix])if(!LC(F)||F.length>8192)throw new N("usage","whisper.cpp executable, model, and media paths must be bounded, nonempty, and NUL-free.");if(!LC(_.runtime.version)||_.runtime.version.length>128)throw new N("usage","whisper.cpp version must be a nonempty, NUL-free string of at most 128 characters.");let $=nI(_.config.language);if($===null)throw new N("usage","Speech language is invalid.");return[_.runtime.executable,"--model",_.runtime.modelPath,"--file",_.inputWavPath,"--language",$,"--threads",String(_.config.threads),"--processors",String(_.config.processors),..._.config.useGpu?[]:["--no-gpu"],"--split-on-word","--max-len","1","--output-json-full","--output-file",_.outputPrefix,"--no-prints"]}function n4(_){return new N("invalid-data",`whisper.cpp word timestamps are unavailable: ${_}. Use a whisper.cpp build that supports full JSON word output.`)}function zE0(_){if(typeof _!=="string")return null;let $=_.normalize("NFKC").trim();if($.length===0||$.length>256||/[\r\n\0]/u.test($))return null;return $}function CE0(_){let $=_.trim();return/^\[_.*_\]$/u.test($)||/^<\|.*\|>$/u.test($)}function AE0(_,$){if(!Array.isArray(_)||_.length===0||_.length>4096)return null;let F=[];for(let Q of _){if(!eV(Q)||typeof Q.text!=="string")return null;if(CE0(Q.text)||Q.text.trim()==="")continue;if(typeof Q.p!=="number"||!Number.isFinite(Q.p)||Q.p<0||Q.p>1)return null;F.push({confidence:Q.p,text:Q.text})}if(F.length===0)return null;if(F.map((Q)=>Q.text).join("").normalize("NFKC").replace(/\s+/gu,"")!==$.replace(/\s+/gu,""))return null;return Math.min(...F.map((Q)=>Q.confidence))}function BE0(_,$){if(!Number.isSafeInteger($)||$<=0)throw new N("invalid-data","Speech analysis duration must be a positive integer number of microseconds.");let F=_;if(typeof _==="string"){if(new TextEncoder().encode(_).byteLength>q10)throw n4("full JSON output exceeds the 64 MiB limit");try{F=JSON.parse(_)}catch{throw n4("full JSON output is malformed")}}if(!eV(F)||!Array.isArray(F.transcription))throw n4("full JSON output has no transcription array");if(F.transcription.length>GE0)throw n4("full JSON output exceeds the one-million-word limit");let Q=[F.language,eV(F.result)?F.result.language:void 0,eV(F.transcription_info)?F.transcription_info.language:void 0].filter((V)=>V!==void 0).map((V)=>GC(V));if(Q.some((V)=>V===null||V==="auto"))throw n4("detected language is invalid");let Z=[...new Set(Q)];if(Z.length>1)throw n4("detected language fields disagree");let J=[],X=0;for(let V of F.transcription){if(!eV(V)||!eV(V.offsets))throw n4("a transcription item has no numeric offsets");let Y=zE0(V.text);if(Y===null||/\s/u.test(Y))throw n4("the output contains a segment that is not one word");let j=V.offsets.from,H=V.offsets.to;if(!Number.isSafeInteger(j)||!Number.isSafeInteger(H)||j<0||H<=j)throw n4("a word has invalid millisecond offsets");let K=j*1000,W=H*1000;if(!Number.isSafeInteger(K)||!Number.isSafeInteger(W)||K<X||W>$)throw n4("word offsets overlap, exceed the asset, or are not safely representable");let O=AE0(V.tokens,Y);if(O===null)throw n4("a word has no matching token probability");J.push({confidence:O,range:{endUs:W,startUs:K},speaker:null,text:Y}),X=W}if(J.length>0&&Z[0]===void 0)throw n4("full JSON output does not identify the detected language");return{detectedLanguage:Z[0]??null,words:J}}function SH(_){return(_/1e6).toFixed(6).replace(/0+$/u,"").replace(/\.$/u,"")}async function TE0(_,$,F,w){let Q;try{Q=await R10(_)}catch{throw new N("subprocess","FFmpeg speech decode did not create its WAV output.")}if(!Q.isFile()||Q.isSymbolicLink()||Q.size<44||Q.size>w||!Number.isSafeInteger(Q.size))throw new N("invalid-data","FFmpeg speech decode produced an unsafe or unexpectedly sized WAV output.");let Z=await E10(_,yH.O_RDONLY|yH.O_NOFOLLOW);try{let J=await Z.stat();if(!J.isFile()||J.dev!==Q.dev||J.ino!==Q.ino||J.size!==Q.size)throw new N("conflict","Decoded speech WAV changed before validation.");let X=async(D,z)=>{let C=Buffer.allocUnsafe(D);if((await Z.read(C,0,D,z)).bytesRead!==D)throw new N("invalid-data","Decoded speech WAV has a truncated chunk header.");return C},V=await X(12,0);if(V.toString("ascii",0,4)!=="RIFF"||V.toString("ascii",8,12)!=="WAVE")throw new N("invalid-data","FFmpeg speech decode did not produce a RIFF/WAVE file.");if(V.readUInt32LE(4)+8!==J.size)throw new N("invalid-data","Decoded speech WAV declares an incomplete or trailing RIFF payload.");let Y=null,j=!1,H=12,K=0;while(H+8<=J.size&&K<256){let D=await X(8,H),z=D.toString("ascii",0,4),C=D.readUInt32LE(4),A=H+8,B=A+C+C%2;if(!Number.isSafeInteger(B)||B>J.size)throw new N("invalid-data","Decoded speech WAV contains a truncated chunk.");if(z==="fmt "){if(C<16)throw new N("invalid-data","Decoded speech WAV has an incomplete format chunk.");let T=await X(16,A);j=T.readUInt16LE(0)===1&&T.readUInt16LE(2)===1&&T.readUInt32LE(4)===fZ&&T.readUInt16LE(12)===2&&T.readUInt16LE(14)===16}else if(z==="data")Y=C;H=B,K+=1}if(!j||Y===null||Y%2!==0)throw new N("invalid-data","Decoded speech WAV does not contain 16 kHz mono signed-16 PCM data.");let W=Math.round($*fZ/1e6),O=Y/2,L=Math.max(2,F*2);if(Math.abs(O-W)>L)throw new N("invalid-data","FFmpeg speech decode produced incomplete PCM timeline coverage.",{actualSamples:O,expectedSamples:W,sampleTolerance:L});let G=await Z.stat();if(G.dev!==J.dev||G.ino!==J.ino||G.size!==J.size||G.mtimeMs!==J.mtimeMs||G.ctimeMs!==J.ctimeMs)throw new N("conflict","Decoded speech WAV changed during validation.")}finally{await Z.close()}}async function UE0(_){if(!LC(_.ffmpeg)||!LC(_.outputPath))throw new N("usage","FFmpeg and decoded audio paths must be nonempty and NUL-free.");let $=Math.ceil(_.assetDurationUs*fZ*2/1e6)+1048576;if(!Number.isSafeInteger($)||$>LE0)throw new N("invalid-data","Decoded speech PCM would exceed its 8 GiB limit.");let F=[],w=[],Q=[],Z=0;for(let[X,V]of _.stream.segments.entries()){if(V.assetRange.startUs>Z){let j=`gap_${X}`;w.push(`anullsrc=r=${fZ}:cl=mono:d=${SH(V.assetRange.startUs-Z)}[${j}]`),Q.push(j)}F.push("-i",await f1({expected:{bytes:V.bytes,sha256:V.sha256},label:`Speech segment ${V.path}:${V.streamIndex}`,path:V.path,repositoryRoot:_.repositoryRoot}));let Y=`speech_${X}`;w.push(`[${X}:${V.streamIndex}]atrim=start=${SH(V.fileRange.startUs)}:end=${SH(V.fileRange.endUs)},asetpts=PTS-STARTPTS,aresample=${fZ},aformat=sample_fmts=s16:channel_layouts=mono[${Y}]`),Q.push(Y),Z=V.assetRange.endUs}if(Z<_.assetDurationUs)w.push(`anullsrc=r=${fZ}:cl=mono:d=${SH(_.assetDurationUs-Z)}[gap_tail]`),Q.push("gap_tail");if(Q.length===0)throw new N("invalid-data",`Audio stream ${_.stream.streamId} has no media segments.`);w.push(`${Q.map((X)=>`[${X}]`).join("")}concat=n=${Q.length}:v=0:a=1[decoded]`);let J=await _.runner.run([_.ffmpeg,"-hide_banner","-nostdin","-y",...F,"-filter_complex",w.join(";"),"-map","[decoded]","-vn","-c:a","pcm_s16le","-ac","1","-ar",String(fZ),"-t",SH(_.assetDurationUs),"-fs",String($),_.outputPath],{maxOutputBytes:b10});if(J.exitCode!==0)throw new N("subprocess",`FFmpeg speech decode failed: ${J.stderr.trim().slice(-4000)||`exit ${J.exitCode}`}`);await TE0(_.outputPath,_.assetDurationUs,_.stream.segments.length,$)}async function kE0(_,$){try{let F=await R10(_);if(!F.isFile()||F.isSymbolicLink()||F.size<=0)throw n4("full JSON output is missing or unsafe");if(F.size>$)throw n4("full JSON output exceeds the 64 MiB limit");let w=await E10(_,yH.O_RDONLY|yH.O_NOFOLLOW|yH.O_NONBLOCK);try{let Q=await w.stat();if(!Q.isFile()||Q.size!==F.size||Q.dev!==F.dev||Q.ino!==F.ino)throw n4("full JSON output changed before it could be read");let Z=await w.readFile(),J=await w.stat();if(Z.byteLength!==Q.size||J.size!==Q.size||J.mtimeMs!==Q.mtimeMs)throw n4("full JSON output changed while it was being read");try{return new TextDecoder("utf-8",{fatal:!0}).decode(Z)}catch{throw n4("full JSON output is not valid UTF-8")}}finally{await w.close()}}catch(F){if(F instanceof N)throw F;throw n4("full JSON output could not be read safely")}}async function ME0(_){let $=[..._.project.analyses].filter((J)=>J.kind==="music"&&J.assetId===_.subject.assetId&&J.streamId===_.subject.streamId).sort((J,X)=>X.createdAt.localeCompare(J.createdAt)||String(X.analysisId).localeCompare(String(J.analysisId)))[0];if($===void 0)return null;let F;try{F=a4.parse(await EJ(_.fileSystem,$.path))}catch(J){throw new N("invalid-data",`Latest music analysis ${$.analysisId} cannot be loaded: ${String(J)}`)}if(F.analysisId!==$.analysisId||F.subject.assetId!==_.subject.assetId||F.subject.streamId!==_.subject.streamId||F.subject.integritySha256!==_.subject.integritySha256)throw new N("conflict",`Latest music analysis ${$.analysisId} is stale for the selected audio stream.`);let Q=_.project.assets.find((J)=>J.assetId===_.subject.assetId)?.streams.find((J)=>J.streamId===_.subject.streamId);if(Q?.kind!=="audio")throw new N("invalid-data",`Music analysis ${$.analysisId} has no current audio stream.`);if(NN(F,Q),t(`${k(F)}
4657
4657
  `)!==$.sha256)throw new N("invalid-data",`Latest music analysis ${$.analysisId} failed its project-reference integrity check.`);return{analysis:F,reference:$}}function I10(_,$=Z4("speech",_.analysisId)){let F=S5.parse(_);return P4.parse({analysisId:F.analysisId,assetId:F.subject.assetId,createdAt:F.createdAt,fillerCount:F.result.status==="transcribed"?F.result.fillers.length:0,kind:"speech",path:$,sha256:t(`${k(F)}
4658
4658
  `),streamId:F.subject.streamId,wordCount:F.result.status==="transcribed"?F.result.words.length:0})}async function f10(_){P10(_.config);let $=Q$(_.project,_.source);if(_.useLatestMusicAnalysis&&_.fileSystem===void 0)throw new N("internal","A bundle filesystem is required to load music protection analysis.");let F=_.useLatestMusicAnalysis?await ME0({fileSystem:_.fileSystem,project:_.project,subject:$.subject}):null,w=fH(_.projectDirectory,"analysis","cache");await J1(fH(_.projectDirectory,"analysis")),await J1(w);let Q=await WE0(fH(w,"speech-")),Z=fH(Q,"input.wav"),J=fH(Q,"transcript");try{await UE0({assetDurationUs:$.asset.durationUs,ffmpeg:_.ffmpeg,outputPath:Z,repositoryRoot:_.repositoryRoot,runner:_.runner,stream:$.stream});let X=DE0({config:_.config,inputWavPath:Z,outputPrefix:J,runtime:_.runtime}),V=await _.runner.run(X,{maxOutputBytes:b10});if(V.exitCode!==0)throw new N("subprocess",`whisper.cpp speech analysis failed: ${V.stderr.trim().slice(-4000)||`exit ${V.exitCode}`}`);let Y=BE0(await kE0(`${J}.json`,q10),$.asset.durationUs),j=_.analysisId??`analysis_${HE0().replaceAll("-","")}`,H=_.now.toISOString(),K=GC(_.config.language);if(K!=="auto"&&Y.detectedLanguage!==null&&nI(K)!==nI(Y.detectedLanguage))throw n4("detected language does not match the requested language");let W=jl({analysisId:j,config:{language:K,minimumFillerConfidence:_.config.minimumFillerConfidence,speechHandleUs:_.config.speechHandleUs},createdAt:H,detectedLanguage:Y.detectedLanguage??(K==="auto"?"":K),durationUs:$.asset.durationUs,inputDigest:S({config:_.config,musicAnalysisId:F?.analysis.analysisId??null,pcmProfile:OE0,runtime:{executable:S(_.runtime.executable),model:S(_.runtime.modelPath),version:_.runtime.version},subject:$.subject,transcript:Y,whisperProfile:M10}),musicRegions:F?.analysis.musicRegions??[],subject:$.subject,tool:{name:"whisper.cpp",profile:M10,version:_.runtime.version},words:Y.words}),O=S5.parse(W),L=Z4("speech",O.analysisId);return{analysis:O,analysisPath:L,musicAnalysisId:F?.analysis.analysisId??null,reference:I10(O,L)}}finally{await KE0(Q,{force:!0,recursive:!0})}}async function S10(_){let $=S5.parse(_.result.analysis),F=I10($,_.result.analysisPath);if(k(F)!==k(_.result.reference))throw new N("invalid-data","Speech analysis reference does not match its validated artifact.");let w=(_.updatedAt??new Date($.createdAt)).toISOString(),Q=w.localeCompare(_.project.updatedAt)<0?_.project.updatedAt:w,Z=h1(j1.parse({..._.project,analyses:[..._.project.analyses.filter((J)=>J.analysisId!==$.analysisId),F],updatedAt:Q}));return await _8(_.fileSystem,$,_.result.analysisPath),await t4(_.fileSystem,Z),Z}var RE0="https://ai-gateway.vercel.sh/v4/ai",EE0="https://ai-gateway.vercel.sh",y10=4000000,qE0=120000,N3="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";async function bE0(){let[_,$]=await Promise.all([import("@ai-sdk/gateway-v4"),import("ai-v7")]);if(typeof _!=="object"||_===null||!("createGateway"in _)||typeof _.createGateway!=="function"||typeof $!=="object"||$===null||!("generateText"in $)||typeof $.generateText!=="function"||!("Output"in $)||typeof $.Output!=="object"||$.Output===null||!("object"in $.Output)||typeof $.Output.object!=="function")throw Error("The AI SDK scene provider is unavailable.");return{Output:$.Output,createGateway:_.createGateway,generateText:$.generateText}}function PE0(_){if(typeof _==="string")return new URL(_);return new URL(_ instanceof URL?_.href:_.url)}function IE0(_){let $=[],F="",w=0;for(;w+2<_.length;w+=3){let Z=_[w]<<16|_[w+1]<<8|_[w+2];if(F+=N3.charAt(Z>>>18&63)+N3.charAt(Z>>>12&63)+N3.charAt(Z>>>6&63)+N3.charAt(Z&63),F.length>=16384)$.push(F),F=""}let Q=_.length-w;if(Q===1){let Z=_[w]<<16;F+=N3.charAt(Z>>>18&63)+N3.charAt(Z>>>12&63)+"=="}else if(Q===2){let Z=_[w]<<16|_[w+1]<<8;F+=N3.charAt(Z>>>18&63)+N3.charAt(Z>>>12&63)+N3.charAt(Z>>>6&63)+"="}return $.push(F),$.join("")}function fE0(_,$){return`data:${_};base64,${IE0($)}`}async function SE0(_){if(_.redirected||_.status>=300&&_.status<400)throw await _.body?.cancel().catch(()=>{return}),Error("Scene Gateway redirects are forbidden.");let $=_.headers.get("content-length");if($!==null){let X=Number($);if(Number.isFinite(X)&&X>y10)throw await _.body?.cancel().catch(()=>{return}),Error("Scene Gateway response exceeded its byte bound.")}if(_.body===null)return _;let F=_.body.getReader(),w=[],Q=0;try{while(!0){let X=await F.read();if(X.done)break;if(Q+=X.value.byteLength,Q>y10)throw await F.cancel().catch(()=>{return}),Error("Scene Gateway response exceeded its byte bound.");w.push(X.value)}}finally{F.releaseLock()}let Z=new Uint8Array(Q),J=0;for(let X of w)Z.set(X,J),J+=X.byteLength;return new Response(Z,{headers:_.headers,status:_.status,statusText:_.statusText})}function yE0(_=globalThis.fetch){return async($,F)=>{let w=PE0($);if(w.origin!==EE0||w.username!==""||w.password!==""||w.pathname!=="/v4/ai"&&!w.pathname.startsWith("/v4/ai/"))throw Error("Scene Gateway request target is forbidden.");let Q=$ instanceof Request?new Request(w.href,$):new Request(w.href),Z=new Request(Q,{...F,redirect:"error"});return await SE0(await _(Z))}}function gE0(_){let $=[{text:`Describe exactly ${_.scenes.length} scenes. Frames within each scene are chronological.`,type:"text"}];for(let F of _.scenes){$.push({text:`Scene ${F.sceneId} begins.`,type:"text"});for(let[w,Q]of F.frames.entries())$.push({text:`Frame ${w+1} at ${Q.actualAssetTimeUs} microseconds.`,type:"text"}),$.push({image:fE0(Q.mediaType,Q.bytes),mediaType:Q.mediaType,type:"image"});$.push({text:`Scene ${F.sceneId} ends.`,type:"text"})}return{content:$,role:"user"}}function h10(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)?_:null}function g10(_,$){let F=h10(_)?.[$];return Number.isSafeInteger(F)&&F>=0?F:0}function hE0(_){let $=h10(_)?.modelId;return typeof $==="string"&&$.length>=1&&$.length<=256&&![...$].some((F)=>(F.codePointAt(0)??0)<=31)?$:null}function vE0(_,$){let F=kB.safeParse($);if(!F.success)throw new q4("invalid-response");let w=new Set(_.scenes.map((X)=>X.sceneId)),Q=new Set,Z=[];for(let X of F.data.scenes){if(!w.has(X.sceneId)||Q.has(X.sceneId))throw new q4("invalid-response");Q.add(X.sceneId),Z.push({description:{...X.description,trust:"untrusted-model-output"},sceneId:X.sceneId})}if(Q.size!==w.size)throw new q4("invalid-response");let J=new Map(Z.map((X)=>[X.sceneId,X]));return _.scenes.map((X)=>{let V=J.get(X.sceneId);if(V===void 0)throw new q4("invalid-response");return V})}function xE0(_){let $=_??qE0;if(!Number.isSafeInteger($)||$<1||$>300000)throw new q4("invalid-request");return $}function mE0(){globalThis.AI_SDK_LOG_WARNINGS=!1}function rI(_){if(_.aborted)throw new q4("aborted")}function lE0(_){return _?.aborted===!0}function v10(_){let $=_.loadAiSdk??bE0,F=yE0(_.fetch??globalThis.fetch),w=xE0(_.timeoutMs);return{describe:async(Q,Z)=>{let J=sy(Q),X=!1,V=!1,Y=new AbortController,j=()=>Y.abort(Z?.reason);if(Z?.addEventListener("abort",j,{once:!0}),lE0(Z))throw Z?.removeEventListener("abort",j),new q4("aborted");let H=setTimeout(()=>{V=!0,Y.abort()},w),K=new Promise((W,O)=>{let L=()=>O(X?new q4(V?"gateway-outcome-unknown":"aborted","ambiguous"):new q4(V?"gateway-unavailable":"aborted"));if(Y.signal.addEventListener("abort",L,{once:!0}),Y.signal.aborted)L()});try{let W=(async()=>{mE0();let O=await $();return rI(Y.signal),await _.credential.withApiKey(async(L)=>{rI(Y.signal);let G=O.createGateway({apiKey:L,baseURL:RE0,fetch:F}),D=O.Output.object({description:"One bounded, observable description for every supplied scene identifier.",name:"slopcamera_scene_descriptions",schema:kB});rI(Y.signal),X=!0;let z=await O.generateText({abortSignal:Y.signal,maxOutputTokens:4096,maxRetries:0,messages:[gE0(J)],model:G.languageModel(J.model),output:D,providerOptions:{gateway:{disallowPromptTraining:!0,tags:["slopcamera","scene-analysis","v1"],zeroDataRetention:!0}},system:cy,temperature:0});return{descriptions:vE0(J,z.output),resolvedModel:hE0(z.response),usage:{inputTokens:g10(z.usage,"inputTokens"),outputTokens:g10(z.usage,"outputTokens"),uploadedBytes:J.imageBytes,uploadedImages:J.imageCount}}})})();return await Promise.race([W,K])}catch(W){throw py(W,X)}finally{clearTimeout(H),Z?.removeEventListener("abort",j)}}}}import{constants as yZ}from"fs";import{createHash as x10,randomUUID as dE0}from"crypto";import{chmod as uE0,lstat as cE0,mkdir as m10,open as c10,rename as sE0,rm as pE0}from"fs/promises";import{basename as vV1,isAbsolute as oI,join as SZ,relative as s10,sep as p10}from"path";var nE0=536870912,rE0=1073741824,iI=32,oE0=262144,iE0={"artifact-invalid":"The generated Gateway media output is invalid.","artifact-unavailable":"The generated Gateway media output could not be saved.","output-too-large":"The generated Gateway media output exceeds its local size limit.","unsafe-output":"The Gateway media output directory is unsafe."};class b2 extends Error{code;constructor(_){super(iE0[_]);this.code=_,this.name="GatewayMediaArtifactError"}}function aE0(_){let $=Date.parse(_);if(!Number.isFinite($)||new Date($).toISOString()!==_)throw new b2("artifact-invalid");return _}function n10(_){if(_.length<3||_.length>128||!/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/iu.test(_))throw new b2("artifact-invalid");return _.toLocaleLowerCase("en-US")}function tE0(_){return{"audio/aac":".aac","audio/aiff":".aiff","audio/alaw":".alaw","audio/basic":".au","audio/flac":".flac","audio/l16":".pcm","audio/m4a":".m4a","audio/mp4":".m4a","audio/mpeg":".mp3","audio/mulaw":".mulaw","audio/ogg":".ogg","audio/opus":".opus","audio/pcm":".pcm","audio/wav":".wav","audio/webm":".weba","audio/x-wav":".wav","application/json":".json","application/x-subrip":".srt","image/avif":".avif","image/bmp":".bmp","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/tiff":".tiff","image/webp":".webp","text/plain":".txt","text/vtt":".vtt","video/mp4":".mp4","video/mpeg":".mpeg","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi"}[_]??".bin"}function r10(_){return[..._].map((F)=>{let w=F.codePointAt(0);return w!==void 0&&(w<=8||w===11||w===12||w>=14&&w<=31||w===127)?" ":F}).join("").slice(0,2000)}function eE0(_){if(!Number.isSafeInteger(_.bytes)||_.bytes<0||!/^[a-f0-9]{64}$/u.test(_.sha256)||_.role.length<1||_.role.length>128||_.source!=="inline"&&_.source!=="url"||_.source==="inline"&&_.bytes<1||_.source==="url"&&_.bytes!==0)throw new b2("artifact-invalid");return{bytes:_.bytes,mediaType:n10(_.mediaType),role:_.role,sha256:_.sha256,source:_.source}}function l10(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function _q0(_){let $=(X)=>{if(X===void 0)return;if(typeof X!=="string"||X.length<1||X.length>256)throw new b2("artifact-invalid");return r10(X)};if(!l10(_))throw new b2("artifact-invalid");let{attempts:F,providers:w}=_;if(!Array.isArray(F)||F.length>32||!Number.isSafeInteger(_.attemptCount)||_.attemptCount<F.length||_.attemptCount>1e6||typeof _.attemptsTruncated!=="boolean"||_.attemptsTruncated!==(_.attemptCount!==F.length)||_.clientMaxRetries!==0||_.gatewayProviderFailover!=="may-attempt-multiple-providers"||!Array.isArray(w)||w.length>32||!Number.isSafeInteger(_.providerCount)||_.providerCount<w.length||_.providerCount>1e6||typeof _.providersTruncated!=="boolean"||_.providersTruncated!==(_.providerCount!==w.length))throw new b2("artifact-invalid");let Q=w.map((X)=>{let V=$(X);if(V===void 0)throw new b2("artifact-invalid");return V}),Z=F.map((X)=>{if(!l10(X))throw new b2("artifact-invalid");let V=X.configuredTimeoutMs,Y=$(X.credentialType),j=$(X.error),H=$(X.model),K=$(X.provider),W=X.statusCode;if(V!==void 0&&(!Number.isSafeInteger(V)||V<0)||X.credentialType!==void 0&&Y===void 0||X.error!==void 0&&(j===void 0||!/^sha256:[a-f0-9]{64}$/u.test(j))||X.model!==void 0&&H===void 0||X.provider!==void 0&&K===void 0||X.providerTimeout!==void 0&&typeof X.providerTimeout!=="boolean"||W!==void 0&&(!Number.isSafeInteger(W)||W<0||W>999)||X.success!==void 0&&typeof X.success!=="boolean")throw new b2("artifact-invalid");return{...V===void 0?{}:{configuredTimeoutMs:V},...Y===void 0?{}:{credentialType:Y},...j===void 0?{}:{error:j},...H===void 0?{}:{model:H},...K===void 0?{}:{provider:K},...X.providerTimeout===void 0?{}:{providerTimeout:X.providerTimeout},...W===void 0?{}:{statusCode:W},...X.success===void 0?{}:{success:X.success}}}),J=$(_.generationId);if(_.generationId!==void 0&&J===void 0)throw new b2("artifact-invalid");return{attemptCount:_.attemptCount,attempts:Z,attemptsTruncated:_.attemptsTruncated,clientMaxRetries:0,gatewayProviderFailover:"may-attempt-multiple-providers",...J===void 0?{}:{generationId:J},providerCount:_.providerCount,providers:[...new Set(Q)],providersTruncated:_.providersTruncated}}async function d10(_){let $=await c10(_,yZ.O_RDONLY|(yZ.O_DIRECTORY??0)|(yZ.O_NOFOLLOW??0));try{await $.sync()}finally{await $.close()}}async function u10(_,$){let F=await c10(_,yZ.O_CREAT|yZ.O_EXCL|yZ.O_WRONLY|(yZ.O_NOFOLLOW??0),384);try{await F.writeFile($),await F.sync()}finally{await F.close()}}function o10(_){switch(_){case"image.generate":return"image";case"speech.generate":return"speech";case"transcription.create":return"transcript";case"video.generate":return"video"}}function $q0(_){return/^[A-Za-z0-9_./:@%+=,-]+$/u.test(_)?_:`'${_.replaceAll("'",`'"'"'`)}'`}var i10=new Set(["audio/alaw","audio/basic","audio/l16","audio/mulaw","audio/pcm"]);function Fq0(_){return/^(?:audio|image|video)\//u.test(_)&&!i10.has(_)}function wq0(_,$,F,w){let Q=_==="speech.generate"?"dialogue":_==="transcription.create"?void 0:"b-roll";return Q===void 0?[]:F.filter((Z)=>_!=="speech.generate"||!i10.has(Z.mediaType)).map((Z)=>`slopcamera project add <project> ${$q0(s10(w,SZ($,Z.file)).split(p10).join("/"))} --role ${Q}`)}function Qq0(_,$,F){return`${$.replace(/[-:.]/gu,"").replace("Z","Z")}-${o10(_)}-${F}`}function Zq0(_){if(!(_.uint8Array instanceof Uint8Array)||_.uint8Array.byteLength<1)throw new b2("artifact-invalid");if(_.uint8Array.byteLength>nE0)throw new b2("output-too-large");let $=n10(_.mediaType);if(/^(?:audio|image|video)\//u.test($)&&!$8(_.uint8Array,$))throw new b2("artifact-invalid");return{mediaType:$,uint8Array:_.uint8Array}}function Jq0(_){if(!Number.isSafeInteger(_.requested)||_.requested<1||_.requested>iI||!Number.isSafeInteger(_.produced)||_.produced<1||_.produced>iI)throw new b2("artifact-invalid");return{produced:_.produced,requested:_.requested,status:_.produced===_.requested?"complete":_.produced<_.requested?"partial":"overproduced"}}function a10(_){if(!oI(_.outputRoot)||!oI(_.repositoryRoot))throw new b2("unsafe-output");let $=s10(_.repositoryRoot,_.outputRoot);if($.length===0||$===".."||$.startsWith(`..${p10}`)||oI($))throw new b2("unsafe-output");let F=_.randomId??(()=>dE0().slice(0,12));return{commit:async(w)=>{if(w.signal.throwIfAborted(),w.files.length<1||w.files.length>iI)throw new b2("artifact-invalid");let Q=w.files.map(Zq0);if(Q.reduce((O,L)=>O+L.uint8Array.byteLength,0)>rE0)throw new b2("output-too-large");let J=aE0(w.createdAt),X=F();if(!/^[a-z0-9_-]{4,64}$/iu.test(X))throw new b2("artifact-invalid");let V=Qq0(w.operation,J,X),Y=SZ(_.outputRoot,V),j=SZ(_.outputRoot,`.${V}.tmp`),H=!1,K=[],W=[];try{await m10(_.outputRoot,{mode:448,recursive:!0});let O=await cE0(_.outputRoot);if(O.isSymbolicLink()||!O.isDirectory())throw new b2("unsafe-output");await uE0(_.outputRoot,448),w.signal.throwIfAborted(),await m10(j,{mode:448});for(let[C,A]of Q.entries()){w.signal.throwIfAborted();let B=`${o10(w.operation)}-${String(C+1).padStart(2,"0")}${tE0(A.mediaType)}`,T=SZ(j,B);await u10(T,A.uint8Array),W.push({mediaType:A.mediaType,path:T,uint8Array:A.uint8Array}),K.push({bytes:A.uint8Array.byteLength,file:B,mediaType:A.mediaType,sha256:x10("sha256").update(A.uint8Array).digest("hex")}),w.signal.throwIfAborted()}let L=W.filter((C)=>Fq0(C.mediaType)),G;if(L.length===0||_.validateMediaFile===void 0)G={decodeValidatedOutputs:0,signatureOnlyOutputs:W.length,status:"signature-only"};else try{for(let C of L)w.signal.throwIfAborted(),await _.validateMediaFile(C,w.signal),w.signal.throwIfAborted();G={decodeValidatedOutputs:L.length,signatureOnlyOutputs:W.length-L.length,status:"decode-passed"}}catch(C){w.signal.throwIfAborted();let A=C instanceof Error?`${C.name}\x00${C.message}`:typeof C==="string"?C:typeof C;G={decodeValidatedOutputs:0,failureSha256:x10("sha256").update(A,"utf8").digest("hex"),signatureOnlyOutputs:W.length-L.length,status:"decode-failed"}}w.signal.throwIfAborted();let D={catalog:w.catalog,createdAt:J,inputs:w.inputs.map(eE0),kind:"slopcamera.gateway-media-receipt",localValidation:G,model:w.model,nextCommands:G.status==="decode-passed"?wq0(w.operation,Y,K,_.repositoryRoot):[],operation:w.operation,outputs:K,request:w.request,routing:_q0(w.routing),...w.sampleFulfillment===void 0?{}:{sampleFulfillment:Jq0(w.sampleFulfillment)},schemaVersion:1,warnings:w.warnings.slice(0,100).map(r10)},z;try{z=`${k(D)}
4659
4659
  `}catch{throw new b2("artifact-invalid")}if(new TextEncoder().encode(z).byteLength>oE0)throw new b2("artifact-invalid");return await u10(SZ(j,"receipt.json"),z),await d10(j),w.signal.throwIfAborted(),await _.beforePublication?.(),w.signal.throwIfAborted(),await sE0(j,Y),H=!0,await d10(_.outputRoot),{directory:Y,outputs:K.map((C)=>({...C,path:SZ(Y,C.file)})),receipt:D,receiptPath:SZ(Y,"receipt.json")}}catch(O){if(!H)w.signal.throwIfAborted();if(O instanceof b2)throw O;throw new b2("artifact-unavailable")}finally{await pE0(j,{force:!0,recursive:!0}).catch(()=>{return})}}}}import{createHash as Xq0}from"crypto";import{isAbsolute as Vq0,relative as Yq0,resolve as aI}from"path";import{z as h8}from"zod";var jq0="studio.gateway-application-request/v1",Nq0="studio.gateway-application-failure/v1",Hq0="studio.gateway-application-conflict/v1",X20="request.json",V20=536870912,Y20=262144,j20=h8.strictObject({chargeMayHaveOccurred:h8.boolean(),createdAt:h8.string().datetime({offset:!0}),failureSha256:P.optional(),kind:h8.union([h8.literal("slopcamera.gateway-workflow-request"),h8.literal("studio.gateway-workflow-request")]),model:h8.string().min(3).max(256),operation:lw,requestId:F_,requestSha256:P,result:Oj.optional(),schemaVersion:h8.literal(1),sourceBindings:h8.array(Y2).max(65).optional(),state:h8.enum(["prepared","dispatched","completed"]),updatedAt:h8.string().datetime({offset:!0})}).superRefine((_,$)=>{if(_.state==="completed"!==(_.result!==void 0)||_.chargeMayHaveOccurred===(_.state==="prepared")||_.result!==void 0&&(_.result.operation!==_.operation||_.result.model!==_.model||_.result.requestId!==_.requestId))$.addIssue({code:"custom",message:"Gateway workflow journal state is inconsistent."})});function E5(_){if(_.aborted)throw new N("cancelled","Gateway operation was cancelled.")}function Wq0(_){return _ instanceof Error&&"code"in _&&_.code==="ENOENT"}function t10(_){return t(`${jq0}\x00${k(_)}`)}function DC(_){let $=_ instanceof Error?`${_.name}\x00${_.message}`:typeof _;return t(`${Nq0}\x00${$}`)}function e10(_){return t(`${Hq0}\x00${_}`)}function _20(_,$,F,w){return _.requestId===F&&_.requestSha256===w&&_.operation===$.operation&&_.model===$.request.model&&(_.sourceBindings===void 0||k(_.sourceBindings)===k(N20($)))}async function $20(_,$){await J1(_.paths.privateRoot);let F=await I0(_.paths.privateRoot,"gateway-workflow-requests");return await I0(F,$)}async function F20(_){let $=L0(_),F;try{F=await $.readText(X20)}catch(w){if(Wq0(w))return null;throw w}try{return j20.parse(JSON.parse(F))}catch{throw new N("conflict","The durable Gateway request journal is invalid.")}}async function zC(_,$){let F=j20.parse($);return await L0(_).writeTextAtomic(X20,`${k(F)}
@@ -5030,7 +5030,7 @@ export default defineWorkflow({
5030
5030
  `)}async function YA(_,$){let F=n0(HA(_),`.replace-${NA()}`);await Nw(F,$);try{await If0(F,_),await G$(HA(_))}catch(w){throw await sZ(F).catch(()=>{return}),w}}async function OA(_,$=B50){if(!Number.isSafeInteger($)||$<0||$>B50)throw new N("invalid-data","Run artifact byte bound is invalid.");let F;try{F=await r4(_)}catch(Q){if(v8(Q,"ENOENT"))throw new N("not-found",`Run artifact does not exist: ${_}`);throw Q}if(!jS(F)||!Number.isSafeInteger(F.size)||F.size<0||F.size>$)throw new N("unsafe-path",`Run artifact must be a bounded private physical file: ${_}`);let w=await GA(_,x8.O_NOFOLLOW|x8.O_RDONLY|x8.O_NONBLOCK);try{let Q=Ww(F),Z,J,X=Buffer.alloc(F.size+1);for(let V of[1,2]){let Y=Ww(await w.stat());if(!CY(Q,Y)||Z!==void 0&&!pZ(Z,Y))throw new N("conflict",`Run artifact changed before read: ${_}`);let j=0;while(j<X.byteLength){let{bytesRead:L}=await w.read(X,j,X.byteLength-j,j);if(L===0)break;j+=L}let H=Ww(await w.stat()),K=Ww(await r4(_)),W=_W("sha256").update(X.subarray(0,j)).digest("hex");if(!CY(Y,H)||!CY(H,K)||j!==Y.size||J!==void 0&&J!==W)throw new N("conflict",`Run artifact changed during read: ${_}`);if(pZ(Y,H)&&pZ(H,K)&&(V===2||pZ(Q,Y)))return X.subarray(0,j);if(V===2)throw new N("conflict",`Run artifact changed during read: ${_}`);Z=K,J=W}throw new N("conflict",`Run artifact changed during read: ${_}`)}finally{await w.close()}}function h50(_,$){try{return new TextDecoder("utf-8",{fatal:!0}).decode(_)}catch(F){throw new N("invalid-data",`Run artifact is not UTF-8 (${$}): ${String(F)}`)}}async function _S0(_,$){let F=await OA(_);return $?.set(_,_W("sha256").update(F).digest("hex")),h50(F,_)}async function v50(_,$){try{return JSON.parse(await _S0(_,$))}catch(F){if(F instanceof N)throw F;throw new N("invalid-data",`Run artifact is not JSON: ${_}`)}}async function M4(_,$,F){try{return $.parse(await v50(_,F))}catch(w){if(w instanceof N)throw w;throw new N("invalid-data",`Run artifact failed validation (${_}): ${String(w)}`)}}function x50(_){let $=_.lastIndexOf(10);return $<0?_.subarray(0,0):_.subarray(0,$+1)}function m50(_,$,F){let w=x50(_);if(w.byteLength===0)return Object.freeze([]);let Q=h50(w,$).split(`
5031
5031
  `);if(Q.pop(),Q.length>WA)throw new N("invalid-data",`Run journal exceeds ${String(WA)} entries: ${$}`);return Object.freeze(Q.map((Z,J)=>{try{return F.parse(JSON.parse(Z))}catch(X){throw new N("invalid-data",`Invalid run journal entry ${String(J+1)} (${$}): ${String(X)}`)}}))}async function XS(_,$){return m50(await OA(_,jA),_,$)}async function f50(_,$,F,w,Q,Z){let J=await r4(_);if(!jS(J)||J.size>jA)throw new N("unsafe-path",`Run journal must be a bounded private physical file: ${_}`);let X=await GA(_,x8.O_NOFOLLOW|x8.O_RDWR);try{let V=await X.stat();if(!Hw(z_(J),z_(V)))throw new N("conflict",`Run journal changed before append: ${_}`);let Y=Z!==void 0&&pZ(Z.snapshot,Ww(J))&&pZ(Z.snapshot,Ww(V)),j,H,K;if(Y)j=V.size,H=Z.cursor,K=Z.entryCount;else{let z=new Uint8Array(await X.readFile());if(z.byteLength>jA)throw new N("invalid-data",`Run journal exceeds its byte limit: ${_}`);let C=x50(z),A=m50(z,_,$);if(H=F(A),K=A.length,j=C.byteLength,z.byteLength!==j)await X.truncate(j),await X.sync()}if(K>=WA)throw new N("conflict",`Run journal already contains ${String(WA)} entries.`);let W=w({cursor:H,entryCount:K}),O=$.parse(W.entry),L=new TextEncoder().encode(`${k(O)}
5032
5032
  `);if(L.byteLength>yf0)throw new N("invalid-data","Run journal entry exceeds its byte limit.");if(j+L.byteLength>jA)throw new N("conflict","Run journal has reached its byte limit.");let G=0;while(G<L.byteLength){let z=await X.write(L,G,L.byteLength-G,j+G);if(z.bytesWritten<1)throw new N("unavailable",`Run journal append made no progress: ${_}`);G+=z.bytesWritten}await X.sync();let D=await X.stat();if(!nf0(z_(V),z_(D))||D.size!==j+L.byteLength)throw new N("conflict",`Run journal changed during append: ${_}`);return{result:W.result,state:{cursor:Q(H,O),entryCount:K+1,snapshot:Ww(D)}}}finally{await X.close()}}function S50(_,$){let F=0;for(let[w,Q]of _.entries()){if(Q.runId!==$||Q.sequence!==w+1)throw new N("invalid-data",`Run event sequence is inconsistent for ${$}.`);if(Q.fenceGeneration<F)throw new N("invalid-data",`Run event fence generation regressed for ${$}.`);F=Q.fenceGeneration}return{lastFenceGeneration:F,lastSequence:_.at(-1)?.sequence??0}}function VS(_,$,F){let w=new Set;for(let Q of _){if(Q.runId!==$||Q.graphPlanSha256!==F)throw new N("invalid-data",`Run grant identity is inconsistent for ${$}.`);if(w.has(Q.grantId))throw new N("invalid-data",`Run grant ID is duplicated: ${Q.grantId}`);w.add(Q.grantId)}return{grantIds:w}}function YS(_){return{cancelled:_.filter(($)=>$.status==="cancelled").length,completed:_.filter(($)=>$.status==="completed").length,failed:_.filter(($)=>$.status==="failed"||$.status==="incompatible"||$.status==="ambiguous").length,pending:_.filter(($)=>$.status==="pending"||$.status==="ready"||$.status==="preparing"||$.status==="running"||$.status==="approval-required"||$.status==="ambiguous-code").length,skipped:_.filter(($)=>$.status==="skipped").length}}function $S0(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)&&Object.hasOwn(_,"$ref")}function FS0(_){return Array.isArray(_)}function LA(_,$,F){if($S0(_)){let Q=$.get(_.$ref.nodeKey);if(Q?.status!=="completed"||Q.output===void 0)return;return F[Q.nodeKey]=Q.output.digestSha256,tH(_,Q.output.value)}if(FS0(_)){let Q=[];for(let Z of _){let J=LA(Z,$,F);if(J===void 0)return;Q.push(J)}return Q}let w={};for(let[Q,Z]of Object.entries(_).sort(([J],[X])=>J.localeCompare(X))){let J=LA(Z,$,F);if(J===void 0)return;w[Q]=J}return w}function y50(_){if(_.some((F)=>F.status==="approval-required"))return"approval-required";if(_.some((F)=>F.status==="ambiguous-code"))return"ambiguous-code";if(_.some((F)=>F.status==="pending"||F.status==="ready"||F.status==="preparing"||F.status==="running"))return"running";let $=YS(_);if($.cancelled>0)return"cancelled";if($.failed===0&&$.skipped===0&&$.completed===_.length)return"completed";if(_.some((F)=>F.status==="incompatible")&&$.completed===0)return"incompatible";if($.completed>0)return"partial";return"failed"}class NS{#_=new Map;#$=0;#Q;#J;constructor(_){let $=_.claimSessionCacheBudgetBytes??QS;if(!Number.isSafeInteger($)||$<0||$>QS)throw new N("usage",`Run claim-session cache budget must be a safe integer from 0 through ${String(QS)}.`);this.#Q=$,this.#J=Sf0(_.root)}async#F(){let _=this.#J,$=ff0(_),F=_.slice($.root.length).split("/").filter(Boolean),w=$.root;for(let Z of F){w=n0(w,Z);let J;try{J=await r4(w)}catch(X){if(!v8(X,"ENOENT"))throw X;try{await eH(w,{mode:448})}catch(V){if(!v8(V,"EEXIST"))throw V}J=await r4(w)}if(J.isSymbolicLink()||!J.isDirectory())throw new N("unsafe-path",`Run root crosses a non-physical directory component: ${w}`)}let Q=await r4(_);if(!XA(Q))throw new N("unsafe-path",`Run root must be an owner-only physical directory (0700): ${_}`);if(await _S(_)!==_)throw new N("unsafe-path",`Run root crosses a symbolic link: ${_}`);return _}async#X(_,$=!0){let F=m_.shape.runId.parse(_),w=await this.#F(),Q=n0(w,F);if($){let Z=await r4(Q).catch((J)=>{if(v8(J,"ENOENT"))throw new N("not-found",`Workflow run does not exist: ${F}`);throw J});if(!XA(Z)||await _S(Q)!==Q)throw new N("unsafe-path",`Workflow run must be an owner-only physical directory (0700): ${F}`)}return Q}async#Y(_){return await this.#V(_,"nodes")}async#V(_,$){let F=n0(_,$),w=await r4(F);if(!XA(w)||await _S(F)!==F)throw new N("unsafe-path",`Run ${$} storage must be a physical 0700 directory.`);return F}async#w(_,$){let F=n0(_,$);try{await eH(F,{mode:448})}catch(w){if(!v8(w,"EEXIST"))throw w}return await this.#V(_,$)}async#j(_,$){let F=await this.#X(_),w=n0(F,uf0),Q=ZS.parse({acquiredAt:new Date().toISOString(),hostname:ZA(),pid:process.pid,token:NA(),version:x_}),Z=Date.now()+gf0,J;while(J===void 0)try{await VA(w,Q),J=z_(await r4(w))}catch(X){if(!v8(X,"EEXIST"))throw X;let V,Y;try{Y=await r4(w),V=await M4(w,ZS)}catch(j){let H=await r4(w).catch(()=>{return});if(Y===void 0||H===void 0||!Hw(z_(Y),z_(H))){if(Date.now()>=Z)throw new N("conflict",`Timed out waiting for run serialization: ${_}`);await $S(wS);continue}if(v8(j,"ENOENT")||j instanceof N&&(j.code==="not-found"||j.code==="conflict")){if(Date.now()>=Z)throw new N("conflict",`Timed out waiting for run serialization: ${_}`);await $S(wS);continue}throw new N("unsafe-path",`Run serialization lock is malformed: ${String(j)}`)}if(V.hostname===ZA()&&!q50(V.pid)){let j=await r4(w).catch(()=>{return});if(j!==void 0&&Hw(z_(Y),z_(j))){await sZ(w),await G$(F);continue}}if(Date.now()>=Z)throw new N("conflict",`Timed out waiting for run serialization: ${_}`);await $S(wS)}try{return await $(F)}finally{let X=await r4(w).catch(()=>{return});if(X!==void 0&&Hw(J,z_(X))){if((await M4(w,ZS).catch(()=>{return}))?.token===Q.token)await sZ(w).catch(()=>{return}),await G$(F).catch(()=>{return})}}}async#W(_,$,F){await this.#V(_,"staging");let w;try{w=Lf(await v50(n0(_,"graph-plan.json"),F))}catch(j){if(j instanceof N)throw j;throw new N("invalid-data",`Persisted graph plan is invalid: ${String(j)}`)}let Q=await M4(n0(_,JA),E50,F);if(Q.runId!==$||Q.graphPlanSha256!==w.graphPlanSha256)throw new N("invalid-data","Run initialization identity is inconsistent.");let Z=await M4(n0(_,"graph.json"),D$,F);if(!W2(Z,w.graph))throw new N("invalid-data","Persisted authored graph differs from its graph plan.");let J=await M4(n0(_,"workflow.json"),af,F);if(!W2(J.bundle,w.bundle)||!W2(J.workflow,w.graph.workflow))throw new N("invalid-data","Persisted workflow identity differs from its graph plan.");let X=await M4(n0(_,"runtime.json"),iC,F);if(!W2(X.runtime,w.runtime)||!W2(X.computes,P50(w))||!W2(X.operations,b50(w)))throw new N("invalid-data","Persisted runtime identity differs from its graph plan.");let V=await OA(n0(_,"workflow.bundle.js"),FS),Y=_W("sha256").update(V).digest("hex");if(F?.set(n0(_,"workflow.bundle.js"),Y),V.byteLength!==w.bundle.bytes||Y!==w.bundle.bundleSha256)throw new N("invalid-data","Persisted workflow bundle bytes changed.");return{bundleBytes:V,directory:_,graphPlan:w,runtime:X,workflow:J}}#U(_){return[n0(_,"graph-plan.json"),n0(_,JA),n0(_,"graph.json"),n0(_,"workflow.json"),n0(_,"runtime.json"),n0(_,"workflow.bundle.js")]}async#Z(_){let $=await Promise.all(this.#U(_).map(async(F)=>{let w=await r4(F);if(!jS(w))throw new N("unsafe-path",`Run identity must be stored in a private physical file: ${F}`);return[F,Ww(w)]}));return new Map($)}#H(_,$){if(_.size!==$.size)return!1;for(let[F,w]of _){let Q=$.get(F);if(Q===void 0||!pZ(w,Q))return!1}return!0}async#L(_){let $=new Map;for(let[F,w]of _){let Q=await OA(F,w.size);$.set(F,_W("sha256").update(Q).digest("hex"))}return $}async#G(_,$){let F=await this.#Z(_),w=new Map,Q=await this.#W(_,$,w),Z=await this.#Z(_);if(!this.#H(F,Z)){for(let[Y,j]of F){let H=Z.get(Y);if(H===void 0||!CY(j,H))throw new N("conflict",`Run identity changed while it was validated: ${$}`)}let X=await this.#L(Z),V=await this.#Z(_);if(!this.#H(Z,V)||[...w].some(([Y,j])=>X.get(Y)!==j))throw new N("conflict",`Run identity changed while it was validated: ${$}`);Z=V}let J={directory:Q.directory,graphPlan:Q.graphPlan,runtime:Q.runtime,workflow:Q.workflow};return{identity:J,retainedBytes:of0(J,Z),sha256ByPath:w,snapshots:Z}}#N(_){let $=this.#_.get(_.runId);if($===void 0||$.fenceGeneration!==_.generation||$.fenceToken!==_.token)return;return this.#_.delete(_.runId),this.#_.set(_.runId,$),$}#z(_){let $=this.#_.get(_);if($===void 0)return;this.#_.delete(_),this.#$=Math.max(0,this.#$-$.retainedBytes)}#K(_,$){let F=this.#N(_),w={...F?.eventJournal===void 0?{}:{eventJournal:F.eventJournal},...F?.grantJournal===void 0?{}:{grantJournal:F.grantJournal},...F?.identity===void 0?{}:{identity:F.identity},...$,fenceGeneration:_.generation,fenceToken:_.token},Q=if0(_.runId,w);if(this.#z(_.runId),Q>vf0||Q>this.#Q)return;this.#_.set(_.runId,{...w,retainedBytes:Q}),this.#$=Kw(this.#$,Q);while(this.#_.size>hf0||this.#$>this.#Q){let Z=this.#_.keys().next().value;if(Z===void 0)break;this.#z(Z)}}#k(_){let $=this.#_.get(_.runId);if($?.fenceGeneration===_.generation&&$.fenceToken===_.token)this.#z(_.runId)}async#M(_,$){let F=this.#N($)?.identity;if(F!==void 0)try{let Q=await this.#Z(_);if(this.#H(F.snapshots,Q))return F.identity;for(let[X,V]of F.snapshots){let Y=Q.get(X);if(Y===void 0||!CY(V,Y))throw new N("conflict",`Run identity metadata changed: ${X}`)}let Z=await this.#L(Q),J=await this.#Z(_);if(!this.#H(Q,J))throw new N("conflict","Run identity changed during revalidation.");for(let[X,V]of F.sha256ByPath)if(Z.get(X)!==V)throw new N("conflict",`Run identity bytes changed: ${X}`);return this.#K($,{identity:{...F,snapshots:J}}),F.identity}catch(Q){throw this.#k($),new N("conflict",`Run identity changed while its claim was active: ${$.runId} (${String(Q)})`)}let w=await this.#G(_,$.runId);return this.#K($,{identity:w}),w.identity}async#D(_){let $=await this.#X(_);return await this.#W($,_)}async create(_){let $=C50.parse(_),F=Lf($.graphPlan);if($.bundleBytes.byteLength>FS)throw new N("invalid-data",`Workflow bundle exceeds ${String(FS)} bytes.`);let w=_W("sha256").update($.bundleBytes).digest("hex");if($.bundleBytes.byteLength!==F.bundle.bytes||w!==F.bundle.bundleSha256||!W2($.workflow.bundle,F.bundle))throw new N("invalid-data","Workflow bundle identity or bytes do not match.");if(!W2($.workflow.workflow,F.graph.workflow)||$.workflow.sourceLocator!==$.sourceLocator)throw new N("invalid-data","Workflow source identity does not match the graph plan.");if(!W2($.runtime.runtime,F.runtime)||!W2($.runtime.computes,P50(F))||!W2($.runtime.operations,b50(F)))throw new N("invalid-data","Workflow runtime or operation identities do not match.");let Q=await this.#X($.runId,!1),Z=HA(Q);try{await eH(Q,{mode:448})}catch(Y){if(v8(Y,"EEXIST"))throw new N("conflict",`Workflow run already exists: ${$.runId}`);throw Y}if(await G$(Z),!XA(await r4(Q)))throw new N("unsafe-path","New workflow run directory is not private.");await eH(n0(Q,"nodes"),{mode:448}),await eH(n0(Q,"staging"),{mode:448}),await Nw(n0(Q,"runtime.json"),$.runtime),await Nw(n0(Q,"workflow.json"),$.workflow),await FW(n0(Q,"workflow.bundle.js"),$.bundleBytes),await Nw(n0(Q,"graph.json"),F.graph),await Nw(n0(Q,"graph-plan.json"),F),await FW(n0(Q,"events.jsonl"),""),await FW(n0(Q,"grants.jsonl"),"");let J=await this.#Y(Q);for(let Y of F.graph.nodes){let j=l_.parse({attempt:0,dependencies:Y.dependencies,executor:Y.executor,nodeKey:Y.key,status:Y.dependencies.length===0?"ready":"pending",version:Vw});await Nw(n0(J,Yw(Y.key)),j)}let X=new Date().toISOString(),V=L3.parse({counts:{cancelled:0,completed:0,failed:0,pending:F.graph.nodes.length,skipped:0},graphPlanSha256:F.graphPlanSha256,runId:$.runId,status:"planned",updatedAt:X,version:x_});return await Nw(n0(Q,"summary.json"),V),await Nw(n0(Q,JA),{graphPlanSha256:F.graphPlanSha256,runId:$.runId,version:x_}),await G$(J),await G$(n0(Q,"staging")),await G$(Q),V}async list(){let _=await this.#F(),$=await Pf0(_,{withFileTypes:!0}),F=[];for(let w of $.sort((Q,Z)=>Q.name.localeCompare(Z.name))){if(!w.isDirectory()||!w.name.startsWith("run_"))continue;try{let Q=await this.#X(w.name),Z=await M4(n0(Q,JA),E50),J=await M4(n0(Q,"summary.json"),L3);if(Z.runId!==J.runId||Z.graphPlanSha256!==J.graphPlanSha256)continue;F.push(J)}catch{}}return Object.freeze(F.sort((w,Q)=>Q.updatedAt.localeCompare(w.updatedAt)))}async graphPlan(_){return(await this.#D(_)).graphPlan}async graph(_){return(await this.#D(_)).graphPlan.graph}async workflow(_){return(await this.#D(_)).workflow}async runtime(_){return(await this.#D(_)).runtime}async bundle(_){return new Uint8Array((await this.#D(_)).bundleBytes)}async stagingDirectory(_,$,F){let w=m_.parse(_),Q=k2.parse($),Z=k1.parse(F);return await this.#j(w.runId,async(J)=>{await this.#T(J,w);let X=await this.#M(J,w),V=await M4(n0(await this.#Y(J),Yw(Q)),l_);if(V.nodeKey!==Q||V.executionPlan?.nodePlanSha256!==Z)throw new N("conflict",`Node staging identity does not match its exact execution plan: ${Q}`);let Y=await this.#V(X.directory,"staging"),j=Yw(Q).slice(0,-5),H=await this.#w(Y,j),K=await this.#w(H,Z);return await G$(H),await G$(Y),K})}async summary(_){let $=await this.#D(_),F=await M4(n0($.directory,"summary.json"),L3);if(F.runId!==_||F.graphPlanSha256!==$.graphPlan.graphPlanSha256)throw new N("invalid-data","Run summary identity is inconsistent.");if(F.outputs!==void 0){let w=await this.outputs(_);if(w===void 0||!W2(w.outputs,F.outputs))throw new N("invalid-data","Run summary output identity is inconsistent.")}if(JS.has(F.status)){let w=await this.#A($);if(!W2(F.counts,YS(w))||F.status!==y50(w)||F.finishedAt===void 0)throw new N("invalid-data","Terminal run summary is inconsistent with node state.")}return F}async#A(_){let $=await this.#Y(_.directory),F=await Promise.all(_.graphPlan.graph.nodes.map(async(Q)=>await M4(n0($,Yw(Q.key)),l_))),w=new Map(F.map((Q)=>[Q.nodeKey,Q]));if(w.size!==_.graphPlan.graph.nodes.length)throw new N("invalid-data","Run node identities are duplicated or missing.");for(let Q of _.graphPlan.graph.nodes){let Z=w.get(Q.key);if(Z===void 0)throw new N("invalid-data",`Run is missing authored node ${Q.key}.`);this.#C(_.graphPlan,Q,Z,w)}return Object.freeze(F)}async#R(_,$){let F=_.graphPlan.graph.nodes.find((H)=>H.key===$);if(F===void 0)throw new N("not-found",`Workflow run node does not exist: ${$}`);let w=await this.#Y(_.directory),Q=new Map(_.graphPlan.graph.nodes.map((H)=>[H.key,H])),Z=new Set,J=[F.key];while(J.length>0){let H=J.pop();if(H===void 0||Z.has(H))continue;let K=Q.get(H);if(K===void 0)throw new N("invalid-data",`Run graph is missing dependency ${H}.`);Z.add(H),J.push(...K.dependencies)}let X=[...Z],V=await Promise.all(X.map(async(H)=>await M4(n0(w,Yw(H)),l_))),Y=new Map(V.map((H)=>[H.nodeKey,H]));if(Y.size!==X.length)throw new N("invalid-data",`Run node context contains duplicated or missing identities: ${$}`);for(let H of X){let K=Y.get(H),W=Q.get(H);if(K===void 0||W===void 0)throw new N("invalid-data",`Run is missing authored node ${H}.`);this.#C(_.graphPlan,W,K,Y)}let j=Y.get(F.key);if(j===void 0)throw new N("invalid-data",`Run is missing authored node ${F.key}.`);return{authored:F,record:j,recordsByKey:Y}}#C(_,$,F,w){if(F.nodeKey!==$.key||!W2(F.dependencies,$.dependencies)||!W2(F.executor,$.executor))throw new N("invalid-data",`Persisted node identity changed: ${$.key}`);let Q=I50(_,$);if(F.executionPlan!==void 0&&F.preparationPlan===void 0)throw new N("invalid-data",`Execution plan has no preparation plan for node ${$.key}.`);if(F.preparationPlan!==void 0){let{preparationPlanSha256:Z,...J}=F.preparationPlan;if(F.preparationPlan.version!==pH||Z!==rH(J)||F.preparationPlan.graphPlanSha256!==_.graphPlanSha256||F.preparationPlan.nodeKey!==$.key||!W2(F.preparationPlan.executor,$.executor)||!W2(F.preparationPlan.requestedPreparation,[...Q.preparation].sort((X,V)=>X.localeCompare(V)))||F.preparationPlan.upperDurationMs>Q.maxDurationMs||F.preparationPlan.upperInputBytes>Q.maxInputBytes)throw new N("invalid-data",`Preparation plan digest or identity is invalid for node ${$.key}.`)}if(F.executionPlan!==void 0){let{nodePlanSha256:Z,...J}=F.executionPlan,X=Object.fromEntries([...$.dependencies].sort((Y,j)=>Y.localeCompare(j)).map((Y)=>{let j=w.get(Y);if(j?.status!=="completed"||j.output===void 0)throw new N("invalid-data",`Execution plan for ${$.key} references incomplete dependency ${Y}.`);return[Y,j.output.digestSha256]})),V=[...F.executionPlan.publicationKeys].sort((Y,j)=>Y.localeCompare(j));if(F.executionPlan.version!==nH||Z!==oH(J)||F.executionPlan.inputSha256!==D50(F.executionPlan.exactInput)||F.executionPlan.graphPlanSha256!==_.graphPlanSha256||F.executionPlan.nodeKey!==$.key||F.executionPlan.preparationPlanSha256!==F.preparationPlan?.preparationPlanSha256||!W2(F.executionPlan.executor,$.executor)||!W2(F.executionPlan.policy,af0(Q))||!W2(F.executionPlan.dependencyOutputDigests,X)||!W2(F.executionPlan.publicationKeys,V)||new Set(V).size!==V.length)throw new N("invalid-data",`Execution plan digest or identity is invalid for node ${$.key}.`)}if(F.output!==void 0&&F.output.digestSha256!==z50(F.output.value))throw new N("invalid-data",`Output digest is invalid for node ${$.key}.`)}async node(_,$){let F=k2.parse($),w=await this.#D(_);return(await this.#R(w,F)).record}async nodes(_){let $=await this.#D(_);return await this.#A($)}async events(_){let $=await this.#X(_),F=await XS(n0($,"events.jsonl"),wA);return S50(F,_),F}async grants(_){let $=await this.#D(_),F=await XS(n0($.directory,"grants.jsonl"),iH);return VS(F,_,$.graphPlan.graphPlanSha256),F}async outputs(_){let $=await this.#D(_),F=n0($.directory,"outputs.json"),w=await M4(F,QA).catch((V)=>{if(V instanceof N&&V.code==="not-found")return;throw V});if(w===void 0)return;if(w.runId!==_||w.graphPlanSha256!==$.graphPlan.graphPlanSha256||w.outputsSha256!==ef(w.outputs))throw new N("invalid-data","Persisted run outputs have an invalid identity.");let Q=await this.#A($),Z=new Map(Q.map((V)=>[V.nodeKey,V])),J={},X=LA($.graphPlan.graph.outputs,Z,J);if(X===void 0||!W2(w.outputs,X)||!W2(w.nodeOutputDigests,J))throw new N("invalid-data","Persisted run outputs differ from completed nodes.");return w}async#E(_){let $=n0(_,jw),F;try{F=await r4($)}catch(Q){if(v8(Q,"ENOENT"))return;throw Q}return{fence:await M4($,m_),snapshot:z_(F)}}async#T(_,$){let F=m_.parse($),w=await this.#E(_);if(w===void 0||w.fence.generation!==F.generation||w.fence.token!==F.token||w.fence.owner!==F.owner||w.fence.runId!==F.runId)throw this.#k(F),new N("conflict",`Workflow run fence is stale: ${F.runId}`);return F}async#b(_,$,F){let w=this.#N($)?.eventJournal,Q=await f50(n0(_,"events.jsonl"),wA,(Z)=>S50(Z,$.runId),({cursor:Z})=>{if($.generation<Z.lastFenceGeneration)throw new N("invalid-data",`Run event fence generation regressed for ${$.runId}.`);let J=wA.parse({...F,fenceGeneration:$.generation,runId:$.runId,sequence:Z.lastSequence+1,version:sf});return{entry:J,result:J}},(Z,J)=>({lastFenceGeneration:J.fenceGeneration,lastSequence:J.sequence}),w);return this.#K($,{eventJournal:Q.state}),Q.result}async acquireClaim(_,$){return await this.#j(_,async(F)=>{let w=await this.#G(F,_),Q=($.now??(()=>new Date))(),Z=$.staleAfterMs??30000;if(!Number.isSafeInteger(Z)||Z<0)throw new N("usage","Run claim stale interval must be a nonnegative safe integer.");let J=await this.#E(F),X=J?.fence.generation??0;if(J!==void 0){let H=Q.getTime()-Date.parse(J.fence.acquiredAt),K=J.fence.hostname!==ZA()||($.processAlive??q50)(J.fence.pid);if(H<Z||K)throw new N("conflict",`Workflow run is already claimed: ${_}`,{acquiredAt:J.fence.acquiredAt,owner:J.fence.owner,pid:J.fence.pid});let W=await r4(n0(F,jw)).catch(()=>{return});if(W===void 0||!Hw(J.snapshot,z_(W)))throw new N("conflict",`Workflow run claim changed during reclaim: ${_}`);await sZ(n0(F,jw)),await G$(F)}this.#z(_);let V=await M4(n0(F,R50),cf0).catch((H)=>{if(H instanceof N&&H.code==="not-found")return;throw H});X=Math.max(X,V?.generation??0);let Y=X+1,j=m_.parse({acquiredAt:Q.toISOString(),generation:Y,hostname:ZA(),owner:$.owner,pid:process.pid,runId:_,token:NA(),version:nf});await YA(n0(F,R50),{generation:Y,version:x_});try{return await VA(n0(F,jw),j),await this.#b(F,j,{details:{owner:j.owner},kind:"run-claimed",timestamp:j.acquiredAt}),this.#K(j,{identity:w}),j}catch(H){this.#k(j);let K=await this.#E(F).catch(()=>{return});if(K?.fence.token===j.token&&K.fence.generation===j.generation){let W=await r4(n0(F,jw)).catch(()=>{return});if(W!==void 0&&Hw(K.snapshot,z_(W)))await sZ(n0(F,jw)).catch(()=>{return}),await G$(F).catch(()=>{return})}throw H}})}async assertFence(_){let $=m_.parse(_);await this.#T(await this.#X($.runId),$)}async releaseClaim(_){let $=m_.parse(_);await this.#j($.runId,async(F)=>{await this.#T(F,$);let w=await this.#E(F);if(w===void 0)throw new N("conflict",`Workflow run fence is stale: ${$.runId}`);let Q=await r4(n0(F,jw));if(!Hw(w.snapshot,z_(Q)))throw new N("conflict",`Workflow run claim changed during release: ${$.runId}`);await sZ(n0(F,jw)),await G$(F),this.#k($)})}async appendEvent(_,$){let F=m_.parse(_);return await this.#j(F.runId,async(w)=>{if(await this.#T(w,F),$.nodeKey!==void 0){if(!(await this.#M(w,F)).graphPlan.graph.nodes.some((Z)=>Z.key===$.nodeKey))throw new N("invalid-data",`Run event names an unknown node: ${$.nodeKey}`)}return await this.#b(w,F,$)})}#B(_,$,F,w,Q){if(sf0.has(F.status)){if(!W2(F,w))throw new N("conflict",`Terminal run node ${F.nodeKey} is immutable.`);return}if(!pf0[F.status].has(w.status))throw new N("invalid-data",`Illegal run node transition ${F.status} -> ${w.status} for ${F.nodeKey}.`);let Z=F.status==="ready"&&w.status==="running"?F.attempt+1:F.attempt;if(w.attempt!==Z)throw new N("invalid-data",`Run node attempt changed outside ready -> running for ${F.nodeKey}.`);if(F.preparationPlan!==void 0&&!W2(F.preparationPlan,w.preparationPlan))throw new N("conflict",`Preparation plan changed for ${F.nodeKey}.`);if(F.executionPlan!==void 0&&!W2(F.executionPlan,w.executionPlan))throw new N("conflict",`Execution plan changed for ${F.nodeKey}.`);if(!(F.status==="ready"&&w.status==="running")&&F.startedAt!==w.startedAt)throw new N("invalid-data",`Run node startedAt changed illegally: ${F.nodeKey}`);if(F.status==="ready"&&w.status==="running"&&F.startedAt!==void 0&&Date.parse(w.startedAt)<Date.parse(F.startedAt))throw new N("invalid-data",`Run node startedAt regressed: ${F.nodeKey}`);if(F.status==="pending"&&w.status==="ready"&&$.dependencies.some((J)=>Q.get(J)?.status!=="completed"))throw new N("invalid-data",`Run node ${F.nodeKey} became ready before all dependencies completed.`);if(F.status==="running"&&w.status==="ready"){let J=I50(_,$).resume;if(J!=="deterministic"&&J!=="verified-receipt"&&J!=="recoverable-transaction")throw new N("conflict",`Interrupted node ${F.nodeKey} cannot be retried under ${J}.`)}}async writeNode(_,$){let F=m_.parse(_);await this.#j(F.runId,async(w)=>{await this.#T(w,F);let Q=l_.parse($),Z=await this.#M(w,F),J=await this.#R(Z,Q.nodeKey),X=new Map(J.recordsByKey);X.set(Q.nodeKey,Q),this.#B(Z.graphPlan,J.authored,J.record,Q,X),this.#C(Z.graphPlan,J.authored,Q,X);let V=await this.#Y(w);await YA(n0(V,Yw(Q.nodeKey)),Q)})}async writeSummary(_,$){let F=m_.parse(_);await this.#j(F.runId,async(w)=>{await this.#T(w,F);let Q=L3.parse($),Z=await this.#M(w,F);if(Q.runId!==F.runId||Q.graphPlanSha256!==Z.graphPlan.graphPlanSha256)throw new N("invalid-data","Run summary identity is inconsistent.");let J=await M4(n0(w,"summary.json"),L3);if(JS.has(J.status)){if(!W2(J,Q))throw new N("conflict","Terminal run summary is immutable.");return}if(Date.parse(Q.updatedAt)<Date.parse(J.updatedAt))throw new N("invalid-data","Run summary updatedAt regressed.");if(J.startedAt!==void 0&&Q.startedAt!==J.startedAt)throw new N("invalid-data","Run summary startedAt changed.");if(Q.status!=="planned"&&Q.startedAt===void 0)throw new N("invalid-data","Started run summaries require startedAt.");if(JS.has(Q.status)!==(Q.finishedAt!==void 0))throw new N("invalid-data","Only terminal run summaries require finishedAt.");let V=await this.#A(Z);if(!W2(Q.counts,YS(V)))throw new N("invalid-data","Run summary counts do not match node state.");let Y=y50(V);if(Q.status!==Y)throw new N("invalid-data",`Run summary status ${Q.status} does not match ${Y}.`);if(Q.status==="completed"){let j={},H=new Map(V.map((O)=>[O.nodeKey,O])),K=LA(Z.graphPlan.graph.outputs,H,j);if(K===void 0||Q.outputs===void 0||!W2(Q.outputs,K))throw new N("invalid-data","Completed run outputs do not match the authored output bindings.");let W=QA.parse({graphPlanSha256:Z.graphPlan.graphPlanSha256,nodeOutputDigests:j,outputs:K,outputsSha256:ef(K),runId:F.runId,version:rf});try{await VA(n0(w,"outputs.json"),W)}catch(O){if(!v8(O,"EEXIST"))throw O;let L=await M4(n0(w,"outputs.json"),QA);if(!W2(L,W))throw new N("conflict","Run outputs were already published differently.")}}else if(Q.outputs!==void 0)throw new N("invalid-data","Only completed runs may publish outputs.");await YA(n0(w,"summary.json"),Q)})}async appendGrant(_,$){let F=m_.parse(_);return await this.#j(F.runId,async(w)=>{await this.#T(w,F);let Q=await this.#M(w,F),Z=iH.parse({...$,runId:F.runId,version:pf});if(Z.graphPlanSha256!==Q.graphPlan.graphPlanSha256)throw new N("invalid-data","Run grant targets a different graph plan.");if("nodeKey"in Z&&!Q.graphPlan.graph.nodes.some((V)=>V.key===Z.nodeKey))throw new N("invalid-data",`Run grant targets unknown node ${Z.nodeKey}.`);if(Z.kind==="compute-replay"&&Z.bundleSha256!==Q.graphPlan.bundle.bundleSha256)throw new N("invalid-data","Compute replay grant targets a different bundle.");if(Z.kind==="compute-replay"){let V=Q.graphPlan.graph.nodes.find((H)=>H.key===Z.nodeKey);if(V===void 0||!j5(V))throw new N("invalid-data",`Compute replay grant targets a non-compute node: ${Z.nodeKey}`);let j=(await this.#A(Q)).find((H)=>H.nodeKey===Z.nodeKey);if(j?.status!=="ambiguous-code"||j.executionPlan===void 0||Z.computeKey!==V.executor.compute.key||Z.nodePlanSha256!==j.executionPlan.nodePlanSha256||Z.attempt!==j.attempt+1)throw new N("conflict",`Compute replay grant does not match the exact next attempt for ${Z.nodeKey}.`)}let J=this.#N(F)?.grantJournal,X=await f50(n0(w,"grants.jsonl"),iH,(V)=>VS(V,F.runId,Q.graphPlan.graphPlanSha256),({cursor:V})=>{if(V.grantIds.has(Z.grantId))throw new N("conflict",`Run grant already exists: ${Z.grantId}`);return{entry:Z,result:Z}},(V,Y)=>{return V.grantIds.add(Y.grantId),V},J);return this.#K(F,{grantJournal:X.state}),X.result})}async reopenComputeNode(_,$){let F=m_.parse(_),w=k2.parse($);return await this.#j(F.runId,async(Q)=>{await this.#T(Q,F);let Z=await this.#M(Q,F),J=Z.graphPlan.graph.nodes.find((O)=>O.key===w);if(J===void 0||!j5(J))throw new N("invalid-data",`Only a trusted compute node may be reopened: ${w}`);let X=await this.#A(Z),V=X.find((O)=>O.nodeKey===w);if(V?.status!=="ambiguous-code"||V.executionPlan===void 0)throw new N("conflict",`Compute node is not awaiting an explicit replay: ${w}`);let Y=await XS(n0(Q,"grants.jsonl"),iH);if(VS(Y,F.runId,Z.graphPlan.graphPlanSha256),!Y.some((O)=>O.kind==="compute-replay"&&O.nodeKey===w&&O.attempt===V.attempt+1&&O.bundleSha256===Z.graphPlan.bundle.bundleSha256&&O.computeKey===J.executor.compute.key&&O.nodePlanSha256===V.executionPlan?.nodePlanSha256))throw new N("authorization-required",`Compute node ${w} requires an exact replay grant for attempt ${String(V.attempt+1)}.`);let H={...V};delete H.failure,delete H.finishedAt;let K=l_.parse({...H,status:"ready"}),W=new Map(X.map((O)=>[O.nodeKey,O.nodeKey===w?K:O]));return this.#C(Z.graphPlan,J,K,W),await YA(n0(await this.#Y(Q),Yw(w)),K),K})}async requestCancellation(_,$,F=new Date){return await this.#j(_,async(w)=>{await this.#W(w,_);let Q=n0(w,"cancel-request.json"),Z=await M4(Q,aH).catch((X)=>{if(X instanceof N&&X.code==="not-found")return;throw X});if(Z!==void 0)return Z;let J=aH.parse({requestedAt:F.toISOString(),requestedBy:$,runId:_,version:x_});try{return await VA(Q,J),J}catch(X){let V=await M4(Q,aH).catch(()=>{return});if(V!==void 0)return V;throw X}})}async cancellation(_){let $=await this.#X(_);return await M4(n0($,"cancel-request.json"),aH).then((F)=>{if(F.runId!==_)throw new N("invalid-data","Cancellation request targets a different run.");return F}).catch((F)=>{if(F instanceof N&&F.code==="not-found")return;throw F})}}import{Deferred as CA,Effect as N1,Either as wW,Exit as l50,Fiber as wS0,Queue as HS}from"effect";import{randomUUID as WS}from"crypto";import{performance as Ow}from"perf_hooks";var QS0=32,ZS0=128,JS0=2000,XS0=4000,VS0=100,YS0=Object.freeze({browser:1,"capture-device":1,cpu:4,ffmpeg:2,"local-io":4,network:4,"output-publication":4,"paid-call":1,"project-render":1,"project-publication":1,vision:1,whisper:1});function d50(_,$){return $>Number.MAX_SAFE_INTEGER-_?Number.MAX_SAFE_INTEGER:_+$}function GS(_){return N1.suspend(()=>{let $=_-Ow.now();return $<=0?N1.void:N1.zipRight(N1.sleep(Math.min($,2147483647)),GS(_))})}class r50{#_=new AbortController;deadlineMonotonicMs;#$;#Q;#J;#F;#X;constructor(_,$,F){this.#J=_,this.deadlineMonotonicMs=$,this.#Q=F,this.#$=_.deferred(),this.#F=_.watch(N1.zipRight(GS($),N1.sync(()=>{this.interrupt("deadline",new N("cancelled","Workflow exceeded the host wall-clock bound."))})))}get interruption(){return this.#X}get signal(){return this.#_.signal}interrupt(_,$){if(this.#X!==void 0)return;let F={error:$,kind:_};this.#X=F,this.#_.abort($),this.#Q(F),CA.unsafeDone(this.#$,N1.fail(n9($,"monitor")))}assertActive(){if(this.#X!==void 0)throw this.#X.error}async race(_){return this.assertActive(),await this.#J.run(N1.raceFirst(p0("authority",_),CA.await(this.#$)))}async custody(_){return await this.#J.custody(_)}async runNative(_){return await this.#J.run(_)}async stop(){await this.#F()}}function QW(_,$){if(!Number.isSafeInteger(_)||_<1)throw new N("usage",`${$} must be a positive safe integer.`);return _}function jS0(_,$){if(!Number.isSafeInteger(_)||_<0)throw new N("usage",`${$} must be a nonnegative safe integer.`);return _}function NS0(_){let $=QW(_.hostLimits?.maxJobs??4,"Host job limit"),F=_.jobs===void 0?$:QW(_.jobs,"Requested job limit"),w=_.hostLimits?.resources??{},Q=Object.fromEntries(hN.map((Z)=>[Z,jS0(w[Z]??YS0[Z],`Host ${Z} limit`)]));return{cancellationPollMs:QW(_.cancellationPollMs??VS0,"Cancellation poll interval"),jobs:Math.min($,F),maxNodes:QW(_.hostLimits?.maxNodes??4096,"Host node limit"),maxWallClockMs:QW(_.hostLimits?.maxWallClockMs??86400000,"Host workflow wall-clock limit"),resources:Q}}function HS0(_){return FA(_).sha256}function o50(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)&&Object.hasOwn(_,"$ref")}function WS0(_){return Array.isArray(_)}function KS0(_){return Array.isArray(_)}function DS(_){if(_.status!=="completed"||_.output===void 0)throw new N("invalid-data",`Dependency ${_.nodeKey} does not have a completed output.`);let $=u0.parse(_.output.value);if(HS0($)!==_.output.digestSha256)throw new N("invalid-data",`Completed output digest does not match for node ${_.nodeKey}.`);return _.output}function OS(_,$){if(o50(_)){let F=$.get(_.$ref.nodeKey);if(F===void 0)throw new N("invalid-data",`Node input references unavailable output ${_.$ref.nodeKey}.`);return tH(_,F.value)}if(WS0(_))return _.map((F)=>OS(F,$));if(typeof _==="object"&&_!==null)return Object.fromEntries(Object.entries(_).sort(([F],[w])=>F.localeCompare(w)).map(([F,w])=>[F,OS(w,$)]));return _}function u50(_,$){let F=new Map,w={};for(let Q of[..._.dependencies].sort((Z,J)=>Z.localeCompare(J))){let Z=$.get(Q);if(Z===void 0)throw new N("invalid-data",`Missing dependency node ${Q}.`);let J=DS(Z);F.set(Q,J),w[Q]=J}return{dependencyOutputs:w,input:u0.parse(OS(_.input,F))}}function zS(_){return wJ.parse({..._,preparation:[..._.preparation].sort(($,F)=>$.localeCompare(F)),resources:[..._.resources].sort(($,F)=>$.resource.localeCompare(F.resource))})}function c50(_){return{..._,inputSchemaId:_.inputSchemaId.replace(/^studio\./u,"slopcamera."),outputSchemaId:_.outputSchemaId.replace(/^studio\./u,"slopcamera."),policy:FJ.parse(zS(_.policy))}}function ZW(_,$,F){let w=$.executor.operation,Q=F.get(w.kind,w.version),Z=_.registry.discovery.find((J)=>J.kind===w.kind&&J.version===w.version);if(Z===void 0)throw new N("incompatible",`Graph plan omits operation ${w.kind}@${String(w.version)}.`);if(k(c50(Q.discovery))!==k(c50(Z)))throw new N("incompatible",`Registered operation changed after planning: ${w.kind}@${String(w.version)}.`);return Q}function s50(_,$,F){if(K2($)){let w=ZW(_,$,F);return{kind:"operation",operation:w,policy:w.discovery.policy}}if(j5($))return{compute:$.executor.compute,kind:"compute",policy:QJ($.executor.compute)};throw new N("internal",`Unknown node executor for ${$.key}.`)}function i50(_){if(_.length>64)throw new N("invalid-data","A node may claim at most 64 publication keys.");let $=[..._].map((F)=>{if(F.length<1||F.length>512)throw new N("invalid-data","Publication keys must contain between 1 and 512 characters.");return F}).sort((F,w)=>F.localeCompare(w));if(new Set($).size!==$.length)throw new N("invalid-data","A node cannot claim a publication key twice.");return $}function OS0(_){let $=r9(_.input,"studio.workflow.compute-input-descriptor/v1\x00");return{inputDescriptors:u0.parse({bytes:$.bytes,inputSha256:$.sha256}),upperInputBytes:$.bytes}}function LS0(_,$,F,w){let Q=w.upperDurationMs??F.maxDurationMs,Z=w.upperInputBytes??F.maxInputBytes;if(!Number.isSafeInteger(Q)||Q<0||Q>F.maxDurationMs)throw new N("invalid-data",`Preparation duration bound exceeds policy for node ${$.key}.`);if(!Number.isSafeInteger(Z)||Z<0||Z>F.maxInputBytes)throw new N("invalid-data",`Preparation input bound exceeds policy for node ${$.key}.`);let J=aC.parse({exactInputBound:!0,executor:$.executor,graphPlanSha256:_.graphPlanSha256,inputDescriptors:u0.parse(w.inputDescriptors),nodeKey:$.key,requestedPreparation:[...F.preparation].sort((X,V)=>X.localeCompare(V)),upperDurationMs:Q,upperInputBytes:Z,version:pH});return tC.parse({...J,preparationPlanSha256:rH(J)})}function GS0(_,$,F,w,Q,Z){let J=u0.parse(Z.exactInput),X=$A(J),V=X.bytes,Y=w.exactInputBound===!0?w.upperInputBytes:F.maxInputBytes;if(V>Y)throw new N("invalid-data",`Exact input for node ${$.key} uses ${String(V)} canonical JSON bytes; the ${w.exactInputBound===!0?"prepared upper bound":"operation input limit"} is ${String(Y)}.`);let j=Object.fromEntries(Object.entries(Q.dependencyOutputs).sort(([K],[W])=>K.localeCompare(W)).map(([K,W])=>[K,W.digestSha256])),H=eC.parse({dependencyOutputDigests:j,executor:$.executor,exactInput:J,...Z.expectedProjectGeneration===void 0?{}:{expectedProjectGeneration:Z.expectedProjectGeneration},graphPlanSha256:_.graphPlanSha256,inputSha256:X.sha256,nodeKey:$.key,policy:zS(F),preparationPlanSha256:w.preparationPlanSha256,publicationKeys:i50(Z.publicationKeys),version:nH});return _A.parse({...H,nodePlanSha256:oH(H)})}function DS0(_,$,F,w){let Q=tC.parse(_),{preparationPlanSha256:Z,...J}=Q;if(Z!==rH(J)||Q.graphPlanSha256!==$.graphPlanSha256||Q.nodeKey!==F.key||k(Q.executor)!==k(F.executor)||Q.upperDurationMs>w.maxDurationMs||Q.upperInputBytes>w.maxInputBytes||k(Q.requestedPreparation)!==k([...w.preparation].sort((X,V)=>X.localeCompare(V))))throw new N("invalid-data",`Persisted preparation plan no longer matches node ${F.key}.`)}function zS0(_,$,F,w,Q,Z){let J=_A.parse(_),{nodePlanSha256:X,...V}=J,Y=$A(J.exactInput),j=Y.bytes,H=Q.exactInputBound===!0?Q.upperInputBytes:w.maxInputBytes,K=Object.fromEntries(Object.entries(Z.dependencyOutputs).sort(([W],[O])=>W.localeCompare(O)).map(([W,O])=>[W,O.digestSha256]));if(X!==oH(V)||j>H||J.inputSha256!==Y.sha256||J.graphPlanSha256!==$.graphPlanSha256||J.nodeKey!==F.key||J.preparationPlanSha256!==Q.preparationPlanSha256||k(J.executor)!==k(F.executor)||k(J.policy)!==k(zS(w))||k(J.dependencyOutputDigests)!==k(K)||k(J.publicationKeys)!==k(i50(J.publicationKeys)))throw new N("invalid-data",`Persisted execution plan no longer matches node ${F.key}.`)}function p50(_){return typeof _==="boolean"?_:_.allowed}function CS0(_,$,F,w){return _.some((Q)=>Q.kind==="preparation"&&Q.graphPlanSha256===$&&Q.nodeKey===F&&Q.preparationPlanSha256===w)}function AS0(_,$,F,w){return _.some((Q)=>Q.kind==="effect"&&Q.graphPlanSha256===$&&Q.nodeKey===F&&Q.nodePlanSha256===w)}function BS0(_){return(_.length===0?"Unknown scheduler failure.":_).slice(0,XS0)}function o5(_,$=!1){let F=qw(_),w=T5.safeParse(F.details?.spatialPublication);return{code:(()=>{switch(F.code){case"authorization-required":case"cancelled":case"conflict":case"incompatible":case"invalid-data":case"subprocess":case"unavailable":case"unsupported-plan":case"ambiguous":case"internal":return F.code;case"not-found":case"unsafe-path":case"usage":return"invalid-data"}})(),message:BS0(F.message),retryable:$,...w.success?{spatialPublication:w.data}:{}}}function TS0(_){let $=Object.entries(_).sort(([F],[w])=>F.localeCompare(w));if($.length>QS0)throw new N("internal","Operation summary exceeds the scheduler field limit.");return Object.fromEntries($.map(([F,w])=>{if(F.length<1||F.length>ZS0)throw new N("internal","Operation summary contains an invalid field name.");if(typeof w==="number"&&!Number.isFinite(w))throw new N("internal","Operation summary contains a non-finite number.");if(typeof w==="string"&&w.length>JS0)throw new N("internal","Operation summary contains an oversized string.");return[F,w]}))}function KS(_,$,F,w){let Q=u0.parse(_),Z=FA(Q),J=Z.bytes;if(J>F)throw new N("invalid-data",`Operation output uses ${String(J)} bytes; the limit is ${String(F)}.`);return{digestSha256:Z.sha256,...w===void 0?{}:{receiptReference:w},summary:TS0($),value:Q}}function US0(_){return["ambiguous","cancelled","failed","incompatible","skipped"].includes(_.status)}function kS0(_){return _.status==="pending"||_.status==="ready"||_.status==="preparing"||_.status==="approval-required"}class a50{#_;#$;#Q=new Set;#J;#F=0;constructor(_){this.#_=_.jobs,this.#$=_.resources,this.#J=Object.fromEntries(hN.map(($)=>[$,0]))}impossible(_){return _.some(($)=>$.amount>this.#$[$.resource])}acquire(_,$){if(this.#F>=this.#_)return!1;if($.some((F)=>this.#Q.has(F)))return!1;if(_.some((F)=>this.#J[F.resource]+F.amount>this.#$[F.resource]))return!1;this.#F+=1;for(let F of _)this.#J[F.resource]+=F.amount;for(let F of $)this.#Q.add(F);return!0}release(_,$){this.#F-=1;for(let F of _)this.#J[F.resource]-=F.amount;for(let F of $)this.#Q.delete(F)}}function DA(_,$){return{..._,hostResourceLease:{assertOwned:async()=>await $.assertOwned(),claims:$.claims,inheritedFileDescriptor:$.inheritedFileDescriptor,inheritedFileDescriptors:[$.inheritedFileDescriptor],profile:$.profile,ticket:$.ticket},runner:{run:async(F,w={})=>{await $.assertOwned();let Q=[...w.inheritedFileDescriptors??[],$.inheritedFileDescriptor].filter((Z,J,X)=>X.indexOf(Z)===J);if(Q.length>16)throw new N("incompatible","A workflow subprocess cannot inherit more than 16 file descriptors.");return await _.runner.run(F,{...w,inheritedFileDescriptors:Q})}}}}function MS0(_){if(!(_ instanceof c1))return qw(_);switch(_.code){case"WAIT_ABORTED":return new N("cancelled",_.message);case"WAIT_TIMEOUT":return new N("unavailable",_.message);case"OWNERSHIP_LOST":return new N("conflict",_.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":return new N("incompatible",_.message);default:return _.code}}function t50(_){return{cancelled:_.filter(($)=>$.status==="cancelled").length,completed:_.filter(($)=>$.status==="completed").length,failed:_.filter(($)=>$.status==="failed"||$.status==="incompatible"||$.status==="ambiguous").length,pending:_.filter(($)=>$.status==="pending"||$.status==="ready"||$.status==="preparing"||$.status==="running"||$.status==="approval-required"||$.status==="ambiguous-code").length,skipped:_.filter(($)=>$.status==="skipped").length}}function n50(_,$,F){if($.pause!==void 0)return"approval-required";if(_.some((Q)=>Q.status==="approval-required"))return"approval-required";if(_.some((Q)=>Q.status==="ambiguous-code"))return"ambiguous-code";if(F>0||_.some((Q)=>Q.status==="running")||_.some(kS0))return"running";let w=t50(_);if(w.cancelled>0)return"cancelled";if(w.failed===0&&w.skipped===0&&w.completed===_.length)return"completed";if($.cancelled)return"cancelled";if(_.some((Q)=>Q.status==="incompatible")&&w.completed===0)return"incompatible";if(w.completed>0)return"partial";return"failed"}function zA(_){return _==="cancelled"||_==="completed"||_==="failed"||_==="incompatible"||_==="partial"}function LS(_,$){if(o50(_)){let w=$.get(_.$ref.nodeKey);if(w===void 0||w.status!=="completed")return;return tH(_,DS(w).value)}if(KS0(_)){let w=[];for(let Q of _){let Z=LS(Q,$);if(Z===void 0)return;w.push(Z)}return w}let F={};for(let[w,Q]of Object.entries(_).sort(([Z],[J])=>Z.localeCompare(J))){let Z=LS(Q,$);if(Z===void 0)return;F[w]=Z}return F}class CS{#_;#$;#Q;#J;#F;#X;#Y;#V;#w;#j;#W;#U=new Set;#Z;constructor(_){if(_.owner.length<1||_.owner.length>256)throw new N("usage","Scheduler owner must contain between 1 and 256 characters.");if(_.authorization.grantedBy.length<1||_.authorization.grantedBy.length>256)throw new N("usage","Authorization owner must contain between 1 and 256 characters.");if(this.#_=_.application,this.#$=_.authorization,this.#Q=_.compute,this.#J=_.compute?.kind==="fresh"?_.compute.executor:void 0,_.currentApplicationBuild.length<1||_.currentApplicationBuild.length>160)throw new N("usage","Current application build must contain between 1 and 160 characters.");this.#F=_.currentApplicationBuild,this.#X=_.hostResourceCoordinator,this.#Y=NS0(_),this.#V=_.nodePlanner,this.#w=_.now??(()=>new Date),this.#j=_.owner,this.#W=_.registry,this.#Z=_.store}async run(_){let $=new cf;try{return await $.run(this.#H(_,$))}finally{await $.stop()}}#H(_,$){return j50(N1.gen(this,function*(){let F=yield*p0("authority",()=>this.#Z.graphPlan(_));if(F.graph.nodes.length>this.#Y.maxNodes)return yield*N1.fail(n9(new N("incompatible",`Workflow has ${String(F.graph.nodes.length)} nodes; the host limit is ${String(this.#Y.maxNodes)}.`)));let w=!0,Q=yield*uf(p0("admission",()=>this.#Z.acquireClaim(_,{owner:this.#j})),(D)=>w?this.#L(D):N1.void),Z;yield*uf(N1.void,()=>p0("cleanup",()=>Z?.release()));let J=d50(Ow.now(),this.#Y.maxWallClockMs),V={cancelled:!1,monitorError:void 0,pause:void 0,reconciliationDeferred:!1,startedAt:(yield*p0("authority",()=>this.#G(_))).startedAt??this.#w().toISOString()},Y=new Map,j=yield*HS.unbounded(),H=new Map,K=new a50(this.#Y),W=new r50($,J,(D)=>{if(D.kind==="monitor")V.monitorError=D.error;else V.cancelled=!0;if(D.kind!=="deadline"){for(let z of Y.values())if(z.admissionAbortController.abort(),z.cancellable)z.abortController.abort()}}),O=$.watch(N1.forever(N1.gen(this,function*(){yield*N1.sleep(this.#Y.cancellationPollMs);let D=yield*N1.either(p0("monitor",()=>this.#N(_)));if(wW.isLeft(D))W.interrupt("monitor",qw(D.left.cause));else if(D.right!==void 0)W.interrupt("cancellation",new N("cancelled","Workflow cancellation requested."))}))),L=yield*N1.exit(N1.catchAll(N1.gen(this,function*(){yield*p0("authority",()=>this.#Z.assertFence(Q)),yield*p0("authority",()=>this.#Z.appendEvent(Q,{details:{status:"running"},kind:"run-status",timestamp:this.#w().toISOString()}));let D=yield*N1.either(N1.gen(this,function*(){yield*p0("authority",()=>this.#k(_,F)),Z=yield*p0("authority",()=>this.#M(Q,F,V,W))}));if(wW.isLeft(D)){let z=D.left.cause,C=qw(z);if(C.code!=="incompatible"&&C.code!=="unsupported-plan")return yield*N1.fail(n9(z));yield*p0("authority",()=>this.#g(Q,F,V,C));let A=yield*p0("authority",()=>this.#q(Q,F,V,0));return yield*p0("authority",()=>this.#Z.appendEvent(Q,{details:{status:A.status},kind:"run-finalized",timestamp:this.#w().toISOString()})),yield*p0("authority",()=>this.#Z.releaseClaim(Q)),w=!1,{summary:A}}if(yield*p0("authority",()=>this.#D(Q,F,V,W)),yield*p0("authority",()=>this.#q(Q,F,V,Y.size)),V.reconciliationDeferred){let z=yield*p0("authority",()=>this.#q(Q,F,V,0));return yield*p0("authority",()=>this.#Z.appendEvent(Q,{details:{status:z.status},kind:"run-status",timestamp:this.#w().toISOString()})),yield*p0("authority",()=>this.#Z.releaseClaim(Q)),w=!1,{summary:z}}while(!0){if(V.monitorError!==void 0)return yield*N1.fail(n9(V.monitorError));if(yield*p0("authority",()=>this.#Z.assertFence(Q)),(yield*p0("authority",()=>this.#N(_)))!==void 0){V.cancelled=!0;for(let B of Y.values())if(B.admissionAbortController.abort(),B.cancellable)B.abortController.abort()}if(Ow.now()>=J){V.cancelled=!0;for(let B of Y.values())if(B.admissionAbortController.abort(),B.cancellable)B.abortController.abort()}if(yield*p0("authority",()=>this.#C(Q,F,V)),V.cancelled)yield*p0("authority",()=>this.#P(Q,F));else if(V.pause===void 0){if(yield*p0("authority",()=>this.#E(Q,F,V,W,H)),V.pause===void 0){if(yield*p0("authority",()=>this.#B(Q,H,Y,K,J,W,$,j)),V.cancelled)yield*p0("authority",()=>this.#P(Q,F))}}if(Y.size>0){let B=yield*HS.take(j),T=Y.get(B.nodeKey);if(T===void 0)continue;let M={item:T,outcome:yield*B.outcome};Y.delete(M.item.nodeKey),K.release(M.item.resources,M.item.publicationKeys);let R=yield*p0("authority",()=>this.#f(Q,F,M.item,M.outcome,W));if(yield*p0("authority",()=>this.#q(Q,F,V,Y.size)),R){V.reconciliationDeferred=!0;let g=yield*p0("authority",()=>this.#q(Q,F,V,Y.size));return yield*p0("authority",()=>this.#Z.appendEvent(Q,{details:{status:g.status},kind:"run-status",timestamp:this.#w().toISOString()})),yield*p0("authority",()=>this.#Z.releaseClaim(Q)),w=!1,{summary:g}}continue}let z=yield*p0("authority",()=>this.#Z.nodes(_));if(n50(z,V,0)==="running"){if(yield*p0("authority",()=>this.#I(Q,F,K)))continue;return yield*N1.fail(n9(new N("internal","Workflow scheduler reached a nonterminal state without runnable work.")))}let A=yield*p0("authority",()=>this.#q(Q,F,V,0));return yield*p0("authority",()=>this.#Z.appendEvent(Q,{details:{status:A.status},kind:zA(A.status)?"run-finalized":"run-status",timestamp:this.#w().toISOString()})),yield*p0("authority",()=>this.#Z.releaseClaim(Q)),w=!1,{...V.pause===void 0?{}:{pause:V.pause},summary:A}}}),(D)=>N1.gen(this,function*(){let z=D.cause;if(w&&(W.interruption?.kind==="cancellation"||W.interruption?.kind==="deadline")){let C=[...Y.values()].sort((B,T)=>B.nodeKey.localeCompare(T.nodeKey));if(C.length>0){let B=yield*N1.forEach(C,(T)=>N1.flatMap(wS0.join(T.fiber),(M)=>N1.map(M,(R)=>({item:T,outcome:R}))),{concurrency:"unbounded"});Y.clear();for(let T of B){K.release(T.item.resources,T.item.publicationKeys);let M=yield*p0("authority",()=>this.#f(Q,F,T.item,T.outcome,W));V.reconciliationDeferred||=M}}yield*p0("authority",()=>this.#P(Q,F));let A=yield*p0("authority",()=>this.#q(Q,F,V,Y.size));return yield*p0("authority",()=>this.#Z.appendEvent(Q,{details:{status:A.status},kind:zA(A.status)?"run-finalized":"run-status",timestamp:this.#w().toISOString()})),yield*p0("authority",()=>this.#Z.releaseClaim(Q)),w=!1,{summary:A}}if(w){let C=qw(z);if(C.code!=="conflict")yield*p0("authority",()=>this.#y(Q,F,V,C).catch(()=>{return}))}return yield*N1.fail(n9(z))}))),G=yield*N1.exit(N1.gen(this,function*(){yield*p0("authority",()=>O()),yield*p0("authority",()=>W.stop())}));return yield*l50.zipLeft(L,G)}))}#L(_){return N1.gen(this,function*(){let $=yield*N1.either(p0("cleanup",()=>this.#Z.assertFence(_)));if(wW.isLeft($)){if($.left.cause instanceof N&&$.left.cause.code==="conflict")return;return yield*N1.fail($.left)}let F=yield*N1.either(p0("cleanup",()=>this.#Z.releaseClaim(_)));if(wW.isRight(F))return;if(F.left.cause instanceof N&&F.left.cause.code==="conflict"){let w=yield*N1.either(p0("cleanup",()=>this.#Z.assertFence(_)));if(wW.isLeft(w)&&w.left.cause instanceof N&&w.left.cause.code==="conflict")return}return yield*N1.fail(F.left)})}async#G(_){return await this.#Z.summary(_)}async#N(_){let $;for(let F=0;F<4;F+=1)try{return await this.#Z.cancellation(_)}catch(w){let Q=qw(w);if(Q.code!=="conflict")throw w;$=Q,await Promise.resolve()}throw $??new N("conflict",`Could not read a stable cancellation marker for ${_}.`)}async#z(_,$){if($.assertActive(),await $.race(async()=>await this.#N(_.runId))!==void 0)$.interrupt("cancellation",new N("cancelled","Workflow cancellation requested.")),$.assertActive()}async#K(_,$,F){await this.#z(_,$);let w=await $.race(F);return $.assertActive(),w}async#k(_,$){if($.runtime.applicationBuild!==this.#F)throw new N("incompatible","Persisted workflow application build differs from the current host build.");let F=await this.#Z.runtime(_);if(k(F.runtime)!==k($.runtime))throw new N("incompatible","Persisted workflow runtime identity changed.");let w=[...new Set($.graph.nodes.filter(K2).map((J)=>`${J.executor.operation.kind}@${String(J.executor.operation.version)}`))].sort((J,X)=>J.localeCompare(X)),Q=F.operations.map((J)=>`${J.kind}@${String(J.version)}`).sort((J,X)=>J.localeCompare(X));if(k(w)!==k(Q))throw new N("incompatible","Persisted operation runtime set changed.");let Z=[...new Map($.graph.nodes.filter(j5).map((J)=>[J.executor.compute.key,J.executor.compute])).values()].sort((J,X)=>J.key.localeCompare(X.key));if(k(Z)!==k(F.computes))throw new N("incompatible","Persisted compute runtime set changed.");for(let J of $.graph.nodes)if(K2(J))ZW($,J,this.#W)}async#M(_,$,F,w){let Q=this.#Q;if(Q===void 0)return;if(Q.kind==="fresh"){if(Q.executor.bundleSha256!==$.bundle.bundleSha256)throw new N("incompatible","Fresh code worker bundle does not match the persisted graph plan.");this.#J=Q.executor;return}let Z=[...new Set(Q.nodeKeys.map((K)=>k2.parse(K)))].sort((K,W)=>K.localeCompare(W));if(Z.length===0)throw new N("usage","A compute replay requires at least one exact node key.");if(await this.#N(_.runId)!==void 0){F.cancelled=!0;return}let J=await this.#Z.nodes(_.runId),X=new Map($.graph.nodes.map((K)=>[K.key,K])),V=[];for(let K of Z){let W=X.get(K),O=J.find((L)=>L.nodeKey===K);if(W===void 0||!j5(W)||O?.status!=="ambiguous-code"||O.executionPlan===void 0)throw new N("conflict",`Compute node is not awaiting exact replay: ${K}`);V.push({attempt:O.attempt+1,bundleSha256:$.bundle.bundleSha256,computeKey:W.executor.compute.key,createdAt:this.#w().toISOString(),graphPlanSha256:$.graphPlanSha256,grantedBy:this.#$.grantedBy,grantId:WS(),kind:"compute-replay",nodeKey:K,nodePlanSha256:O.executionPlan.nodePlanSha256})}for(let K of V){if(await this.#N(_.runId)!==void 0){F.cancelled=!0;return}await this.#Z.appendGrant(_,K)}if(await this.#N(_.runId)!==void 0){F.cancelled=!0;return}await this.#z(_,w);let Y=w.deadlineMonotonicMs-Ow.now();if(Y<=0)w.interrupt("deadline",new N("cancelled","Workflow exceeded the host wall-clock bound.")),w.assertActive();let j=Q.load({signal:w.signal,waitTimeoutMilliseconds:Math.min(d$,Math.max(1,Math.ceil(Y)))}),H;try{H=await w.race(async()=>await j)}catch(K){throw j.then(async(W)=>await W.release(),()=>{return}).catch(()=>{return}),K}try{if(w.assertActive(),H.executor.bundleSha256!==$.bundle.bundleSha256)throw new N("incompatible","Replay code worker bundle does not match the persisted graph plan.");this.#J=H.executor;for(let K of Z)this.#U.add(K);for(let K of Z)await this.#Z.reopenComputeNode(_,K);return H}catch(K){throw await H.release().catch(()=>{return}),K}}async#D(_,$,F,w){let Q=await this.#Z.nodes(_.runId),Z=new Map(Q.map((J)=>[J.nodeKey,J]));for(let J of[...$.graph.nodes].sort((X,V)=>X.key.localeCompare(V.key))){let X=Z.get(J.key);if(X===void 0)throw new N("invalid-data",`Run is missing node ${J.key}.`);if(X.status==="completed"){DS(X),await this.#Z.appendEvent(_,{details:{digestSha256:X.output?.digestSha256??""},kind:"node-reused",nodeKey:J.key,timestamp:this.#w().toISOString()});continue}if(X.status==="approval-required")continue;if(X.status==="preparing"){await this.#O(_,{...X,status:"ready"});continue}if(X.status!=="running")continue;if(j5(J)){await this.#O(_,{...X,failure:o5(new N("ambiguous","Interrupted trusted compute requires an explicit exact-bundle replay.")),finishedAt:this.#w().toISOString(),status:"ambiguous-code"});continue}if(!K2(J))throw new N("internal",`Unknown node executor for ${J.key}.`);let V=ZW($,J,this.#W).discovery.policy.resume;if(V==="deterministic"){await this.#O(_,{...X,failure:void 0,finishedAt:void 0,status:"ready"});continue}let Y=await this.#A(_,$,J,X,Z,w);if(Y.deferred){if(F.reconciliationDeferred=!0,w.interruption!==void 0)break;continue}if(Y.reconciliation?.kind==="ambiguous"&&V==="non-resumable-live")F.cancelled=!1}}async#A(_,$,F,w,Q,Z){let J=ZW($,F,this.#W),X=u50(F,Q),V=J.discovery.policy.resume;await this.#Z.assertFence(_);let Y=w.executionPlan===void 0?void 0:await this.#Z.stagingDirectory(_,F.key,w.executionPlan.nodePlanSha256),j;try{let H=this.#V.reconcile,K=this.#V.reconcileEffect;j=H===void 0&&K===void 0?void 0:await this.#K(_,Z,async()=>{let W=async()=>await this.#X.withLease(Y3(J.discovery.policy.resources,this.#X),async(O)=>{await O.assertOwned();let L=async()=>{if(await O.assertOwned(),Z.assertActive(),Z.signal.aborted)throw new N("cancelled","Workflow reconciliation was cancelled before publication.");await this.#Z.assertFence(_),await this.#z(_,Z),await this.#Z.assertFence(_),Z.assertActive(),await O.assertOwned()},G={abortSignal:Z.signal,application:DA(this.#_,O),beforePublication:L,dependencyOutputs:X.dependencyOutputs,executionPlan:w.executionPlan,graphPlan:$,node:F,operation:J.discovery,preparationPlan:w.preparationPlan,previous:w,resolvedInput:X.input,resumeClass:V,runId:_.runId,...Y===void 0?{}:{workspaceDirectory:Y}};return K===void 0?await H.call(this.#V,G):await Z.runNative(K.call(this.#V,G))},{signal:Z.signal,waitTimeoutMilliseconds:d$});return K===void 0?await W():await Z.custody(p0("authority",W))})}catch{return await this.#Z.assertFence(_),{deferred:!0,reconciliation:void 0}}return await this.#Z.assertFence(_),await this.#R(_,w,J,V,j),{deferred:!1,reconciliation:j}}async#R(_,$,F,w,Q){if(Q?.kind==="completed"){let V=KS(Q.output,Q.summary,F.discovery.policy.maxOutputBytes,Q.receiptReference);await this.#O(_,{...$,failure:void 0,finishedAt:this.#w().toISOString(),output:V,status:"completed"});return}let Z=w==="verified-receipt"||w==="recoverable-transaction";if(Q?.kind==="retry"&&Z){await this.#O(_,{...$,failure:void 0,finishedAt:void 0,status:"ready"});return}if(Q?.kind==="incompatible"){await this.#O(_,{...$,failure:o5(new N("incompatible",Q.message)),finishedAt:this.#w().toISOString(),status:"incompatible"});return}let J=Q?.kind==="ambiguous"?Q.message:w==="non-resumable-live"?"Interrupted live operation requires explicit operator reconciliation.":w==="ambiguous-after-dispatch"?"Interrupted paid operation has an ambiguous dispatch outcome.":"Interrupted operation has no compatible reconciliation implementation.",X=w==="verified-receipt"||w==="recoverable-transaction"?"incompatible":"ambiguous";await this.#O(_,{...$,failure:o5(new N(X==="incompatible"?"incompatible":"ambiguous",J)),finishedAt:this.#w().toISOString(),status:X})}async#C(_,$,F){let w=!0;while(w){w=!1;let Q=await this.#Z.nodes(_.runId),Z=new Map(Q.map((J)=>[J.nodeKey,J]));for(let J of[...$.graph.nodes].sort((X,V)=>X.key.localeCompare(V.key))){let X=Z.get(J.key);if(X===void 0||X.status!=="pending")continue;let V=J.dependencies.map((Y)=>Z.get(Y));if(V.some((Y)=>Y===void 0))throw new N("invalid-data",`Node ${J.key} has a missing dependency.`);if(V.some((Y)=>Y!==void 0&&US0(Y))){let Y={...X,finishedAt:this.#w().toISOString(),status:F.cancelled?"cancelled":"skipped"};await this.#O(_,Y),Z.set(J.key,Y),w=!0;continue}if(V.every((Y)=>Y?.status==="completed")){let Y={...X,status:"ready"};await this.#O(_,Y),Z.set(J.key,Y),w=!0}}}}async#E(_,$,F,w,Q){let Z=await this.#Z.nodes(_.runId),J=new Map(Z.map((V)=>[V.nodeKey,V])),X=new Map($.graph.nodes.map((V)=>[V.key,V]));for(let V of Z.filter((Y)=>Y.status==="ready"||Y.status==="approval-required").sort((Y,j)=>Y.nodeKey.localeCompare(j.nodeKey))){if(F.pause!==void 0||F.cancelled)break;if(Q.has(V.nodeKey))continue;await this.#z(_,w);let Y=X.get(V.nodeKey);if(Y===void 0)throw new N("invalid-data",`Run contains unknown node ${V.nodeKey}.`);let j=s50($,Y,this.#W),H=u50(Y,J),K;if(j.kind==="operation"){if(!K2(Y))throw new N("internal",`Node executor classification changed for ${Y.key}.`);K={dependencyOutputs:H.dependencyOutputs,graphPlan:$,node:Y,operation:j.operation.discovery,resolvedInput:H.input,runId:_.runId}}let W=V.preparationPlan;if(W===void 0){await this.#O(_,{...V,status:"preparing"}),await this.#Z.assertFence(_);let z=K===void 0?OS0(H):await this.#K(_,w,async()=>await this.#V.prepare(K));W=LS0($,Y,j.policy,z)}else DS0(W,$,Y,j.policy);if(!await this.#T(_,$,Y,j,W,w)){let z=l_.parse({...V,preparationPlan:W,status:"approval-required",version:Vw});await this.#O(_,z),F.pause={nodeKey:Y.key,phase:"preparation",planSha256:W.preparationPlanSha256},await this.#Z.appendEvent(_,{details:{phase:"preparation",planSha256:W.preparationPlanSha256},kind:"approval-required",nodeKey:Y.key,timestamp:this.#w().toISOString()});break}let L=V.executionPlan;if(L===void 0){await this.#Z.assertFence(_);let z=K===void 0?{exactInput:H.input,publicationKeys:[]}:await this.#K(_,w,async()=>{if(K.operation.kind!=="slopcamera.studio.run")return await this.#V.plan({...K,preparationPlan:W});return await this.#X.withLease(Y3(K.operation.policy.resources,this.#X),async(C)=>{let A=async()=>{await C.assertOwned(),await this.#Z.assertFence(_),await this.#z(_,w),await this.#Z.assertFence(_),await C.assertOwned()};return await A(),await this.#V.plan({...K,preparationPlan:W,application:DA(this.#_,C),abortSignal:w.signal,beforePublication:A})},{signal:w.signal})});L=GS0($,Y,j.policy,W,H,z)}else zS0(L,$,Y,j.policy,W,H);if(!await this.#b(_,$,Y,j,L,w)){let z=l_.parse({...V,executionPlan:L,preparationPlan:W,status:"approval-required",version:Vw});await this.#O(_,z),F.pause={nodeKey:Y.key,phase:"effect",planSha256:L.nodePlanSha256},await this.#Z.appendEvent(_,{details:{phase:"effect",planSha256:L.nodePlanSha256},kind:"approval-required",nodeKey:Y.key,timestamp:this.#w().toISOString()});break}let D=l_.parse({...V,executionPlan:L,failure:void 0,preparationPlan:W,status:"ready",version:Vw});if(V.status!=="ready"||V.preparationPlan===void 0||V.executionPlan===void 0||V.failure!==void 0)await this.#O(_,D);J.set(Y.key,D),Q.set(Y.key,{executionPlan:L,executor:j,record:D,resolved:H})}}async#T(_,$,F,w,Q,Z){if(Q.requestedPreparation.length===0)return!0;let J=await this.#Z.grants(_.runId);if(CS0(J,$.graphPlanSha256,Q.nodeKey,Q.preparationPlanSha256))return!0;if(!p50(await this.#K(_,Z,async()=>await this.#$.authorizePreparation({executor:F.executor,graphPlanSha256:$.graphPlanSha256,nodeKey:Q.nodeKey,...w.kind==="operation"?{operation:w.operation.discovery}:{},policy:w.policy,preparationPlan:Q,runId:_.runId}))))return!1;let V={createdAt:this.#w().toISOString(),graphPlanSha256:$.graphPlanSha256,grantedBy:this.#$.grantedBy,grantId:WS(),kind:"preparation",nodeKey:Q.nodeKey,preparationPlanSha256:Q.preparationPlanSha256};return await this.#z(_,Z),await this.#Z.appendGrant(_,V),!0}async#b(_,$,F,w,Q,Z){if(w.kind==="operation"&&w.operation.discovery.kind==="slopcamera.studio.run"){let Y=this.#_.studioAuthorization;if(Y===void 0||!await this.#K(_,Z,async()=>await Y.authorize(EP(Q.exactInput))))return!1}let J=await this.#Z.grants(_.runId);if(AS0(J,$.graphPlanSha256,Q.nodeKey,Q.nodePlanSha256))return!0;if(!p50(await this.#K(_,Z,async()=>await this.#$.authorizeEffect({executor:F.executor,executionPlan:Q,graphPlanSha256:$.graphPlanSha256,nodeKey:Q.nodeKey,...w.kind==="operation"?{operation:w.operation.discovery}:{},policy:w.policy,runId:_.runId}))))return!1;let V={createdAt:this.#w().toISOString(),graphPlanSha256:$.graphPlanSha256,grantedBy:this.#$.grantedBy,grantId:WS(),kind:"effect",nodeKey:Q.nodeKey,nodePlanSha256:Q.nodePlanSha256};return await this.#z(_,Z),await this.#Z.appendGrant(_,V),!0}async#B(_,$,F,w,Q,Z,J,X){for(let V of[...$.values()].sort((Y,j)=>Y.record.nodeKey.localeCompare(j.record.nodeKey))){if(Ow.now()>=Q){Z.interrupt("deadline",new N("cancelled","Workflow exceeded the host wall-clock bound."));break}let Y=V.executor.policy.resources;if(w.impossible(Y)){await this.#O(_,{...V.record,failure:o5(new N("incompatible",`Node ${V.record.nodeKey} exceeds the host resource ceiling.`)),finishedAt:this.#w().toISOString(),status:"incompatible"}),$.delete(V.record.nodeKey);continue}if(!w.acquire(Y,V.executionPlan.publicationKeys))continue;try{if(await this.#Z.assertFence(_),await this.#N(_.runId)!==void 0){w.release(Y,V.executionPlan.publicationKeys),Z.interrupt("cancellation",new N("cancelled","Workflow cancellation requested."));break}let j=new AbortController,H=new AbortController,K=l_.parse({...V.record,attempt:V.record.attempt+1,startedAt:this.#w().toISOString(),status:"running",version:Vw});await this.#O(_,K),$.delete(V.record.nodeKey);let W={admissionAbortController:j,abortController:H,cancellable:V.executor.policy.cancellable,executionPlan:V.executionPlan,nodeKey:V.record.nodeKey,fiber:J.fork(N1.exit(this.#S(_,V,j,H,Q,J)).pipe(N1.tap((O)=>HS.offer(X,{nodeKey:V.record.nodeKey,outcome:O})))),publicationKeys:V.executionPlan.publicationKeys,resources:Y};F.set(V.record.nodeKey,W)}catch(j){throw w.release(Y,V.executionPlan.publicationKeys),j}}}#S(_,$,F,w,Q,Z){return N1.gen(this,function*(){let J=!1,X,V=!1,Y=!1,j=d50(Ow.now(),$.executor.policy.maxDurationMs),H=Math.min(j,Q),K=Q<=j?"workflow":"node",W=Z.deferred(),O=()=>new N("unavailable",K==="workflow"?"Workflow exceeded the host wall-clock bound.":"Operation exceeded its registered duration bound."),L=Z.watch(N1.zipRight(GS(H),N1.sync(()=>{if(J=!0,X=K,CA.unsafeDone(W,N1.fail(n9(O(),"admission"))),F.abort(),$.executor.policy.cancellable)w.abort()})),!0),G=async(A)=>{if(J)throw O();return await Z.run(N1.raceFirst(p0("authority",A),CA.await(W)))},D=()=>{if(J)throw new N("cancelled","Workflow node deadline expired before publication.")},z=yield*N1.exit(N1.catchAll(N1.gen(this,function*(){if(yield*p0("operation",()=>G(async()=>await this.#Z.assertFence(_))),(yield*p0("operation",()=>G(async()=>await this.#N(_.runId))))!==void 0)return yield*N1.fail(n9(new N("cancelled","Workflow cancellation requested."),"operation"));if($.executor.policy.effect==="paid-cloud"||$.executionPlan.publicationKeys.length>0){if(yield*p0("operation",()=>G(async()=>await this.#Z.assertFence(_))),(yield*p0("operation",()=>G(async()=>await this.#N(_.runId))))!==void 0)return yield*N1.fail(n9(new N("cancelled","Workflow cancellation requested before dispatch or publication."),"operation"))}let A=this.#_,B=async(g,U=A)=>{if($.executor.kind!=="operation")throw new N("internal",`Compute node ${$.record.nodeKey} entered operation execution.`);if(await G(async()=>await this.#Z.assertFence(_)),await G(async()=>await this.#Z.cancellation(_.runId))!==void 0)throw new N("cancelled","Workflow cancellation requested before project publication.");let E=await G(async()=>await this.#Z.stagingDirectory(_,$.record.nodeKey,$.executionPlan.nodePlanSha256));await g.assertOwned();let f=DA(U,g),v=$.executor.operation,m={abortSignal:w.signal,application:f,...$.executionPlan.expectedProjectGeneration===void 0?{}:{expectedProjectGeneration:$.executionPlan.expectedProjectGeneration},runFence:{generation:_.generation,owner:_.owner,token:_.token},workflow:{beforePublication:async()=>{if(D(),await g.assertOwned(),await G(async()=>await this.#Z.assertFence(_)),D(),await G(async()=>await this.#N(_.runId))!==void 0)throw new N("cancelled","Workflow cancellation requested before publication.");D(),V=!0},nodeKey:$.record.nodeKey,nodePlanSha256:$.executionPlan.nodePlanSha256,runId:_.runId,workspaceDirectory:E}},y=v.executeEffect===void 0?await v.execute(m,$.executionPlan.exactInput):kj(await Z.run(N1.exit(v.executeEffect(m,$.executionPlan.exactInput))));if(v.discovery.kind.startsWith("spatial.project.")&&v.discovery.kind!=="spatial.project.snapshot"){let l=y.output;if(l.kind!=="completed")throw new N(l.kind==="ambiguous"?"ambiguous":"conflict",l.message??"Spatial publication did not complete.",{spatialPublication:y.output})}return y},T=Y3($.executor.policy.resources,this.#X),M={signal:F.signal,waitTimeoutMilliseconds:Math.min(d$,Math.max(1,Math.floor(H-Ow.now())))},R;if($.executor.kind==="compute"){let g=$.executor.compute,U=this.#J,E=this.#Q?.kind!=="replay"||this.#U.has($.record.nodeKey);if(U===void 0||!E)return{failure:o5(new N("ambiguous","Trusted compute requires explicit authorization to reload its exact persisted bundle.")),kind:"ambiguous-code"};let f=Z.custody(p0("admission",()=>this.#X.withLease(T,async(m)=>{return await m.assertOwned(),Y=!0,await U.execute({abortSignal:w.signal,computeKey:g.key,...m.inheritedFileDescriptor<3?{}:{inheritedHostResourceFileDescriptor:m.inheritedFileDescriptor},input:$.executionPlan.exactInput,nodeKey:$.record.nodeKey,replayAcknowledged:this.#Q?.kind==="replay",timeoutMs:Math.max(1,Math.floor(H-Ow.now()))})},M))),v=yield*p0("operation",()=>G(async()=>await f));yield*p0("operation",()=>G(async()=>await this.#Z.assertFence(_))),R=yield*GY("operation",()=>KS(v,{computeKey:g.key,trustedCode:!0},$.executor.policy.maxOutputBytes))}else{let g=$.executor.operation,U=$.executionPlan.publicationKeys.some((v)=>v.startsWith("project:")),E=Z.custody(p0("admission",()=>this.#X.withLease(T,async(v)=>g.discovery.kind.startsWith("spatial.project.")?await UZ(DA(this.#_,v),String($.executionPlan.exactInput.project),async(m)=>await B(v,m),async()=>{if(D(),await v.assertOwned(),w.signal.aborted)throw new N("cancelled","Spatial project custody was cancelled before publication.");if(await G(async()=>await this.#Z.assertFence(_)),await G(async()=>await this.#N(_.runId))!==void 0)throw new N("cancelled","Workflow cancellation requested before spatial publication.");if(D(),w.signal.aborted)throw new N("cancelled","Spatial project custody was cancelled before publication.");await v.assertOwned()},g.discovery.kind==="spatial.project.migrate"?"mutation":"read"):U?await jX(this.#_,g.discovery.kind,$.executionPlan.exactInput,async()=>await B(v)):await B(v),M))),f=yield*p0("operation",()=>G(async()=>await E));yield*p0("operation",()=>G(async()=>await this.#Z.assertFence(_))),R=yield*GY("operation",()=>KS(f.output,f.summary.fields,$.executor.policy.maxOutputBytes,f.receiptReference))}return{kind:"completed",output:R}}),(A)=>GY("operation",()=>{let B=A.cause,T=MS0(B);if($.executor.kind==="compute"){if(T.code==="cancelled"&&!Y)return{failure:o5(new N("cancelled","Workflow node was cancelled.")),kind:"cancelled"};if(T.code==="invalid-data"||T.code==="unsupported-plan"||T.code==="incompatible")return{failure:o5(T),kind:"failed"};return{failure:o5(new N("ambiguous",J?X==="workflow"?"Trusted compute exceeded the workflow wall-clock bound and requires explicit replay.":"Trusted compute exceeded its duration bound and requires explicit replay.":`Trusted compute was interrupted and requires explicit replay: ${T.message}`)),kind:"ambiguous-code"}}let M=T.details?.spatialPublication;if($.executor.operation.discovery.kind.startsWith("spatial.project.")&&M!==void 0){let g=T5.safeParse(M);if(g.success&&g.data.kind!=="completed")return{failure:o5(T),kind:g.data.kind==="ambiguous"?"ambiguous":"failed"}}if(V&&($.executor.policy.resume==="verified-receipt"||$.executor.policy.resume==="recoverable-transaction"))return{failure:o5(new N("ambiguous",J?X==="workflow"?"Recoverable publication exceeded the workflow wall-clock bound.":"Recoverable publication exceeded its duration bound.":`Recoverable publication requires reconciliation: ${T.message}`,T.details)),kind:"interrupted"};if(T.code==="cancelled"||w.signal.aborted&&!J)return{failure:o5(new N("cancelled","Workflow node was cancelled.")),kind:"cancelled"};if($.executor.policy.resume==="ambiguous-after-dispatch"||$.executor.policy.resume==="non-resumable-live")return{failure:o5(new N("ambiguous",J?X==="workflow"?"Operation exceeded the workflow wall-clock bound after dispatch.":"Operation exceeded its duration bound after dispatch.":T.message,T.details)),kind:"ambiguous"};return{failure:o5(J?new N("unavailable",X==="workflow"?"Operation exceeded the workflow wall-clock bound.":"Operation exceeded its registered duration bound."):T,T.code==="unavailable"||T.code==="subprocess"),kind:"failed"}}))),C=yield*N1.exit(N1.gen(this,function*(){yield*p0("operation",()=>L())}));return yield*l50.zipLeft(z,C)})}async#f(_,$,F,w,Q){await this.#Z.assertFence(_);let Z=await this.#Z.node(_.runId,F.nodeKey);if(w.kind==="completed")return await this.#O(_,{...Z,failure:void 0,finishedAt:this.#w().toISOString(),output:w.output,status:"completed"}),!1;if(w.kind==="interrupted"){let J=$.graph.nodes.find((j)=>j.key===F.nodeKey);if(J===void 0||!K2(J))throw new N("invalid-data",`Missing recoverable operation node ${F.nodeKey}.`);let X=await this.#Z.nodes(_.runId),V=new Map(X.map((j)=>[j.nodeKey,j]));return(await this.#A(_,$,J,Z,V,Q)).deferred}if(await this.#O(_,{...Z,failure:w.failure,finishedAt:this.#w().toISOString(),status:w.kind}),w.kind==="ambiguous"){if($.graph.nodes.find((X)=>X.key===F.nodeKey)===void 0)throw new N("invalid-data",`Missing graph node ${F.nodeKey}.`)}return!1}async#P(_,$){let F=await this.#Z.nodes(_.runId),w=new Set($.graph.nodes.map((Q)=>Q.key));for(let Q of F.filter((Z)=>Z.status==="pending"||Z.status==="ready"||Z.status==="preparing"||Z.status==="approval-required"||Z.status==="ambiguous-code").sort((Z,J)=>Z.nodeKey.localeCompare(J.nodeKey))){if(!w.has(Q.nodeKey))continue;await this.#O(_,{...Q,finishedAt:this.#w().toISOString(),status:"cancelled"})}}async#I(_,$,F){let w=await this.#Z.nodes(_.runId),Q=new Map($.graph.nodes.map((J)=>[J.key,J])),Z=!1;for(let J of w.filter((X)=>X.status==="ready").sort((X,V)=>X.nodeKey.localeCompare(V.nodeKey))){let X=Q.get(J.nodeKey);if(X===void 0)continue;let V=s50($,X,this.#W);if(!F.impossible(V.policy.resources))continue;await this.#O(_,{...J,failure:o5(new N("incompatible",`Node ${X.key} exceeds the host resource ceiling.`)),finishedAt:this.#w().toISOString(),status:"incompatible"}),Z=!0}return Z}async#O(_,$){let F=l_.parse($),w=l_.parse({attempt:F.attempt,dependencies:F.dependencies,...F.executionPlan===void 0?{}:{executionPlan:F.executionPlan},...F.failure===void 0?{}:{failure:F.failure},...F.finishedAt===void 0?{}:{finishedAt:F.finishedAt},executor:F.executor,nodeKey:F.nodeKey,...F.output===void 0?{}:{output:F.output},...F.preparationPlan===void 0?{}:{preparationPlan:F.preparationPlan},...F.startedAt===void 0?{}:{startedAt:F.startedAt},status:F.status,version:F.version});await this.#Z.assertFence(_),await this.#Z.writeNode(_,w),await this.#Z.appendEvent(_,{details:{status:w.status},kind:"node-status",nodeKey:w.nodeKey,timestamp:this.#w().toISOString()})}async#q(_,$,F,w){let Q=await this.#Z.summary(_.runId);if(zA(Q.status))return Q;let Z=await this.#Z.nodes(_.runId),J=new Map(Z.map((H)=>[H.nodeKey,H])),X=n50(Z,F,w),V=this.#w().toISOString(),Y=X==="completed"?LS($.graph.outputs,J):void 0,j=L3.parse({counts:t50(Z),...zA(X)?{finishedAt:V}:{},graphPlanSha256:$.graphPlanSha256,...Y===void 0?{}:{outputs:Y},runId:_.runId,startedAt:F.startedAt,status:X,updatedAt:V,version:x_});return await this.#Z.writeSummary(_,j),j}async#y(_,$,F,w){let Z=(await this.#Z.nodes(_.runId)).filter((J)=>J.status==="ready"||J.status==="preparing"||J.status==="running").sort((J,X)=>J.nodeKey.localeCompare(X.nodeKey))[0];if(Z!==void 0){let J=$.graph.nodes.find((Y)=>Y.key===Z.nodeKey),X=J!==void 0&&K2(J)?ZW($,J,this.#W).discovery.policy.resume:void 0;if(Z.status==="running"&&(X==="verified-receipt"||X==="recoverable-transaction")){await this.#q(_,$,F,0);return}await this.#O(_,{...Z,failure:o5(w),finishedAt:this.#w().toISOString(),status:w.code==="incompatible"?"incompatible":"failed"})}await this.#q(_,$,F,0)}async#g(_,$,F,w){let Q=await this.#Z.nodes(_.runId);for(let Z of[...Q].sort((J,X)=>J.nodeKey.localeCompare(X.nodeKey))){if(Z.status==="approval-required")await this.#O(_,{...Z,status:"ready"});let J=Z.status==="approval-required"?await this.#Z.node(_.runId,Z.nodeKey):Z;if(J.status!=="ready"&&J.status!=="preparing"&&J.status!=="running"&&J.status!=="ambiguous-code")continue;await this.#O(_,{...J,failure:o5(new N("incompatible",w.message)),finishedAt:this.#w().toISOString(),status:"incompatible"})}await this.#C(_,$,F)}}var ES0="workflow-runs",qS0=100;async function e50(_,$,F={}){try{return await _.withLease(uV(_),async(w)=>{return await w.assertOwned(),await $(w)},{...F.signal===void 0?{}:{signal:F.signal},waitTimeoutMilliseconds:F.waitTimeoutMilliseconds??d$})}catch(w){if(!(w instanceof c1))throw w;switch(w.code){case"WAIT_ABORTED":throw new N("cancelled",w.message);case"OWNERSHIP_LOST":throw new N("conflict",w.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":case"WAIT_TIMEOUT":throw new N("unavailable",w.message,{hostResourceCode:w.code})}}}async function bS0(_){let[$,F]=await Promise.all([_.store.graphPlan(_.runId),_.store.bundle(_.runId)]);if($.runtime.externals.kind==="deny-all"&&$.runtime.externals.modules.length!==0)throw new N("incompatible","A deny-all trusted-code runtime cannot contain external modules.");let w=z40({bundle:$.bundle,bytes:F,externalModules:$.runtime.externals.modules}),Q=await uH({applicationBuild:_.currentApplicationBuild,bundle:w});if(k(Q)!==k($.runtime))throw new N("incompatible","The trusted-code runtime changed since this run was planned.",{current:Q,planned:$.runtime});let Z=Jw({bundle:$.bundle,graph:$.graph,limits:$.limits,registry:_.registry,runtime:Q,staticBindings:$.staticBindings,workflowInput:$.workflowInput});if(k(Z)!==k($))throw new N("incompatible","Persisted trusted code no longer compiles to the exact authorized graph plan.");return await pC({bundle:w,expectedBuild:{graph:$.graph,input:$.workflowInput},..._.inheritedHostResourceFileDescriptor===void 0?{}:{inheritedHostResourceFileDescriptor:_.inheritedHostResourceFileDescriptor},maximumWorkers:_.maximumWorkers,registry:_.registry,temporaryRoot:_.application.paths.privateRoot,workflowInput:$.workflowInput,workflowInputMode:"parsed"})}function __0(){return`slopcamera-cli:${String(process.pid)}:${AS()}`}function PS0(){return`run_${AS().replaceAll("-","")}`}function IS0(_){let $=new Map;for(let F of _.graph.nodes){if(!K2(F))continue;let w=F.executor.operation;$.set(`${w.kind}@${String(w.version)}`,w)}return[...$.entries()].sort(([F],[w])=>F.localeCompare(w)).map(([,F])=>F)}function fS0(_){let $=new Map;for(let F of _.graph.nodes)if(j5(F))$.set(F.executor.compute.key,F.executor.compute);return[...$.entries()].sort(([F],[w])=>F.localeCompare(w)).map(([,F])=>F)}function Lw(_){return new NS({root:RS0(_.paths.privateRoot,ES0)})}async function BS(_){let $=Lw(_.application),F=PS0(),w=await $.create({bundleBytes:new Uint8Array(_.bundleBytes),graphPlan:_.graphPlan,runId:F,runtime:{computes:fS0(_.graphPlan),operations:IS0(_.graphPlan),runtime:_.graphPlan.runtime,version:x_},sourceLocator:_.sourceLocator,workflow:{bundle:_.graphPlan.bundle,sourceLocator:_.sourceLocator,workflow:_.graphPlan.graph.workflow}});return{runId:F,store:$,summary:w}}function SS0(_){let $=new Set(["local-media","project-state"]);return _.preparation.every((F)=>$.has(F))}function yS0(_){return _.effect!=="paid-cloud"&&_.effect!=="live-control"}function gS0(){return{authorizeEffect:(_)=>Promise.resolve(yS0(_.policy)),authorizePreparation:(_)=>Promise.resolve(SS0(_.policy)),grantedBy:"slopcamera-local-cli"}}async function hS0(_,$,F,w){let Q;try{Q=await _.events($)}catch(J){if(J instanceof N&&J.code==="conflict")return F;throw J}let Z=F;for(let J of Q){if(J.sequence<=F)continue;w(J),Z=Math.max(Z,J.sequence)}return Z}async function AA(_){let $=_.store??Lw(_.application),F=_.hostResourceCoordinator??v9(),w=await e50(F,async(j)=>await dH(_.application,j.inheritedFileDescriptor<3?{}:{inheritedFileDescriptors:[j.inheritedFileDescriptor]})),Q=_.replayAmbiguousCode??[];if(_.compute!==void 0&&Q.length>0)throw new N("usage","A workflow run cannot use a fresh code worker and persisted compute replay together.");let Z=!1,J=Q.length===0?_.compute:{kind:"replay",load:async({signal:j,waitTimeoutMilliseconds:H})=>{if(Z)throw new N("conflict","The persisted trusted-code worker pool was already loaded.");Z=!0;let K=await e50(F,async(W)=>await bS0({application:_.application,currentApplicationBuild:w,inheritedHostResourceFileDescriptor:W.inheritedFileDescriptor,maximumWorkers:Y00(_.jobs,Q,F),registry:_.registry,runId:_.runId,store:$}),{signal:j,waitTimeoutMilliseconds:H});return{executor:K,release:async()=>await K.close()}},nodeKeys:Q},X=new CS({application:_.application,authorization:gS0(),currentApplicationBuild:w,...J===void 0?{}:{compute:J},hostLimits:{maxJobs:_.jobs},hostResourceCoordinator:F,jobs:_.jobs,nodePlanner:O50(_.application),owner:__0(),registry:_.registry,store:$});if(_.onEvent===void 0)return await X.run(_.runId);let V=X.run(_.runId).then((j)=>({kind:"result",result:j}),(j)=>({error:j,kind:"error"})),Y=0;while(!0){let j=await Promise.race([V,new Promise((H)=>{setTimeout(H,qS0)})]);if(Y=await hS0($,_.runId,Y,_.onEvent),j===void 0)continue;if(j.kind==="error")throw j.error;return j.result}}async function $_0(_){let $=Lw(_.application),F=__0(),w=await $.acquireClaim(_.runId,{owner:F});try{let[Q,Z]=await Promise.all([$.graphPlan(_.runId),$.node(_.runId,_.nodeKey)]);if(Z.status!=="approval-required")throw new N("conflict",`Node ${_.nodeKey} is not awaiting approval.`);let J={createdAt:new Date().toISOString(),graphPlanSha256:Q.graphPlanSha256,grantedBy:"slopcamera-local-cli",grantId:AS(),nodeKey:_.nodeKey},X;if(_.planKind==="preparation"){let V=Z.preparationPlan?.preparationPlanSha256;if(V!==_.planHash)throw new N("conflict","The preparation approval hash does not match the pending node plan.",{actual:V,requested:_.planHash});X={...J,kind:"preparation",preparationPlanSha256:_.planHash}}else{let V=Z.executionPlan?.nodePlanSha256;if(V!==_.planHash)throw new N("conflict","The effect approval hash does not match the pending node plan.",{actual:V,requested:_.planHash});X={...J,kind:"effect",nodePlanSha256:_.planHash}}return await $.appendGrant(w,X)}finally{await $.releaseClaim(w).catch(()=>{return})}}async function F_0(_){return await Lw(_.application).requestCancellation(_.runId,"slopcamera-local-cli")}async function w_0(_,$){return(await Lw(_).list()).slice(0,$)}async function Q_0(_){let $=Lw(_.application),[F,w,Q,Z]=await Promise.all([$.summary(_.runId),$.workflow(_.runId),$.nodes(_.runId),$.outputs(_.runId)]),J=_.nodes==="all"?Q:Q.filter((X)=>["ambiguous","ambiguous-code","approval-required","failed","incompatible"].includes(X.status));return{graphPlanSha256:F.graphPlanSha256,nodes:J,outputs:Z?.outputs??null,summary:F,workflow:w.workflow}}function BA(_){let $=_.summary,F=[`${$.runId} ${$.status} ${$.graphPlanSha256}`,`nodes completed=${String($.counts.completed)} failed=${String($.counts.failed)} skipped=${String($.counts.skipped)} pending=${String($.counts.pending)} cancelled=${String($.counts.cancelled)}`];if(_.pause!==void 0){let w=_.pause.phase==="effect"?"--node-plan":"--preparation-plan";F.push(`next slopcamera runs approve ${$.runId} ${_.pause.nodeKey} ${w} ${_.pause.planSha256}`,`then slopcamera runs resume ${$.runId}`)}else if($.status!=="completed"&&$.status!=="cancelled")F.push(`next slopcamera runs show ${$.runId} --nodes failed`);return F.join(`
5033
- `)}var UA="3.2.4",mS0=34359738368,lS0=34359738368;function dS0(_,$){return kS(_,{assertOwned:async()=>await $.assertOwned(),claims:$.claims,inheritedFileDescriptor:$.inheritedFileDescriptor,inheritedFileDescriptors:[$.inheritedFileDescriptor],profile:$.profile,ticket:$.ticket})}function kS(_,$){let F=_.hostResourceLease,w=F?.inheritedFileDescriptors??[],Q=$.inheritedFileDescriptors.every((Y)=>w.includes(Y)),Z=w.every((Y)=>$.inheritedFileDescriptors.includes(Y));if(F!==void 0&&(F.profile.id!==$.profile.id||F.profile.capacities.length!==$.profile.capacities.length||F.profile.capacities.some((Y)=>{return $.profile.capacities.find((H)=>H.resource===Y.resource)?.limit!==Y.limit})))throw new N("unavailable","Nested host-resource phases must use the same machine profile.");let J=[...w,...$.inheritedFileDescriptors].filter((Y,j,H)=>H.indexOf(Y)===j);if(J.length>16)throw new N("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");let X=F===void 0||Z?$:Q?F:{assertOwned:async()=>{await F.assertOwned(),await $.assertOwned()},claims:V00(F.claims,$.claims),inheritedFileDescriptor:$.inheritedFileDescriptor,inheritedFileDescriptors:J,profile:$.profile,ticket:$.ticket},V=(Y=[])=>[...Y,...X.inheritedFileDescriptors].filter((j,H,K)=>K.indexOf(j)===H);return{..._,capabilities:async(Y)=>await _.capabilities(V(Y)),capability:async(Y,j,H)=>await _.capability(Y,j,V(H)),hostResourceLease:X,runner:{run:async(Y,j={})=>{await X.assertOwned();let H=V(j.inheritedFileDescriptors);if(H.length>16)throw new N("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");return await _.runner.run(Y,{...j,inheritedFileDescriptors:H})}}}}function uS0(_){switch(_.code){case"WAIT_ABORTED":return new N("cancelled",_.message);case"OWNERSHIP_LOST":return new N("conflict",_.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":case"WAIT_TIMEOUT":return new N("unavailable",_.message,{hostResourceCode:_.code})}}async function cS0(_,$,F){let w=j00($,_.hostResourceCoordinator);await nZ(_,w,F,_.abortSignal)}async function nZ(_,$,F,w){if($.length===0)return await F(_);try{return await _.hostResourceCoordinator.withLease($,async(Q)=>{return await Q.assertOwned(),await F(dS0(_,Q))},{...w===void 0?{}:{signal:w},waitTimeoutMilliseconds:d$})}catch(Q){if(Q instanceof c1)throw uS0(Q);throw Q}}async function TS(_,$,F){let w=Y3([{amount:1,resource:"cpu"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"local-io"}],_.hostResourceCoordinator);if(_.hostResourceLease!==void 0){if(await _.hostResourceLease.assertOwned(),KI(_.hostResourceLease.claims,w))return await F(S2(_))}return await nZ(_,OI(_.hostResourceLease?.claims??[],w),async(Q)=>await F(S2(Q)),$)}function S2(_,$){let F=_.recordingController,w=(Z)=>({available:Z.available,...Z.command===void 0?{}:{command:Z.command},name:Z.name,...Z.reason===void 0?{}:{reason:Z.reason},...Z.version===void 0?{}:{version:Z.version}}),Q={capabilities:async(Z)=>(await _.capabilities(Z)).map(w),capability:async(Z)=>w(await _.capability(Z)),clock:{now:()=>new Date(_.clock()),timestampMilliseconds:_.clock},htmlOverlayRenderer:new WI({cacheRoot:R4(_.paths.privateRoot,"html-overlay-modules-v1"),fetch:_.fetch}),..._.hostResourceLease===void 0?{}:{hostResourceLease:_.hostResourceLease},machineStateRoot:_.stateRoot,paths:_.paths,...F===void 0?{}:{recordingController:{execute:async(Z,J)=>await IH(F,Z,J),status:async()=>await F.status()}},runner:_.runner};return{...Q,gatewayPort:K20({application:Q,createService:async(Z,J)=>await d_0(J===void 0?_:kS(_,J),Z),inspectMedia:async(Z,J,X)=>{let V=X===void 0?_:kS(_,X);return(await MY(V,Z.map((j)=>({data:j.data,mediaType:j.mediaType,path:j.path})),J)).map((j)=>{if(j.url!==void 0)throw new N("internal","Gateway workflow preparation unexpectedly produced a remote media input.");let H=j.facts;return{...H?.durationSeconds===void 0?{}:{durationSeconds:H.durationSeconds},...H?.height===void 0?{}:{height:H.height},...H?.width===void 0?{}:{width:H.width}}})},now:_.io.now,resolveProviderOptions:(Z,J)=>{if(J.aborted)throw new N("cancelled","Gateway provider-options resolution was cancelled.");return Promise.resolve($)}})}}function d_(_){if(_<1000)return`${_}us`;if(_<1e6)return`${(_/1000).toFixed(1).replace(/\.0$/u,"")}ms`;return`${(_/1e6).toFixed(3).replace(/0+$/u,"").replace(/\.$/u,"")}s`}function q5(_,$){let F=rF(_,$);if(!F.available||F.command===void 0)throw new N("unavailable",`${$} is unavailable${F.reason===void 0?".":`: ${F.reason}`}`,{capability:$});return F.command}async function iZ(_,$){return await Promise.all($.map(async(F)=>await _.capability(F)))}async function oZ(_,$){return q5([await _.capability($)],$)}function d0(_,$,F,w){if($)a8(_,F);else t8(_,w())}function fS(_,$){let F=IS(_,$);return F===""||!F.startsWith("..")&&!PS(F)}async function MS(_,$){let F=await a_(_.directory.path,$);if(!LL(_,F).startsWith("renders/"))throw new N("unsafe-path","Render outputs must remain under the bundle's renders/ directory so raw capture files stay immutable.");let Q=await a_(_.directory.path,"renders");await J1(Q),await J1(rZ(F));let[Z,J]=await Promise.all([UY(Q),UY(rZ(F))]);if(!fS(Z,J))throw new N("unsafe-path",`Render output crosses a symlink outside renders/: ${$}`);try{if((await Tw(F)).isSymbolicLink())throw new N("unsafe-path",`Render output may not be a symlink: ${$}`)}catch(X){if(X instanceof N)throw X;if(!(X instanceof Error&&("code"in X)&&X.code==="ENOENT"))throw X}return F}async function sS0(_,$,F){let w=await MS(_,$),Q=LL(_,w),Z=Q.toLowerCase();if(Cw(Q).toLowerCase()!==".json")throw new N("usage","A resolved render plan output must use a .json path under renders/.");if(Z.endsWith(".mp4.plan.json"))throw new N("unsafe-path",`A render plan alias may not overwrite a video receipt: ${$}`);if(/^renders\/resolved-[a-f0-9]{64}\.json$/u.test(Z)&&Q!==F)throw new N("unsafe-path",`A render plan alias may not use the canonical resolved-plan namespace: ${$}`);return{absolute:w,relative:Q}}async function US(_,$,F={}){let w=await a_(_,$),Q=IS(_,w);if(!Q.startsWith("renders/")||PS(Q))throw new N("unsafe-path","Project render artifacts must remain under the project's renders/ directory.");if(F.videoOutput){let V=Q.split("/"),Y=V.at(-1),j=new Set([".filter-graphs",".overlay-cache","derived","plans"]);if(V[0]!=="renders"||j.has(V[1]?.toLowerCase()??""))throw new N("unsafe-path",`Project video output may not use a reserved render-artifact subtree: ${$}`);if(Y===void 0||Y.toLowerCase()===".mp4"||Cw(Y).toLowerCase()!==".mp4")throw new N("usage","Project render output must be a final .mp4 file under renders/.")}let Z=R4(_,"renders");await J1(Z),await J1(rZ(w));let[J,X]=await Promise.all([UY(Z),UY(rZ(w))]);if(!fS(J,X))throw new N("unsafe-path",`Project render path crosses a symlink outside renders/: ${$}`);try{let V=await Tw(w);if(V.isSymbolicLink()||!V.isFile())throw new N("unsafe-path",`Project render leaf must be a physical regular file: ${$}`)}catch(V){if(V instanceof N)throw V;if(!(V instanceof Error&&("code"in V)&&V.code==="ENOENT"))throw V}return{absolute:w,relative:Q}}async function qA(_){return await M6(_)}function D_0(_,$,F){return{operation:$,planHash:B6(F),planId:F.planId,planPath:XF,recordingId:_.manifest.recordingId}}async function Z_0(_,$,F,w,Q){let Z=h1(F);await J1(R4(_.directory.path,"edits")),await Lj(_.fileSystem,Z,XF);let J=D_0(_,$,Z);d0(Q,w,J,()=>`${$} ${F.planId} ${String(J.planHash)}`)}function zw(_){if(_!=="linear"&&_!=="ease-in"&&_!=="ease-out"&&_!=="ease-in-out"&&_!=="spring")throw new N("usage",`Unsupported easing: ${_}`);return{kind:_}}function J_0(_,$,F,w,Q,Z){let J=_??"none";if(J==="none")return{kind:"none"};let X=O2($??F);if(J==="fade")return{durationUs:X,easing:zw(w),kind:J};if(J==="scale")return{durationUs:X,easing:zw(w),fromScale:Q,kind:J};let V=/^slide-(up|down|left|right)$/u.exec(J);if(V?.[1]==="up"||V?.[1]==="down"||V?.[1]==="left"||V?.[1]==="right")return{direction:V[1],distancePx:Z,durationUs:X,easing:zw(w),kind:"slide"};throw new N("usage",`Unsupported overlay animation: ${J}`)}function pS0(_){let $=_.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test($))return{kind:"id",value:$};if([..._].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test(_))return{kind:"unicode",value:_};return{kind:"name",value:_}}function G3(_,$,F){let w=O2(_,F),Q=O2($,F);if(Q<=w)throw new N("usage",`Time range must increase: ${_}..${$}`);return{endUs:Q,startUs:w}}function nS0(_){let $=_.length+1;while(_.some(({overlayId:F})=>F===`overlay_manual${String($).padStart(4,"0")}`))$+=1;return`overlay_manual${String($).padStart(4,"0")}`}function rS0(_){let $=_.length+1;while(_.includes(`zoom_manual${String($).padStart(4,"0")}`))$+=1;return`zoom_manual${String($).padStart(4,"0")}`}async function z_0(_,$,F,w,Q,Z){let{startUs:J,endUs:X}=G3(w.from,w.to,Q),V=Z?.({endUs:X,startUs:J})??X-J;if(V<=0)throw new N("conflict","Overlay range has no visible kept output time.");let Y=w.overlayKind==="emoji"?await mX(_.paths.repositoryRoot,w.source,w.variant,w.provider):void 0,j=w.overlayKind==="emoji"?await VG($,Y):await XG($,w.source,w.overlayKind),{created:H,...K}=j,W=async()=>{let O=F.some((L)=>L.source.asset.path===K.path);if(H&&!O)await kY(R4($,K.path),{force:!0})};try{let O=await a_($,K.path),L=K.mediaType==="image/svg+xml"?{...await CF(O),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await L9(await oZ(_,"ffprobe"),_.runner,O),G={height:"pixelHeight"in L?L.pixelHeight:L.height,width:"pixelWidth"in L?L.pixelWidth:L.width},D;if(w.overlayKind==="image"||w.overlayKind==="svg")D={asset:K,kind:w.overlayKind};else if(w.overlayKind==="emoji")D={asset:K,kind:"emoji",provider:Y.provider,selector:pS0(w.source)};else{if(w.loop&&w.freezeEnd)throw new N("usage","Use only one of --loop and --freeze-end.");let C=O2(w.sourceIn??"0us",Q),A=w.sourceOut===void 0?void 0:O2(w.sourceOut,Q);if(L.durationUs===null||L.durationUs<=0)throw new N("invalid-data","Animated overlay media must report a positive finite duration.");if(w.overlayKind==="video"&&w.animatedAudio!=="mute"&&!L.hasAudio)throw new N("conflict",`Video overlay audio policy ${w.animatedAudio} requires an audio stream in the source media.`);let B=lX({mediaDurationUs:L.durationUs,outputDurationUs:V,playbackRate:w.playbackRate,sourceInUs:C,sourceOutUs:A}),T={audioEndUs:L.audioEndUs,audioStartUs:L.audioStartUs,audioStreamIndex:L.audioStreamIndex,endBehavior:w.loop?"loop":w.freezeEnd?"freeze-end":"hide",playbackRate:w.playbackRate,streamStartUs:L.videoStartUs,videoStreamIndex:L.videoStreamIndex,...B};if(w.overlayKind==="gif")D={asset:K,audioPolicy:{kind:"mute"},kind:"gif",playback:T};else{let M=w.animatedAudio==="mute"?{kind:"mute"}:w.animatedAudio==="mix"?{kind:"mix",volume:w.audioVolume}:{duckPrimaryTo:w.duckPrimaryTo,kind:"duck-primary",volume:w.audioVolume};D={asset:K,audioPolicy:M,kind:"video",playback:T}}}if(w.width===void 0!==(w.height===void 0))throw new N("usage","Overlay pixel size requires both --width and --height.");let z=a2.safeParse({anchor:w.anchor,blendMode:w.blendMode,coordinateSpace:"output-pixels",crop:w.crop===void 0?{kind:"none"}:{bottom:w.crop[3],kind:"normalized-insets",left:w.crop[0],right:w.crop[2],top:w.crop[1]},entrance:J_0(w.entrance,w.entranceDuration,"250ms",w.easing,w.entranceFromScale,w.slideDistance),exit:J_0(w.exit,w.exitDuration,"250ms",w.easing,w.exitToScale,w.slideDistance),fit:w.fit,intrinsicSize:G,mask:w.cornerRadius===void 0?{kind:"none"}:{kind:"rounded-rectangle",radiusPx:w.cornerRadius},motion:w.motionKeyframes.length===0?{kind:"none"}:{keyframes:w.motionKeyframes.map((C)=>({easing:zw(w.easing),offset:C.offset,opacityMultiplier:C.opacity,positionOffset:{x:C.position[0],y:C.position[1]},rotationOffsetDegrees:C.rotation,scaleMultiplier:C.scale})),kind:"keyframes",timeline:"visible-output"},opacity:w.opacity,overlayId:nS0(F),position:{x:w.position[0],y:w.position[1]},range:{endUs:X,startUs:J},rotationDegrees:w.rotation,scale:w.scale,size:w.width===void 0||w.height===void 0?{kind:"intrinsic"}:{height:w.height,kind:"pixels",width:w.width},source:D,zIndex:w.zIndex});if(!z.success)throw new N("usage",`Invalid overlay: ${z.error.issues[0]?.message??"unknown error"}`);return{operation:z.data,rollback:W}}catch(O){throw await W(),O}}function oS0(_,$,F,w){let Q=C_0(_,$,void 0,w),Z=Q.displayId??F.sources.displays.find(({isPrimary:J})=>J)?.displayId;if(Z===void 0)throw new N("not-found","Manual zoom requires a selected or primary display.");return e9.parse({...Q,displayId:Z,kind:"manual"})}function C_0(_,$,F,w){let{startUs:Q,endUs:Z}=G3(_.from,_.to,w),J=_.target==="rect"?{kind:"rect",rect:{height:_.rect[3],width:_.rect[2],x:_.rect[0],y:_.rect[1]}}:_.target==="point"?{kind:"point",point:{x:_.point[0],y:_.point[1]}}:_.target==="cursor"?{kind:"cursor",sampling:"interpolated"}:_.target==="focused-input"?{kind:"focused-input",paddingPx:24}:_.window==="frontmost"?{kind:"window",paddingPx:24,selector:{kind:"frontmost"}}:_.window.startsWith("bundle:")?{kind:"window",paddingPx:24,selector:{applicationBundleId:_.window.slice(7),kind:"application"}}:{kind:"window",paddingPx:24,selector:{kind:"window-id",windowId:_.window}},X=Z-Q,V=Math.min(300000,Math.max(0,Math.floor(X/2))),Y=_.enterDuration===void 0?V:O2(_.enterDuration,w),j=_.exitDuration===void 0?V:O2(_.exitDuration,w),H=WM.safeParse({..._.display===void 0?{}:{displayId:_.display},easing:zw(_.easing),enterDurationUs:Y,exitDurationUs:j,...F===void 0?{}:{placementId:F},range:{endUs:Z,startUs:Q},scale:_.scale,target:J,zoomId:rS0($)});if(!H.success)throw new N("usage",`Invalid zoom: ${H.error.issues[0]?.message??"unknown error"}`);return H.data}async function iS0(_,$){let F=await g4(_.paths.artifactRoot,$.recording);if(F.manifest.state!=="stopped")throw new N("conflict","Editing requires a stopped recording with an immutable timeline, media, and events.");if($.edit.operation==="init"){let X=await JM(F),V=X??Vm(F.manifest,Pd(F.manifest),_.io.now().toISOString());await Z_0(F,X===null?"init":"init-existing",V,$.json,_.io);return}let w=await KN(F);if($.edit.operation==="show"){d0(_.io,$.json,w,()=>`${w.planId} ${B6(w)} keep=${w.keep.length} speed=${w.speed.length} zooms=${w.zooms.length} overlays=${w.overlays.length}`);return}let Q=_.io.now().toISOString(),Z,J=$.edit;switch(J.operation){case"trim":Z=Ym(w,G3(J.from,J.to,$.fps),Q);break;case"cut":Z=IO(w,G3(J.from,J.to,$.fps),Q);break;case"speed":Z=jk(w,G3(J.from,J.to,$.fps),J.rate,Q);break;case"zoom-add":Z=jm(w,oS0(J,w.zooms.map((X)=>X.zoomId),F.manifest,$.fps),Q);break;case"zoom-remove":Z=Nm(w,J.id,Q);break;case"overlay-add":{let X=await z_0(_,F.directory.path,w.overlays,J,$.fps,(Y)=>jQ(pO(w),Y).reduce((j,H)=>j+H.output.endUs-H.output.startUs,0));try{Z=h1(Hm(w,X.operation,Q)),await J1(R4(F.directory.path,"edits")),await Lj(F.fileSystem,Z,XF)}catch(Y){throw await X.rollback(),Y}let V=D_0(F,J.operation,Z);d0(_.io,$.json,V,()=>`${J.operation} ${Z.planId} ${String(V.planHash)}`);return}case"overlay-remove":Z=Wm(w,J.id,Q);break;case"cursor":Z=n3({...w,effects:{...w.effects,...J.clickHighlight===void 0?{}:{clicks:J.clickHighlight?{color:"#ffcc00cc",durationUs:350000,enabled:!0,radiusPx:28,style:"pulse"}:{enabled:!1}},cursor:J.enabled?{enabled:!0,scale:1,smoothing:{algorithm:"exponential",strength:J.smoothing??0.7},style:"captured"}:{enabled:!1}},updatedAt:Q});break;case"clicks":Z=n3({...w,effects:{...w.effects,clicks:J.enabled?{color:J.color,durationUs:O2(J.duration,$.fps),enabled:!0,radiusPx:J.radius,style:J.style}:{enabled:!1}},updatedAt:Q});break;case"keystrokes":Z=n3({...w,effects:{...w.effects,keystrokes:J.enabled?{enabled:!0,holdUs:O2(J.stopAfter??"1200ms",$.fps),maxKeys:8,position:"bottom-right",secureText:"hide"}:{enabled:!1}},updatedAt:Q});break;case"typed-text":if(J.enabled&&F.manifest.capture.typedText!=="enabled")throw new N("conflict","Typed-text rendering cannot be enabled because typed-text capture was disabled for this recording.");Z=n3({...w,effects:{...w.effects,typedText:J.enabled?{enabled:!0,idleTimeoutUs:O2(J.idleTimeout,$.fps),maxCharacters:J.maxCharacters,placement:J.placement,secureText:"hide"}:{enabled:!1}},updatedAt:Q});break}await Z_0(F,J.operation,Z,$.json,_.io)}async function A_0(_,$,F){if($.manifest.state!=="stopped")throw new N("conflict","Inactivity analysis requires a stopped recording with immutable media and events.");let w=await iZ(_,["ffmpeg","ffprobe"]),Q=q5(w,"ffmpeg"),Z=q5(w,"ffprobe"),J=new ON({ffmpeg:Q,ffprobe:Z,runner:_.runner}),X=$.manifest.tracks.filter((L)=>L.enabled&&L.kind==="display-video");if(X.length===0)throw new N("invalid-data","Recording has no enabled display tracks to analyze.");let V=await e3(X,4,async(L)=>{let G=[];for(let D of L.segments){if(D.integrity.state!=="verified"||D.integrity.bytes<=0)throw new N("invalid-data",`Inactivity media ${D.path} does not have verified integrity.`);let z=await f1({expected:D.integrity,label:`Inactivity media ${D.path}:${D.streamIndex}`,path:D.path,repositoryRoot:$.directory.path}),C=await J.freeze(z,D.streamIndex,F.minDurationUs,F.motionThreshold,D.startUs);G.push(...C.filter(({startUs:A,endUs:B})=>A<D.endUs&&B>D.startUs).map(({startUs:A,endUs:B})=>({confidence:1,meanFrameDifference:F.motionThreshold,range:{startUs:Math.max(A,D.startUs),endUs:Math.min(B,D.endUs)}})))}return{intervals:G,trackId:L.trackId}}),Y=F.protectAudio?$.manifest.tracks.filter((L)=>L.enabled&&(L.kind==="system-audio"||L.kind==="microphone-audio")):[],j=await e3(Y,4,async(L)=>{let G=[];for(let D of L.segments){if(D.integrity.state!=="verified"||D.integrity.bytes<=0)throw new N("invalid-data",`Inactivity media ${D.path} does not have verified integrity.`);let z=await f1({expected:D.integrity,label:`Inactivity media ${D.path}:${D.streamIndex}`,path:D.path,repositoryRoot:$.directory.path}),C=await J.silence(z,D.streamIndex,F.minDurationUs,D.startUs);G.push(...C.filter(({startUs:A,endUs:B})=>A<D.endUs&&B>D.startUs).map(({startUs:A,endUs:B})=>({peakDb:-45,range:{startUs:Math.max(A,D.startUs),endUs:Math.min(B,D.endUs)}})))}return{intervals:G,trackId:L.trackId}}),H=rF(w,"ffmpeg").version??"unknown",K=tW.parse({audio:j,displays:V,kind:"slopcamera.analyzer-evidence",schemaVersion:1,sourceDurationUs:$.manifest.timeline.durationUs,tool:{name:"ffmpeg-freezedetect-silencedetect",version:H.slice(0,128)}});await J1(R4($.directory.path,"analysis")),await $.fileSystem.writeTextAtomic("analysis/inactivity-v1.json",`${k(K)}
5033
+ `)}var UA="3.2.5",mS0=34359738368,lS0=34359738368;function dS0(_,$){return kS(_,{assertOwned:async()=>await $.assertOwned(),claims:$.claims,inheritedFileDescriptor:$.inheritedFileDescriptor,inheritedFileDescriptors:[$.inheritedFileDescriptor],profile:$.profile,ticket:$.ticket})}function kS(_,$){let F=_.hostResourceLease,w=F?.inheritedFileDescriptors??[],Q=$.inheritedFileDescriptors.every((Y)=>w.includes(Y)),Z=w.every((Y)=>$.inheritedFileDescriptors.includes(Y));if(F!==void 0&&(F.profile.id!==$.profile.id||F.profile.capacities.length!==$.profile.capacities.length||F.profile.capacities.some((Y)=>{return $.profile.capacities.find((H)=>H.resource===Y.resource)?.limit!==Y.limit})))throw new N("unavailable","Nested host-resource phases must use the same machine profile.");let J=[...w,...$.inheritedFileDescriptors].filter((Y,j,H)=>H.indexOf(Y)===j);if(J.length>16)throw new N("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");let X=F===void 0||Z?$:Q?F:{assertOwned:async()=>{await F.assertOwned(),await $.assertOwned()},claims:V00(F.claims,$.claims),inheritedFileDescriptor:$.inheritedFileDescriptor,inheritedFileDescriptors:J,profile:$.profile,ticket:$.ticket},V=(Y=[])=>[...Y,...X.inheritedFileDescriptors].filter((j,H,K)=>K.indexOf(j)===H);return{..._,capabilities:async(Y)=>await _.capabilities(V(Y)),capability:async(Y,j,H)=>await _.capability(Y,j,V(H)),hostResourceLease:X,runner:{run:async(Y,j={})=>{await X.assertOwned();let H=V(j.inheritedFileDescriptors);if(H.length>16)throw new N("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");return await _.runner.run(Y,{...j,inheritedFileDescriptors:H})}}}}function uS0(_){switch(_.code){case"WAIT_ABORTED":return new N("cancelled",_.message);case"OWNERSHIP_LOST":return new N("conflict",_.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":case"WAIT_TIMEOUT":return new N("unavailable",_.message,{hostResourceCode:_.code})}}async function cS0(_,$,F){let w=j00($,_.hostResourceCoordinator);await nZ(_,w,F,_.abortSignal)}async function nZ(_,$,F,w){if($.length===0)return await F(_);try{return await _.hostResourceCoordinator.withLease($,async(Q)=>{return await Q.assertOwned(),await F(dS0(_,Q))},{...w===void 0?{}:{signal:w},waitTimeoutMilliseconds:d$})}catch(Q){if(Q instanceof c1)throw uS0(Q);throw Q}}async function TS(_,$,F){let w=Y3([{amount:1,resource:"cpu"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"local-io"}],_.hostResourceCoordinator);if(_.hostResourceLease!==void 0){if(await _.hostResourceLease.assertOwned(),KI(_.hostResourceLease.claims,w))return await F(S2(_))}return await nZ(_,OI(_.hostResourceLease?.claims??[],w),async(Q)=>await F(S2(Q)),$)}function S2(_,$){let F=_.recordingController,w=(Z)=>({available:Z.available,...Z.command===void 0?{}:{command:Z.command},name:Z.name,...Z.reason===void 0?{}:{reason:Z.reason},...Z.version===void 0?{}:{version:Z.version}}),Q={capabilities:async(Z)=>(await _.capabilities(Z)).map(w),capability:async(Z)=>w(await _.capability(Z)),clock:{now:()=>new Date(_.clock()),timestampMilliseconds:_.clock},htmlOverlayRenderer:new WI({cacheRoot:R4(_.paths.privateRoot,"html-overlay-modules-v1"),fetch:_.fetch}),..._.hostResourceLease===void 0?{}:{hostResourceLease:_.hostResourceLease},machineStateRoot:_.stateRoot,paths:_.paths,...F===void 0?{}:{recordingController:{execute:async(Z,J)=>await IH(F,Z,J),status:async()=>await F.status()}},runner:_.runner};return{...Q,gatewayPort:K20({application:Q,createService:async(Z,J)=>await d_0(J===void 0?_:kS(_,J),Z),inspectMedia:async(Z,J,X)=>{let V=X===void 0?_:kS(_,X);return(await MY(V,Z.map((j)=>({data:j.data,mediaType:j.mediaType,path:j.path})),J)).map((j)=>{if(j.url!==void 0)throw new N("internal","Gateway workflow preparation unexpectedly produced a remote media input.");let H=j.facts;return{...H?.durationSeconds===void 0?{}:{durationSeconds:H.durationSeconds},...H?.height===void 0?{}:{height:H.height},...H?.width===void 0?{}:{width:H.width}}})},now:_.io.now,resolveProviderOptions:(Z,J)=>{if(J.aborted)throw new N("cancelled","Gateway provider-options resolution was cancelled.");return Promise.resolve($)}})}}function d_(_){if(_<1000)return`${_}us`;if(_<1e6)return`${(_/1000).toFixed(1).replace(/\.0$/u,"")}ms`;return`${(_/1e6).toFixed(3).replace(/0+$/u,"").replace(/\.$/u,"")}s`}function q5(_,$){let F=rF(_,$);if(!F.available||F.command===void 0)throw new N("unavailable",`${$} is unavailable${F.reason===void 0?".":`: ${F.reason}`}`,{capability:$});return F.command}async function iZ(_,$){return await Promise.all($.map(async(F)=>await _.capability(F)))}async function oZ(_,$){return q5([await _.capability($)],$)}function d0(_,$,F,w){if($)a8(_,F);else t8(_,w())}function fS(_,$){let F=IS(_,$);return F===""||!F.startsWith("..")&&!PS(F)}async function MS(_,$){let F=await a_(_.directory.path,$);if(!LL(_,F).startsWith("renders/"))throw new N("unsafe-path","Render outputs must remain under the bundle's renders/ directory so raw capture files stay immutable.");let Q=await a_(_.directory.path,"renders");await J1(Q),await J1(rZ(F));let[Z,J]=await Promise.all([UY(Q),UY(rZ(F))]);if(!fS(Z,J))throw new N("unsafe-path",`Render output crosses a symlink outside renders/: ${$}`);try{if((await Tw(F)).isSymbolicLink())throw new N("unsafe-path",`Render output may not be a symlink: ${$}`)}catch(X){if(X instanceof N)throw X;if(!(X instanceof Error&&("code"in X)&&X.code==="ENOENT"))throw X}return F}async function sS0(_,$,F){let w=await MS(_,$),Q=LL(_,w),Z=Q.toLowerCase();if(Cw(Q).toLowerCase()!==".json")throw new N("usage","A resolved render plan output must use a .json path under renders/.");if(Z.endsWith(".mp4.plan.json"))throw new N("unsafe-path",`A render plan alias may not overwrite a video receipt: ${$}`);if(/^renders\/resolved-[a-f0-9]{64}\.json$/u.test(Z)&&Q!==F)throw new N("unsafe-path",`A render plan alias may not use the canonical resolved-plan namespace: ${$}`);return{absolute:w,relative:Q}}async function US(_,$,F={}){let w=await a_(_,$),Q=IS(_,w);if(!Q.startsWith("renders/")||PS(Q))throw new N("unsafe-path","Project render artifacts must remain under the project's renders/ directory.");if(F.videoOutput){let V=Q.split("/"),Y=V.at(-1),j=new Set([".filter-graphs",".overlay-cache","derived","plans"]);if(V[0]!=="renders"||j.has(V[1]?.toLowerCase()??""))throw new N("unsafe-path",`Project video output may not use a reserved render-artifact subtree: ${$}`);if(Y===void 0||Y.toLowerCase()===".mp4"||Cw(Y).toLowerCase()!==".mp4")throw new N("usage","Project render output must be a final .mp4 file under renders/.")}let Z=R4(_,"renders");await J1(Z),await J1(rZ(w));let[J,X]=await Promise.all([UY(Z),UY(rZ(w))]);if(!fS(J,X))throw new N("unsafe-path",`Project render path crosses a symlink outside renders/: ${$}`);try{let V=await Tw(w);if(V.isSymbolicLink()||!V.isFile())throw new N("unsafe-path",`Project render leaf must be a physical regular file: ${$}`)}catch(V){if(V instanceof N)throw V;if(!(V instanceof Error&&("code"in V)&&V.code==="ENOENT"))throw V}return{absolute:w,relative:Q}}async function qA(_){return await M6(_)}function D_0(_,$,F){return{operation:$,planHash:B6(F),planId:F.planId,planPath:XF,recordingId:_.manifest.recordingId}}async function Z_0(_,$,F,w,Q){let Z=h1(F);await J1(R4(_.directory.path,"edits")),await Lj(_.fileSystem,Z,XF);let J=D_0(_,$,Z);d0(Q,w,J,()=>`${$} ${F.planId} ${String(J.planHash)}`)}function zw(_){if(_!=="linear"&&_!=="ease-in"&&_!=="ease-out"&&_!=="ease-in-out"&&_!=="spring")throw new N("usage",`Unsupported easing: ${_}`);return{kind:_}}function J_0(_,$,F,w,Q,Z){let J=_??"none";if(J==="none")return{kind:"none"};let X=O2($??F);if(J==="fade")return{durationUs:X,easing:zw(w),kind:J};if(J==="scale")return{durationUs:X,easing:zw(w),fromScale:Q,kind:J};let V=/^slide-(up|down|left|right)$/u.exec(J);if(V?.[1]==="up"||V?.[1]==="down"||V?.[1]==="left"||V?.[1]==="right")return{direction:V[1],distancePx:Z,durationUs:X,easing:zw(w),kind:"slide"};throw new N("usage",`Unsupported overlay animation: ${J}`)}function pS0(_){let $=_.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test($))return{kind:"id",value:$};if([..._].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test(_))return{kind:"unicode",value:_};return{kind:"name",value:_}}function G3(_,$,F){let w=O2(_,F),Q=O2($,F);if(Q<=w)throw new N("usage",`Time range must increase: ${_}..${$}`);return{endUs:Q,startUs:w}}function nS0(_){let $=_.length+1;while(_.some(({overlayId:F})=>F===`overlay_manual${String($).padStart(4,"0")}`))$+=1;return`overlay_manual${String($).padStart(4,"0")}`}function rS0(_){let $=_.length+1;while(_.includes(`zoom_manual${String($).padStart(4,"0")}`))$+=1;return`zoom_manual${String($).padStart(4,"0")}`}async function z_0(_,$,F,w,Q,Z){let{startUs:J,endUs:X}=G3(w.from,w.to,Q),V=Z?.({endUs:X,startUs:J})??X-J;if(V<=0)throw new N("conflict","Overlay range has no visible kept output time.");let Y=w.overlayKind==="emoji"?await mX(_.paths.repositoryRoot,w.source,w.variant,w.provider):void 0,j=w.overlayKind==="emoji"?await VG($,Y):await XG($,w.source,w.overlayKind),{created:H,...K}=j,W=async()=>{let O=F.some((L)=>L.source.asset.path===K.path);if(H&&!O)await kY(R4($,K.path),{force:!0})};try{let O=await a_($,K.path),L=K.mediaType==="image/svg+xml"?{...await CF(O),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await L9(await oZ(_,"ffprobe"),_.runner,O),G={height:"pixelHeight"in L?L.pixelHeight:L.height,width:"pixelWidth"in L?L.pixelWidth:L.width},D;if(w.overlayKind==="image"||w.overlayKind==="svg")D={asset:K,kind:w.overlayKind};else if(w.overlayKind==="emoji")D={asset:K,kind:"emoji",provider:Y.provider,selector:pS0(w.source)};else{if(w.loop&&w.freezeEnd)throw new N("usage","Use only one of --loop and --freeze-end.");let C=O2(w.sourceIn??"0us",Q),A=w.sourceOut===void 0?void 0:O2(w.sourceOut,Q);if(L.durationUs===null||L.durationUs<=0)throw new N("invalid-data","Animated overlay media must report a positive finite duration.");if(w.overlayKind==="video"&&w.animatedAudio!=="mute"&&!L.hasAudio)throw new N("conflict",`Video overlay audio policy ${w.animatedAudio} requires an audio stream in the source media.`);let B=lX({mediaDurationUs:L.durationUs,outputDurationUs:V,playbackRate:w.playbackRate,sourceInUs:C,sourceOutUs:A}),T={audioEndUs:L.audioEndUs,audioStartUs:L.audioStartUs,audioStreamIndex:L.audioStreamIndex,endBehavior:w.loop?"loop":w.freezeEnd?"freeze-end":"hide",playbackRate:w.playbackRate,streamStartUs:L.videoStartUs,videoStreamIndex:L.videoStreamIndex,...B};if(w.overlayKind==="gif")D={asset:K,audioPolicy:{kind:"mute"},kind:"gif",playback:T};else{let M=w.animatedAudio==="mute"?{kind:"mute"}:w.animatedAudio==="mix"?{kind:"mix",volume:w.audioVolume}:{duckPrimaryTo:w.duckPrimaryTo,kind:"duck-primary",volume:w.audioVolume};D={asset:K,audioPolicy:M,kind:"video",playback:T}}}if(w.width===void 0!==(w.height===void 0))throw new N("usage","Overlay pixel size requires both --width and --height.");let z=a2.safeParse({anchor:w.anchor,blendMode:w.blendMode,coordinateSpace:"output-pixels",crop:w.crop===void 0?{kind:"none"}:{bottom:w.crop[3],kind:"normalized-insets",left:w.crop[0],right:w.crop[2],top:w.crop[1]},entrance:J_0(w.entrance,w.entranceDuration,"250ms",w.easing,w.entranceFromScale,w.slideDistance),exit:J_0(w.exit,w.exitDuration,"250ms",w.easing,w.exitToScale,w.slideDistance),fit:w.fit,intrinsicSize:G,mask:w.cornerRadius===void 0?{kind:"none"}:{kind:"rounded-rectangle",radiusPx:w.cornerRadius},motion:w.motionKeyframes.length===0?{kind:"none"}:{keyframes:w.motionKeyframes.map((C)=>({easing:zw(w.easing),offset:C.offset,opacityMultiplier:C.opacity,positionOffset:{x:C.position[0],y:C.position[1]},rotationOffsetDegrees:C.rotation,scaleMultiplier:C.scale})),kind:"keyframes",timeline:"visible-output"},opacity:w.opacity,overlayId:nS0(F),position:{x:w.position[0],y:w.position[1]},range:{endUs:X,startUs:J},rotationDegrees:w.rotation,scale:w.scale,size:w.width===void 0||w.height===void 0?{kind:"intrinsic"}:{height:w.height,kind:"pixels",width:w.width},source:D,zIndex:w.zIndex});if(!z.success)throw new N("usage",`Invalid overlay: ${z.error.issues[0]?.message??"unknown error"}`);return{operation:z.data,rollback:W}}catch(O){throw await W(),O}}function oS0(_,$,F,w){let Q=C_0(_,$,void 0,w),Z=Q.displayId??F.sources.displays.find(({isPrimary:J})=>J)?.displayId;if(Z===void 0)throw new N("not-found","Manual zoom requires a selected or primary display.");return e9.parse({...Q,displayId:Z,kind:"manual"})}function C_0(_,$,F,w){let{startUs:Q,endUs:Z}=G3(_.from,_.to,w),J=_.target==="rect"?{kind:"rect",rect:{height:_.rect[3],width:_.rect[2],x:_.rect[0],y:_.rect[1]}}:_.target==="point"?{kind:"point",point:{x:_.point[0],y:_.point[1]}}:_.target==="cursor"?{kind:"cursor",sampling:"interpolated"}:_.target==="focused-input"?{kind:"focused-input",paddingPx:24}:_.window==="frontmost"?{kind:"window",paddingPx:24,selector:{kind:"frontmost"}}:_.window.startsWith("bundle:")?{kind:"window",paddingPx:24,selector:{applicationBundleId:_.window.slice(7),kind:"application"}}:{kind:"window",paddingPx:24,selector:{kind:"window-id",windowId:_.window}},X=Z-Q,V=Math.min(300000,Math.max(0,Math.floor(X/2))),Y=_.enterDuration===void 0?V:O2(_.enterDuration,w),j=_.exitDuration===void 0?V:O2(_.exitDuration,w),H=WM.safeParse({..._.display===void 0?{}:{displayId:_.display},easing:zw(_.easing),enterDurationUs:Y,exitDurationUs:j,...F===void 0?{}:{placementId:F},range:{endUs:Z,startUs:Q},scale:_.scale,target:J,zoomId:rS0($)});if(!H.success)throw new N("usage",`Invalid zoom: ${H.error.issues[0]?.message??"unknown error"}`);return H.data}async function iS0(_,$){let F=await g4(_.paths.artifactRoot,$.recording);if(F.manifest.state!=="stopped")throw new N("conflict","Editing requires a stopped recording with an immutable timeline, media, and events.");if($.edit.operation==="init"){let X=await JM(F),V=X??Vm(F.manifest,Pd(F.manifest),_.io.now().toISOString());await Z_0(F,X===null?"init":"init-existing",V,$.json,_.io);return}let w=await KN(F);if($.edit.operation==="show"){d0(_.io,$.json,w,()=>`${w.planId} ${B6(w)} keep=${w.keep.length} speed=${w.speed.length} zooms=${w.zooms.length} overlays=${w.overlays.length}`);return}let Q=_.io.now().toISOString(),Z,J=$.edit;switch(J.operation){case"trim":Z=Ym(w,G3(J.from,J.to,$.fps),Q);break;case"cut":Z=IO(w,G3(J.from,J.to,$.fps),Q);break;case"speed":Z=jk(w,G3(J.from,J.to,$.fps),J.rate,Q);break;case"zoom-add":Z=jm(w,oS0(J,w.zooms.map((X)=>X.zoomId),F.manifest,$.fps),Q);break;case"zoom-remove":Z=Nm(w,J.id,Q);break;case"overlay-add":{let X=await z_0(_,F.directory.path,w.overlays,J,$.fps,(Y)=>jQ(pO(w),Y).reduce((j,H)=>j+H.output.endUs-H.output.startUs,0));try{Z=h1(Hm(w,X.operation,Q)),await J1(R4(F.directory.path,"edits")),await Lj(F.fileSystem,Z,XF)}catch(Y){throw await X.rollback(),Y}let V=D_0(F,J.operation,Z);d0(_.io,$.json,V,()=>`${J.operation} ${Z.planId} ${String(V.planHash)}`);return}case"overlay-remove":Z=Wm(w,J.id,Q);break;case"cursor":Z=n3({...w,effects:{...w.effects,...J.clickHighlight===void 0?{}:{clicks:J.clickHighlight?{color:"#ffcc00cc",durationUs:350000,enabled:!0,radiusPx:28,style:"pulse"}:{enabled:!1}},cursor:J.enabled?{enabled:!0,scale:1,smoothing:{algorithm:"exponential",strength:J.smoothing??0.7},style:"captured"}:{enabled:!1}},updatedAt:Q});break;case"clicks":Z=n3({...w,effects:{...w.effects,clicks:J.enabled?{color:J.color,durationUs:O2(J.duration,$.fps),enabled:!0,radiusPx:J.radius,style:J.style}:{enabled:!1}},updatedAt:Q});break;case"keystrokes":Z=n3({...w,effects:{...w.effects,keystrokes:J.enabled?{enabled:!0,holdUs:O2(J.stopAfter??"1200ms",$.fps),maxKeys:8,position:"bottom-right",secureText:"hide"}:{enabled:!1}},updatedAt:Q});break;case"typed-text":if(J.enabled&&F.manifest.capture.typedText!=="enabled")throw new N("conflict","Typed-text rendering cannot be enabled because typed-text capture was disabled for this recording.");Z=n3({...w,effects:{...w.effects,typedText:J.enabled?{enabled:!0,idleTimeoutUs:O2(J.idleTimeout,$.fps),maxCharacters:J.maxCharacters,placement:J.placement,secureText:"hide"}:{enabled:!1}},updatedAt:Q});break}await Z_0(F,J.operation,Z,$.json,_.io)}async function A_0(_,$,F){if($.manifest.state!=="stopped")throw new N("conflict","Inactivity analysis requires a stopped recording with immutable media and events.");let w=await iZ(_,["ffmpeg","ffprobe"]),Q=q5(w,"ffmpeg"),Z=q5(w,"ffprobe"),J=new ON({ffmpeg:Q,ffprobe:Z,runner:_.runner}),X=$.manifest.tracks.filter((L)=>L.enabled&&L.kind==="display-video");if(X.length===0)throw new N("invalid-data","Recording has no enabled display tracks to analyze.");let V=await e3(X,4,async(L)=>{let G=[];for(let D of L.segments){if(D.integrity.state!=="verified"||D.integrity.bytes<=0)throw new N("invalid-data",`Inactivity media ${D.path} does not have verified integrity.`);let z=await f1({expected:D.integrity,label:`Inactivity media ${D.path}:${D.streamIndex}`,path:D.path,repositoryRoot:$.directory.path}),C=await J.freeze(z,D.streamIndex,F.minDurationUs,F.motionThreshold,D.startUs);G.push(...C.filter(({startUs:A,endUs:B})=>A<D.endUs&&B>D.startUs).map(({startUs:A,endUs:B})=>({confidence:1,meanFrameDifference:F.motionThreshold,range:{startUs:Math.max(A,D.startUs),endUs:Math.min(B,D.endUs)}})))}return{intervals:G,trackId:L.trackId}}),Y=F.protectAudio?$.manifest.tracks.filter((L)=>L.enabled&&(L.kind==="system-audio"||L.kind==="microphone-audio")):[],j=await e3(Y,4,async(L)=>{let G=[];for(let D of L.segments){if(D.integrity.state!=="verified"||D.integrity.bytes<=0)throw new N("invalid-data",`Inactivity media ${D.path} does not have verified integrity.`);let z=await f1({expected:D.integrity,label:`Inactivity media ${D.path}:${D.streamIndex}`,path:D.path,repositoryRoot:$.directory.path}),C=await J.silence(z,D.streamIndex,F.minDurationUs,D.startUs);G.push(...C.filter(({startUs:A,endUs:B})=>A<D.endUs&&B>D.startUs).map(({startUs:A,endUs:B})=>({peakDb:-45,range:{startUs:Math.max(A,D.startUs),endUs:Math.min(B,D.endUs)}})))}return{intervals:G,trackId:L.trackId}}),H=rF(w,"ffmpeg").version??"unknown",K=tW.parse({audio:j,displays:V,kind:"slopcamera.analyzer-evidence",schemaVersion:1,sourceDurationUs:$.manifest.timeline.durationUs,tool:{name:"ffmpeg-freezedetect-silencedetect",version:H.slice(0,128)}});await J1(R4($.directory.path,"analysis")),await $.fileSystem.writeTextAtomic("analysis/inactivity-v1.json",`${k(K)}
5034
5034
  `);let W=await qA($),O=wm(K,W,{edgeHandleUs:250000,interactionHandleUs:750000,minimumCutUs:F.minDurationUs,cursorMovementThresholdPx:2,requireAudioSilence:F.protectAudio});return{evidence:K,result:O}}async function aS0(_,$){let F=await g4(_.paths.artifactRoot,$.recording);if(F.manifest.state!=="stopped")throw new N("conflict","Inactivity analysis requires a stopped recording with immutable media and events.");let w=await KN(F),Q=await A_0(_,F,{minDurationUs:O2($.minDuration),motionThreshold:$.motionThreshold,protectAudio:$.protectAudio}),Z=w;if($.apply&&$.handle!=="keep"){for(let X of Q.result.cuts)Z=$.handle==="cut"?IO(Z,X,_.io.now().toISOString()):jk(Z,X,$.speedRate,_.io.now().toISOString());Z=h1(Z),await J1(R4(F.directory.path,"edits")),await Lj(F.fileSystem,Z,XF)}let J={applied:$.apply&&$.handle!=="keep",candidateCount:Q.result.candidateCount,cuts:Q.result.cuts,evidencePath:"analysis/inactivity-v1.json",handle:$.handle,planHash:B6(Z),protectedInteractionCount:Q.result.protectedInteractionCount,recordingId:F.manifest.recordingId};d0(_.io,$.json,J,()=>`${J.cuts.length} inactivity range(s), ${J.applied?"applied":"dry-run"}; plan ${J.planHash}`)}async function tS0(_,$){let F=await x2(_.paths.projectRoot,$.recording);if($.apply&&$.handle!=="keep")T_0(F.project,"Automated project inactivity edits");let w=await iZ(_,["ffmpeg","ffprobe"]),Q=q5(w,"ffmpeg"),Z=q5(w,"ffprobe"),J=rF(w,"ffmpeg").version??"unknown",X=await cd({artifactRoot:_.paths.artifactRoot,config:{...VF,minimumCutUs:O2($.minDuration),motionThreshold:$.motionThreshold,requireAudioSilence:$.protectAudio},ffmpeg:Q,ffmpegVersion:J,ffprobe:Z,now:_.io.now(),project:F,repositoryRoot:_.paths.repositoryRoot,runner:_.runner,toolVersion:_.version}),V=await V_(F),Y=$.apply&&$.handle!=="keep"&&X.analysis.result.recommendedRanges.length>0;if(Y){let H=_.io.now().toISOString(),K=fm({analysis:X.analysis,decisionIds:X.analysis.result.recommendedRanges.map(()=>`decision_${Bw().replaceAll("-","")}`),operation:$.handle==="cut"?"cut":"speed",plan:V,project:X.project,speedRate:$.speedRate,updatedAt:H});if(K.status==="rejected")throw new N("conflict",`Inactivity application was rejected: ${K.reason}`,K);V=h1(K.plan),await e$(F.fileSystem,V)}let j={analysisId:X.analysis.analysisId,applied:Y,candidateCount:X.analysis.result.candidateCount,cuts:X.analysis.result.recommendedRanges,evidencePath:X.analysisPath,handle:$.handle,planHash:_2(V),projectId:X.project.projectId,protectedInteractionCount:X.analysis.result.protectedInteractionCount,referenceRecording:X.analysis.referenceRecording?.recordingId??null};d0(_.io,$.json,j,()=>`${j.cuts.length} project inactivity range(s), ${j.applied?"applied":"evidence only"}; analysis ${j.analysisId}; plan ${j.planHash}`)}async function eS0(_,$){if($.recording.startsWith("project_")){await tS0(_,$);return}await aS0(_,$)}async function _y0(_,$){let F=await g4(_.paths.artifactRoot,$.recording);if(F.manifest.state!=="stopped")throw new N("conflict","Automatic zoom analysis requires a stopped recording with immutable events.");let w=await KN(F);if($.plan!==void 0&&$.plan!=="current"&&$.plan!==w.planId)throw new N("not-found",`Only current (${w.planId}) is available; requested ${$.plan}.`);let Q=kO(await qA(F),w.sourceDurationUs,{enterDurationUs:300000,exitDurationUs:300000,intentMergeGapUs:750000,maxDurationUs:8000000,maxScale:3,minDurationUs:1500000,postHandleUs:1e6,preHandleUs:500000,scale:2}),Z=w;if($.apply)Z=n3({...w,updatedAt:_.io.now().toISOString(),zooms:[...w.zooms.filter(({kind:X})=>X!=="automatic"),...Q]}),Z=h1(Z),await J1(R4(F.directory.path,"edits")),await Lj(F.fileSystem,Z,XF);let J={applied:$.apply,planHash:B6(Z),recordingId:F.manifest.recordingId,suggestions:Q.map((X)=>({confidence:X.confidence,range:X.range,reason:X.reason,scale:X.scale,target:X.target,zoomId:X.zoomId}))};d0(_.io,$.json,J,()=>`${Q.length} automatic zoom suggestion(s), ${$.apply?"applied":"dry-run"}; plan ${J.planHash}`)}function $y0(_,$){let F=_.tracks.filter((Q)=>Q.enabled&&Q.kind==="display-video"),w=$==="primary"?F.find((Q)=>_.sources.displays.some((Z)=>Z.isPrimary&&Z.displayId===Q.source.displayId)):F.find((Q)=>Q.source.displayId===$||Q.trackId===$);if(w===void 0)throw new N("not-found",`No enabled display track matches ${$}.`);return w}async function Fy0(_,$,F,w,Q){let Z=F;if(w){let j=await A_0(_,$,{minDurationUs:3000000,motionThreshold:0.003,protectAudio:!0});for(let H of j.result.cuts)Z=IO(Z,H,F.updatedAt)}let J=$y0($.manifest,Q),X=$.manifest.sources.displays.find(({displayId:j})=>j===J.source.displayId),V=await qA($),Y=$.manifest.tracks.filter((j)=>j.enabled&&(j.kind==="system-audio"||j.kind==="microphone-audio")).map(({trackId:j})=>j);return{effectivePlan:Z,renderPlan:Zl($.manifest,Z,V,{audioTrackIds:Y,camera:{kind:"none"},displayTrackId:J.trackId,frameRate:Math.min(60,X.refreshRateHz),pixelHeight:X.pixelSize.height,pixelWidth:X.pixelSize.width})}}async function wy0(_,$){let F=await g4(_.paths.artifactRoot,$.recording);if(F.manifest.state!=="stopped")throw new N("conflict","Rendering requires a stopped recording with immutable media and events.");let w=await KN(F),Q=await Fy0(_,F,w,$.autoInactivity,$.display),Z=t(k(Q.renderPlan)),J=`renders/resolved-${Z}.json`,X=`renders/${Z}.mp4`;await J1(R4(F.directory.path,"renders"));let V=$.kind==="render-plan"&&$.output!==void 0?await sS0(F,$.output,J):void 0;if(await F.fileSystem.writeTextAtomic(J,`${k(Q.renderPlan)}
5035
5035
  `),$.kind==="render-plan"){if(V!==void 0&&V.relative!==J)await F.fileSystem.writeTextAtomic(V.relative,`${k(Q.renderPlan)}
5036
5036
  `);let T={artifactPath:J,defaultOutputPath:X,display:Q.renderPlan.composition.baseDisplay,renderPlan:Q.renderPlan};d0(_.io,$.json,T,()=>`${Q.renderPlan.recordingId} display=${Q.renderPlan.composition.baseDisplay.displayId} duration=${d_(Q.renderPlan.output.durationUs)} plan=${J}`);return}let Y=await iZ(_,["ffmpeg","ffprobe","rsvg-convert"]),j=q5(Y,"ffmpeg"),H=q5(Y,"ffprobe"),K=rF(Y,"rsvg-convert"),W=await MS(F,$.output??X);if(Cw(W).toLocaleLowerCase()!==".mp4")throw new N("usage","The current renderer writes MP4 output; use a .mp4 path under renders/.");let O=LL(F,W),L=`${O}.plan.json`,G=$.dryRun?null:await MS(F,L),D=await Mr(Q.renderPlan,{bundleRoot:F.directory.path,dryRun:$.dryRun,ffprobe:H,rsvgConvert:K.available?K.command:void 0,runner:_.runner}),z=await kr(F.manifest,Q.renderPlan,{bundleRoot:F.directory.path,ffmpeg:j,outputPath:W,overlaySources:D.sources}),C={artifactPath:J,dryRun:$.dryRun,invocation:z.invocation,outputPath:O,preprocessing:D.steps,receiptPath:$.dryRun?null:L};if($.dryRun){d0(_.io,$.json,C,()=>`${z.argv.join(" ")}