@hraness/slopcamera 3.9.1 → 3.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1570,7 +1570,7 @@ ${H}`.trim();return{exitCode:Y,output:W}}async function sA($,Q,Z){pZ(Z);let _=aw
1570
1570
  for (const url of urls.keys()) nativeRevokeUrl(url);
1571
1571
  urls.clear(); liveBytes = 0;
1572
1572
  }, { once: true }]);
1573
- }`);return B80(Q,"return securityViolations;","return securityViolations + (sparkWorkerFailure === null ? 0 : 1);")}var vh=sZ.string().regex(/^[a-f0-9]{64}$/u),C80=sZ.union([sZ.literal(1),sZ.literal(2),sZ.literal(3)]),Xg0=sZ.strictObject({key:sZ.string().min(1).max(512),sha256:vh}),e9=sZ.strictObject({algorithm:sZ.literal("sha256-merkle-v1"),leaves:sZ.array(Xg0).min(4).max(256).superRefine(($,Q)=>{for(let Z=1;Z<$.length;Z+=1)if($[Z-1].key>=$[Z].key)Q.addIssue({code:"custom",message:"HTML-overlay integrity leaves must have unique ASCII-sorted keys.",path:[Z,"key"]})}),rootSha256:vh,runtimeSha256:vh,schemaVersion:C80}),i8=Object.freeze({browser:"playwright-chromium",browserVersion:U80.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"})}),Fg0=Object.freeze({...i8.launch,args:Object.freeze([...i8.launch.args.filter(($)=>$!=="--enable-unsafe-swiftshader"&&$!=="--use-angle=swiftshader"),"--use-angle=metal","--disable-software-rasterizer"])});function Jg0($){if($===void 0)return i8;let Q=EQ.parse($);return Object.freeze({...i8,contentSecurityPolicy:Q==="three-spark-webgl2-hardware-v1"?Object.freeze(i8.contentSecurityPolicy.map((Z)=>{if(Z==="worker-src 'none'")return"worker-src blob:";if(Z==="connect-src 'none'")return"connect-src https://slopcamera-overlay.invalid data:";if(Z.startsWith("script-src "))return`${Z} 'wasm-unsafe-eval'`;return Z})):i8.contentSecurityPolicy,executionProfile:Q,launch:Fg0,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 M80($,Q=[]){let Z=Jg0($),X=cZ.parse(Q).filter((F)=>F.transport==="fetch").map((F)=>`${i8.routing.allowedOrigin}${AQ(F)}`);if(X.length===0||!Z.contentSecurityPolicy.includes("connect-src 'none'"))return Z;return Object.freeze({...Z,contentSecurityPolicy:Object.freeze(Z.contentSecurityPolicy.map((F)=>F==="connect-src 'none'"?`connect-src ${X.join(" ")}`:F)),schemaVersion:3})}function Yg0($,Q=[]){let Z=M80($,Q);return Object.freeze({...Z,launch:Object.freeze({...Z.launch,args:Object.freeze(Z.launch.args.map((_)=>_.startsWith("--disable-features=")?`${_},PaintHolding,MacAppCodeSignClone`:_))}),schemaVersion:4})}var Hg0="1.62.0",A80=Object.freeze(["AvoidUnnecessaryBeforeUnloadCheckSync","BoundaryEventDispatchTracksNodeRemoval","DestroyProfileOnBrowserClose","DialMediaRouteProvider","GlobalMediaControls","HttpsUpgrades","LensOverlay","MediaRouter","PaintHolding","ThirdPartyStoragePartitioning","BlockOriginHeaderModificationOnRedirect","Translate","AutoDeElevate","OptimizationHints","msForceBrowserSignIn","msEdgeUpdateLaunchServicesPreferredVersion"]),Kg0=`--disable-features=${A80.join(",")}`;function rA($,Q=[],Z=3){let _=C80.parse(Z);if(_===1)return M80($,Q);let X=Yg0($,Q);if(_===2)return X;if(U80.version!==Hg0)throw Error("The merged HTML-overlay launch policy requires qualified playwright-core 1.62.0 defaults.");return Object.freeze({...X,launch:Object.freeze({...X.launch,args:Object.freeze(X.launch.args.map((F)=>F.startsWith("--disable-features=")?`--disable-features=${[...new Set([...A80,...F.slice(19).split(",")])].join(",")}`:F)),ignoreDefaultArgs:Object.freeze([Kg0])}),schemaVersion:5})}function IO($,Q){if(Q===void 0)return;EQ.parse(Q);let Z=Q==="three-webgl2-hardware-v1"?["three"]:["@sparkjsdev/spark","three","three/addons/postprocessing/Pass.js"];if(R([...$].sort())!==R(Z))throw Error("Hardware execution profile requires its exact approved scene library set.")}function PO($){return _g0("sha256").update($).digest("hex")}function Wg0($,Q){return PO(R({domain:"slopcamera.html-overlay-integrity-leaf/v1",key:$,value:Q}))}function Vg0($){let Q=$.map((Z)=>PO(["slopcamera.html-overlay-integrity-node/v1","leaf",Z.key,Z.sha256].join("\x00")));while(Q.length>1){let Z=[];for(let _=0;_<Q.length;_+=2){let X=Q[_],F=Q[_+1]??X;Z.push(PO(["slopcamera.html-overlay-integrity-node/v1","branch",X,F].join("\x00")))}Q=Z}return Q[0]}function $6($,Q,Z,_=3){let X=kQ.parse($);IO(X.libraries,Z);let F=e$.parse(Q),J=X.libraries.map(lZ),Y=MA(X.libraries),H=Kh({canvas:X.canvas,parameters:X.parameters,resources:X.resources,seed:X.seed,timing:X.timing}),K=Z==="three-spark-webgl2-hardware-v1"?z80(H):H,W=PO(Buffer.from(K,"utf8")),G=[{key:"authoring-config",value:{canvas:X.canvas,kind:X.kind,parameters:X.parameters,schemaVersion:X.schemaVersion,seed:X.seed,timing:X.timing}},{key:"browser-runtime",value:F},{key:"renderer-contract",value:rA(Z,X.resources,_)},{key:"document",value:{bytes:Buffer.byteLength(X.html,"utf8"),sha256:PO(Buffer.from(X.html,"utf8"))}},{key:"import-map",value:Y},{key:"runtime",value:{bytes:Buffer.byteLength(K,"utf8"),sha256:W}},...J.map((D)=>({key:`library:${D.specifier}`,value:D})),...X.resources.map((D)=>({key:`resource:${D.name}`,value:D}))].map((D)=>({key:D.key,sha256:Wg0(D.key,D.value)})).sort((D,L)=>D.key<L.key?-1:D.key>L.key?1:0),N=e9.parse({algorithm:"sha256-merkle-v1",leaves:G,rootSha256:Vg0(G),runtimeSha256:W,schemaVersion:_});return Object.freeze({importMap:Y,integrity:Object.freeze(N),libraryLocks:Object.freeze(J),runtimeSource:K})}var vV="slopcamera-3.9.1",bO=["scene.audit","scene.inspect","scene.patch","scene.evaluate","scene.render","scene.render-audit","scene.review","scene.direction.check","scene.direction.compile","scene.direction.gallery","scene.effects.check","scene.effects.plan","scene.behavior.check","scene.behavior.bake","scene.behavior.gallery","scene.behavior.audit","scene.temporal-audit","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","slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.vectorize","slopcamera.image.generate"],SO=["cpu","local-io","ffmpeg","vision","whisper","network","paid-call","project-render","project-publication","output-publication","capture-device","browser"];import{isAbsolute as Gg0,relative as gh,resolve as T80}from"path";import{z as v1}from"zod";var Ng0=v1.strictObject({path:z0}),jH=536870912,oA=v1.union([Ng0,gj,E0]),iA=v1.strictObject({endBehavior:v1.enum(["hide","loop","freeze-end"]).default("hide"),playbackRate:v1.number().finite().positive().max(64).default(1),sourceInUs:v1.number().int().safe().nonnegative().default(0),sourceOutUs:v1.number().int().safe().positive().optional()}).prefault({}),mh=v1.strictObject({artifact:E0,id:v1.string().min(1).max(256),provider:v1.enum(["apple-emoji-pack","brand-catalog"]),selector:zI,variant:v1.enum(["color","duotone"])}),jg0=v1.discriminatedUnion("kind",[v1.strictObject({artifact:oA,kind:v1.literal("image")}),v1.strictObject({artifact:oA,kind:v1.literal("svg")}),v1.strictObject({artifact:oA,kind:v1.literal("gif"),playback:iA}),v1.strictObject({artifact:oA,audioPolicy:zz.default({kind:"mute"}),kind:v1.literal("video"),playback:iA}),v1.strictObject({kind:v1.literal("emoji"),provider:v1.enum(["apple-emoji-pack","brand-catalog","auto"]).default("auto"),query:v1.string().min(1).max(256),resolved:mh.optional(),variant:v1.enum(["color","duotone"]).optional()})]),R80=v1.discriminatedUnion("kind",[v1.strictObject({artifact:E0,kind:v1.literal("image")}),v1.strictObject({artifact:E0,kind:v1.literal("svg")}),v1.strictObject({artifact:E0,kind:v1.literal("gif"),playback:iA}),v1.strictObject({artifact:E0,audioPolicy:zz,kind:v1.literal("video"),playback:iA}),v1.strictObject({kind:v1.literal("emoji"),provider:v1.enum(["apple-emoji-pack","brand-catalog","auto"]),query:v1.string().min(1).max(256),resolved:mh,variant:v1.enum(["color","duotone"]).optional()})]),uh=v1.strictObject({anchor:CI.default("center"),blendMode:v1.enum(["normal","addition","darken","lighten","multiply","overlay","screen"]).default("normal"),crop:AI.default({kind:"none"}),entrance:Bj.default({kind:"none"}),exit:Bj.default({kind:"none"}),fit:v1.enum(["contain","cover","fill"]).default("fill"),mask:TI.default({kind:"none"}),motion:RI.default({kind:"none"}),opacity:v1.number().finite().min(0).max(1).default(1),position:e6.default({x:0,y:0}),rotationDegrees:v1.number().finite().min(-3600).max(3600).default(0),scale:v1.number().finite().positive().max(128).default(1),size:MI.default({kind:"intrinsic"}),zIndex:v1.number().int().safe().default(0)}).prefault({}),DH=v1.strictObject({capabilityBindings:s4.optional(),identityKey:v1.string().min(1).max(128).optional(),layout:uh,project:V2,range:u0,source:jg0}),lh=DH.extend({source:R80}).strict(),EJ=v1.strictObject({artifact:E0,created:v1.boolean(),operation:z5,receipt:E0}),dh=v1.strictObject({artifact:E0,createdAt:v1.string().datetime({offset:!0}),exactInputSha256:v,ffprobeVersion:v1.string().min(1).max(256).nullable(),kind:v1.union([v1.literal("slopcamera.local-overlay-preparation-receipt"),v1.literal("studio.local-overlay-preparation-receipt")]),operationSha256:v,overlayId:v1.string().min(1).max(128),projectGenerationSha256:v,projectId:V2,schemaVersion:v1.literal(1)});function Dg0($){let Q=$.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test(Q))return{kind:"id",value:Q};if([...$].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test($))return{kind:"unicode",value:$};return{kind:"name",value:$}}function Og0($){if(!("bytes"in $))return $;return E0.parse({bytes:$.bytes,path:$.path,sha256:$.sha256})}function k80($){return $.kind==="image"||$.kind==="gif"||$.kind==="video"?["ffprobe"]:[]}async function Lg0($,Q,Z,_){let X=await _($.paths.repositoryRoot,Q.query,Q.variant,Q.provider),F=gh($.paths.repositoryRoot,X.path),J=await o1($,{path:F},Z,jH);if(J.artifact.sha256!==X.sha256)throw new j("conflict","Resolved emoji bytes disagree with the checked emoji catalog.");let Y=mh.parse({artifact:J.artifact,id:X.id,provider:X.provider,selector:Dg0(Q.query),variant:X.variant});if(Q.resolved!==void 0&&R(Q.resolved)!==R(Y))throw new j("conflict","The checked emoji asset changed after exact node planning.");return R80.parse({...Q,resolved:Y})}async function ch($,Q,Z,_={}){let X=DH.parse(Q),F=k80(X.source),J=X.source.kind==="emoji"?Lg0($,X.source,Z,_.resolveEmoji??xV):o1($,Og0(X.source.artifact),Z,jH).then((K)=>({...X.source,artifact:K.artifact})),[Y,H]=await Promise.all([J,B5($,F,X.capabilityBindings)]);return lh.parse({...X,capabilityBindings:H,source:Y})}function wg0($,Q){let Z=T80($,Q),_=gh(T80($),Z);if(_===""||_.startsWith("..")||Gg0(_))throw new j("unsafe-path","Prepared overlay asset escaped its project bundle.");return Z}function Bg0($,Q,Z){let _=UI.parse(Q),X={bytes:_.asset.bytes,mediaType:_.asset.mediaType,sha256:_.asset.sha256},F=_.kind==="image"||_.kind==="svg"?{asset:X,kind:_.kind}:_.kind==="emoji"?{asset:X,kind:_.kind,provider:_.provider,selector:_.selector}:{asset:X,audioPolicy:_.audioPolicy,kind:_.kind,playback:_.playback};return`overlay_${g({domain:"studio.media-overlay-operation/v1",identityKey:$.identityKey??null,intrinsicSize:Z,layout:$.layout,project:$.project,range:$.range,source:F}).slice(0,32)}`}function zg0($={}){let Q=$.ingestFile??vA,Z=$.ingestEmoji??gA,_=$.inspectPng??GH,X=$.inspectSvg??qJ,F=$.probe??xZ,J=$.resolveEmoji??xV;return{inputSchema:DH,inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",lifecycle:{kind:"local-artifact",execute:async(Y,H)=>{a(Y.abortSignal);let K=await ch(Y.application,H,Y.abortSignal,{resolveEmoji:J}),W=k80(K.source);await a9(Y,Y.application,K.capabilityBindings,W);let V=K.capabilityBindings??await MX(Y.application,W),G=await o2(Y.application,K.project);if(n8(Y.expectedProjectGeneration,G.generation),K.range.endUs>G.plan.timelineDurationUs)throw new j("usage","Overlay range exceeds the project timeline.");let N=J3(F3(G.plan),K.range).reduce((B,z)=>B+z.output.endUs-z.output.startUs,0);if(N<=0)throw new j("conflict","Overlay range has no visible kept output time.");let D=K.source.kind==="emoji"?void 0:await o1(Y.application,K.source.artifact,Y.abortSignal,jH),L=K.source.kind==="emoji"?K.source:void 0,O=L===void 0?void 0:await J(Y.application.paths.repositoryRoot,L.query,L.variant,L.provider);if(O!==void 0&&L!==void 0&&(O.id!==L.resolved.id||O.provider!==L.resolved.provider||O.variant!==L.resolved.variant||O.sha256!==L.resolved.artifact.sha256))throw new j("conflict","Resolved emoji changed immediately before preparation.");let w=await Q5(Y);try{await Y.workflow?.beforePublication(),a(Y.abortSignal);let B=O===void 0?await Q(G.openProject.directory.path,D.absolutePath,K.source.kind):await Z(G.openProject.directory.path,O),z=D?.artifact??L.resolved.artifact;if(B.bytes!==z.bytes||B.sha256!==z.sha256||B.provenance.sourceSha256!==z.sha256)throw new j("conflict","Prepared overlay bytes disagree with the exact bound source.");let U=wg0(G.openProject.directory.path,B.path),C=(await o1(Y.application,{path:gh(Y.application.paths.repositoryRoot,U)},Y.abortSignal,jH)).artifact;if(C.bytes!==B.bytes||C.sha256!==B.sha256)throw new j("conflict","Prepared project asset disagrees with its published bytes.");let M=B.mediaType==="image/svg+xml"?{...await X(U),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:K.source.kind==="emoji"?{...await _(U),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await F(F5(V,"ffprobe"),new H8(o8(Y.application,V),Y.abortSignal),U),T={height:"pixelHeight"in M?M.pixelHeight:M.height,width:"pixelWidth"in M?M.pixelWidth:M.width},q={bytes:B.bytes,mediaType:B.mediaType,path:B.path,provenance:B.provenance,sha256:B.sha256},E;if(K.source.kind==="image"||K.source.kind==="svg")E={asset:q,kind:K.source.kind};else if(K.source.kind==="emoji")E={asset:q,kind:"emoji",provider:K.source.resolved.provider,selector:K.source.resolved.selector};else{if(M.durationUs===null||M.durationUs<=0)throw new j("invalid-data","Animated overlay media must report a positive duration.");let x=hV({mediaDurationUs:M.durationUs,outputDurationUs:N,playbackRate:K.source.playback.playbackRate,sourceInUs:K.source.playback.sourceInUs,sourceOutUs:K.source.playback.sourceOutUs}),b={audioEndUs:M.audioEndUs,audioStartUs:M.audioStartUs,audioStreamIndex:M.audioStreamIndex,endBehavior:K.source.playback.endBehavior,playbackRate:K.source.playback.playbackRate,streamStartUs:M.videoStartUs,videoStreamIndex:M.videoStreamIndex,...x};if(K.source.kind==="gif")E={asset:q,audioPolicy:{kind:"mute"},kind:"gif",playback:b};else{if(K.source.audioPolicy.kind!=="mute"&&!M.hasAudio)throw new j("conflict","The selected video overlay audio policy requires an audio stream.");E={asset:q,audioPolicy:K.source.audioPolicy,kind:"video",playback:b}}}let A=z5.parse({...K.layout,coordinateSpace:"output-pixels",intrinsicSize:T,overlayId:Bg0(K,E,T),range:K.range,source:E}),k=dh.parse({artifact:C,createdAt:Y.application.clock.now().toISOString(),exactInputSha256:g(K),ffprobeVersion:W.length===0?null:t9(V,"ffprobe"),kind:"slopcamera.local-overlay-preparation-receipt",operationSha256:g(A),overlayId:A.overlayId,projectGenerationSha256:G.generation.generationSha256,projectId:G.project.projectId,schemaVersion:1}),P=await T6({context:Y,receipt:k,workspace:w}),I=EJ.parse({artifact:C,created:B.created,operation:A,receipt:P});return await u5(Y,{inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",outputSchemaId:"slopcamera.operation.media.overlay.output/v1",version:1},I),I}finally{await w.dispose()}}},outputSchema:EJ,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:(Y)=>Y.receipt.path,summarize:(Y)=>({fields:{bytes:Y.artifact.bytes,created:Y.created,kind:Y.operation.source.kind,overlayId:Y.operation.overlayId,receipt:Y.receipt.path,sha256:Y.artifact.sha256},kind:"media.overlay"}),version:1}}var q80=zg0();var aA=2097152,tA=134217728,nh=536870912,sh=["ffmpeg","ffprobe","html-browser"],Rg0=n4.union([yV,n4.strictObject({path:z0}),E0]),kg0=n4.union([yV,E0]),qg0=n4.union([f5,gj]),Eg0=RQ.omit({bytes:!0,sha256:!0}).extend({artifact:qg0}).strict(),Pg0=RQ.extend({artifact:E0}).strict(),fO=n4.strictObject({canvas:TX,capabilityBindings:s4.optional(),document:Rg0,identityKey:n4.string().min(1).max(128).optional(),layout:uh,libraries:uZ.default([]),parameters:AJ.default({}),project:V2,range:u0,resources:n4.array(Eg0).max(64).default([]),seed:n4.number().int().min(0).max(4294967295).default(0),timing:I3}),rh=fO.omit({document:!0,resources:!0}).extend({document:kg0,resources:n4.array(Pg0).max(64)}).strict(),oh=n4.strictObject({artifact:E0,browserVersion:n4.string().min(1).max(512),createdAt:n4.string().datetime({offset:!0}),executionIntegrity:e9.optional(),exactInputSha256:v,ffmpegVersion:n4.string().min(1).max(512),ffprobeVersion:n4.string().min(1).max(512),frameCount:n4.number().int().safe().positive(),kind:n4.union([n4.literal("slopcamera.html-overlay-preparation-receipt"),n4.literal("studio.html-overlay-preparation-receipt")]),libraryLocks:_h,libraryLocksSha256:v,operationSha256:v,overlayId:n4.string().min(1).max(128),projectGenerationSha256:v,projectId:V2,schemaVersion:n4.literal(1)}),P80=EJ;function Ig0($){if(!("mediaType"in $.artifact))return $.artifact;if($.artifact.mediaType!==$.mediaType)throw new j("invalid-data",`HTML overlay resource ${$.name} declares ${$.mediaType} but its generated artifact is ${$.artifact.mediaType}.`);return E0.parse({bytes:$.artifact.bytes,path:$.artifact.path,sha256:$.artifact.sha256})}async function bg0($,Q,Z){if("html"in Q)return Q;return(await o1($,Q,Z,aA)).artifact}function Sg0($,Q){return J3(F3($),Q).reduce((Z,_)=>Z+_.output.endUs-_.output.startUs,0)}async function ih($,Q,Z){let _=fO.parse(Q),[X,F,J]=await Promise.all([bg0($,_.document,Z),Promise.all(_.resources.map(async(K)=>({...K,artifact:(await o1($,Ig0(K),Z,tA)).artifact}))),B5($,sh,_.capabilityBindings)]),Y=cZ.parse(F.map(({artifact:K,...W})=>({...W,bytes:K.bytes,sha256:K.sha256}))),H=new Map(F.map((K)=>[K.name,K.artifact]));return rh.parse({..._,capabilityBindings:J,document:X,resources:Y.map((K)=>({...K,artifact:H.get(K.name)}))})}function fg0($){let Q;try{Q=new TextDecoder("utf-8",{fatal:!0}).decode($)}catch{throw new j("invalid-data","The HTML overlay document must be valid UTF-8.")}if(Q.trim()==="")throw new j("invalid-data","The HTML overlay document is empty.");return Q}async function yg0($,Q){let Z=await Mg0($,E80.O_RDONLY|(E80.O_NOFOLLOW??0));try{let _=await Z.stat();if(!_.isFile()||_.size<=0)throw new j("invalid-data","Rendered HTML overlay is empty.");let X=Ug0("sha256"),F=Buffer.allocUnsafe(1048576),J=0;while(J<_.size){a(Q);let H=await Z.read(F,0,Math.min(F.byteLength,_.size-J),J);if(H.bytesRead===0)break;X.update(F.subarray(0,H.bytesRead)),J+=H.bytesRead}let Y=await Z.stat();if(J!==_.size||Y.dev!==_.dev||Y.ino!==_.ino||Y.size!==_.size||Y.mtimeMs!==_.mtimeMs||Y.ctimeMs!==_.ctimeMs)throw new j("conflict","Rendered HTML overlay changed while it was being verified.");return X.digest("hex")}finally{await Z.close()}}var xg0=n4.object({streams:n4.array(n4.object({codec_name:n4.string(),height:n4.number().int().positive(),pix_fmt:n4.string(),width:n4.number().int().positive()})).min(1)});async function hg0($,Q,Z,_,X){let F=await new H8(o8($,Q),X).run([F5(Q,"ffprobe"),"-v","error","-select_streams","v:0","-show_entries","stream=codec_name,pix_fmt,width,height","-of","json",Z],{maxOutputBytes:65536,stdin:"ignore",timeoutMs:30000});if(F.exitCode!==0)throw new j("invalid-data","Rendered HTML overlay could not be inspected as an alpha video.");let J;try{J=JSON.parse(F.stdout)}catch{throw new j("invalid-data","Rendered HTML overlay inspection returned invalid JSON.")}let Y=xg0.parse(J).streams[0];if(Y.codec_name!=="qtrle"||Y.pix_fmt!=="argb"||Y.width!==_.width||Y.height!==_.height)throw new j("invalid-data","Rendered HTML overlay must be a canvas-sized qtrle/argb alpha video.",{stream:Y})}function vg0($,Q,Z){return`overlay_${g({assetSha256:Z,authoring:Q,domain:"studio.media-html-overlay-operation/v1",identityKey:$.identityKey??null,layout:$.layout,project:$.project,range:$.range}).slice(0,32)}`}function ah($={}){let Q=$.ingest??F80,Z=$.probe??xZ,_=$.bindBrowserRuntime??F$,X=$.toolVersion??vV;return{inputSchema:fO,inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",lifecycle:{kind:"local-artifact",execute:async(F,J)=>{a(F.abortSignal);let Y=await ih(F.application,J,F.abortSignal);await a9(F,F.application,Y.capabilityBindings,sh);let H=Y.capabilityBindings??await MX(F.application,sh),K=F.application.htmlOverlayRenderer;if(K===void 0)throw new j("unavailable","This Slopcamera host does not provide an HTML-overlay browser renderer.");let W=await o2(F.application,Y.project);if(n8(F.expectedProjectGeneration,W.generation),Y.range.endUs>W.plan.timelineDurationUs)throw new j("usage","HTML overlay range exceeds the project timeline.");let V=Sg0(W.plan,Y.range);if(V<=0)throw new j("conflict","HTML overlay range has no visible kept output time.");if(Y.timing.durationUs!==V)throw new j("conflict","HTML overlay timing duration must equal the range's visible output duration.",{actualDurationUs:Y.timing.durationUs,expectedDurationUs:V});let[G,N]=await Promise.all(["html"in Y.document?Promise.resolve(Y.document.html):U4(F.application,Y.document,F.abortSignal,aA).then((w)=>fg0(w.data)),Promise.all(Y.resources.map(async(w)=>({...w,absolutePath:(await o1(F.application,w.artifact,F.abortSignal,tA)).absolutePath})))]),D=kQ.parse({canvas:Y.canvas,html:G,kind:"slopcamera.html-overlay",libraries:Y.libraries,parameters:Y.parameters,resources:N.map((w)=>({bytes:w.bytes,mediaType:w.mediaType,name:w.name,sha256:w.sha256,...w.transport===void 0?{}:{transport:w.transport},urlPath:w.urlPath})),schemaVersion:1,seed:Y.seed,timing:Y.timing}),L=await Q5(F),O=await Cg0(ph(L.path,"html-overlay-"));try{let w=await _(l5(H,"html-browser"),F.abortSignal),B=$6(D,w).integrity,z=await K.renderFrames({authoring:D,browserRuntime:w,outputDirectory:O,resources:N},F.abortSignal),U=e9.parse(z.executionIntegrity);if(g(U)!==g(B))throw new j("conflict","HTML-overlay renderer returned integrity evidence that does not match the planned browser execution.");let C=CO.parse(z.libraryLocks),M=D.libraries.map(lZ);if(g(C)!==g(M))throw new j("conflict","HTML-overlay renderer returned library locks that do not exactly match the authoring selection.");let T=b6(D.timing);if(z.frameCount!==T)throw new j("conflict","HTML-overlay renderer returned an unexpected frame count.");let q=ph(O,"overlay.mov"),E=[F5(H,"ffmpeg"),"-hide_banner","-loglevel","error","-nostdin","-n","-framerate",String(D.timing.fps),"-start_number","0","-i",z.framePattern,"-frames:v",String(z.frameCount),"-an","-c:v","qtrle","-pix_fmt","argb","-movflags","+faststart",q],A=await new H8(o8(F.application,H),F.abortSignal).run(E,{cwd:O,maxOutputBytes:1048576,stdin:"ignore",timeoutMs:3600000});if(A.exitCode!==0)throw new j("invalid-data",`FFmpeg could not encode the HTML overlay: ${A.stderr.slice(0,2000)}`);await hg0(F.application,H,q,D.canvas,F.abortSignal);let k=await yg0(q,F.abortSignal);await F.workflow?.beforePublication(),a(F.abortSignal);let P=await Q(W.openProject.directory.path,{command:E,generator:"slopcamera-html-overlay",generatorVersion:X,path:q,sourceSha256:k}),I=ph(W.openProject.directory.path,P.path),x=(await o1(F.application,{path:Tg0(F.application.paths.repositoryRoot,I)},F.abortSignal,nh)).artifact,b=await Z(F5(H,"ffprobe"),new H8(o8(F.application,H),F.abortSignal),I);if(b.durationUs===null||b.durationUs<=0||b.hasAudio||b.pixelWidth!==D.canvas.width||b.pixelHeight!==D.canvas.height)throw new j("invalid-data","Generated HTML overlay has invalid duration, dimensions, or audio streams.");let y=hV({mediaDurationUs:b.durationUs,outputDurationUs:V,playbackRate:1,sourceInUs:0,sourceOutUs:void 0}),r={asset:{bytes:P.bytes,mediaType:P.mediaType,path:P.path,provenance:P.provenance,sha256:P.sha256},audioPolicy:{kind:"mute"},kind:"video",playback:{audioEndUs:null,audioStartUs:0,audioStreamIndex:null,endBehavior:"hide",playbackRate:1,streamStartUs:b.videoStartUs,videoStreamIndex:b.videoStreamIndex,...y}},m=z5.parse({...Y.layout,coordinateSpace:"output-pixels",intrinsicSize:{height:D.canvas.height,width:D.canvas.width},overlayId:vg0(Y,D,x.sha256),range:Y.range,source:r}),p=oh.parse({artifact:x,browserVersion:t9(H,"html-browser"),createdAt:F.application.clock.now().toISOString(),executionIntegrity:U,exactInputSha256:g(Y),ffmpegVersion:t9(H,"ffmpeg"),ffprobeVersion:t9(H,"ffprobe"),frameCount:z.frameCount,kind:"slopcamera.html-overlay-preparation-receipt",libraryLocks:C,libraryLocksSha256:g(C),operationSha256:g(m),overlayId:m.overlayId,projectGenerationSha256:W.generation.generationSha256,projectId:W.project.projectId,schemaVersion:1}),S=await T6({context:F,receipt:p,workspace:L}),i=EJ.parse({artifact:x,created:P.created,operation:m,receipt:S});return await u5(F,{inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",version:1},i),i}finally{await Ag0(O,{force:!0,recursive:!0}),await L.dispose()}}},outputSchema:EJ,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:(F)=>F.receipt.path,summarize:(F)=>({fields:{bytes:F.artifact.bytes,created:F.created,kind:"html",overlayId:F.operation.overlayId,receipt:F.receipt.path,sha256:F.artifact.sha256},kind:"media.html-overlay"}),version:1}}var HA1=ah();var mg0=["media.ingest","media.html-overlay","media.overlay","media.audio-effects","media.color-grade"],OA1=gg0.enum(mg0);async function I80($,Q,Z,_=new AbortController().signal){switch(Q){case"media.ingest":return await t50($,fV.parse(Z),_);case"media.overlay":return await ch($,DH.parse(Z),_);case"media.html-overlay":return await ih($,fO.parse(Z),_);case"media.audio-effects":return await p50($,bV.parse(Z),_);case"media.color-grade":return await r50($,SV.parse(Z),_)}}import{z as yO}from"zod";import{lstat as sg0,realpath as f80}from"fs/promises";import{isAbsolute as ng0,join as rg0,relative as og0,sep as ig0}from"path";import{z as nZ}from"zod";var eA=4096,th=4,ug0=16777216,eh=Object.freeze({maximumCount:64,maximumTotalPixels:67108864,maximumTotalSvgBytes:67108864});function b80($){let Q=1;while(Q<$)Q*=2;return Q}function lg0($){let Q=[],Z=0,_=[],X=0,F=0,J=0,Y=0,H=()=>{if(_.length===0)return;let K=b80(F+J),W=b80(Y),V=W*K;if(Q.length>=eh.maximumCount||Z+V>eh.maximumTotalPixels)throw RangeError("Generated caption sprites exceed the cumulative raster resource bound.");Q.push({cards:_,height:K,width:W}),Z+=V,_=[],X=0,F=0,J=0,Y=0};for(let K of $){let{intrinsicHeight:W,intrinsicWidth:V}=K.rendered;if(V>eA||W>eA)throw RangeError("A social caption card exceeds the sprite dimension bound.");if(X>0&&X+V>eA)X=0,F+=J+th,J=0;if(F>0&&F+W>eA)H();_.push({...K,x:X,y:F}),X+=V+th,J=Math.max(J,W),Y=Math.max(Y,X-th)}return H(),Q}function dg0($){let Q=$.indexOf(">");if(!$.startsWith("<svg ")||Q<0||!$.endsWith("</svg>"))throw TypeError("Social caption renderer returned an unsupported SVG document.");return $.slice(Q+1,-6)}function cg0($){let Q=$.cards.map((X)=>`<g transform="translate(${X.x} ${X.y})">${dg0(X.rendered.svg)}</g>`).join(""),Z=[`<svg xmlns="http://www.w3.org/2000/svg" width="${$.width}" height="${$.height}" viewBox="0 0 ${$.width} ${$.height}" fill="none">`,Q,`</svg>
1573
+ }`);return B80(Q,"return securityViolations;","return securityViolations + (sparkWorkerFailure === null ? 0 : 1);")}var vh=sZ.string().regex(/^[a-f0-9]{64}$/u),C80=sZ.union([sZ.literal(1),sZ.literal(2),sZ.literal(3)]),Xg0=sZ.strictObject({key:sZ.string().min(1).max(512),sha256:vh}),e9=sZ.strictObject({algorithm:sZ.literal("sha256-merkle-v1"),leaves:sZ.array(Xg0).min(4).max(256).superRefine(($,Q)=>{for(let Z=1;Z<$.length;Z+=1)if($[Z-1].key>=$[Z].key)Q.addIssue({code:"custom",message:"HTML-overlay integrity leaves must have unique ASCII-sorted keys.",path:[Z,"key"]})}),rootSha256:vh,runtimeSha256:vh,schemaVersion:C80}),i8=Object.freeze({browser:"playwright-chromium",browserVersion:U80.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"})}),Fg0=Object.freeze({...i8.launch,args:Object.freeze([...i8.launch.args.filter(($)=>$!=="--enable-unsafe-swiftshader"&&$!=="--use-angle=swiftshader"),"--use-angle=metal","--disable-software-rasterizer"])});function Jg0($){if($===void 0)return i8;let Q=EQ.parse($);return Object.freeze({...i8,contentSecurityPolicy:Q==="three-spark-webgl2-hardware-v1"?Object.freeze(i8.contentSecurityPolicy.map((Z)=>{if(Z==="worker-src 'none'")return"worker-src blob:";if(Z==="connect-src 'none'")return"connect-src https://slopcamera-overlay.invalid data:";if(Z.startsWith("script-src "))return`${Z} 'wasm-unsafe-eval'`;return Z})):i8.contentSecurityPolicy,executionProfile:Q,launch:Fg0,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 M80($,Q=[]){let Z=Jg0($),X=cZ.parse(Q).filter((F)=>F.transport==="fetch").map((F)=>`${i8.routing.allowedOrigin}${AQ(F)}`);if(X.length===0||!Z.contentSecurityPolicy.includes("connect-src 'none'"))return Z;return Object.freeze({...Z,contentSecurityPolicy:Object.freeze(Z.contentSecurityPolicy.map((F)=>F==="connect-src 'none'"?`connect-src ${X.join(" ")}`:F)),schemaVersion:3})}function Yg0($,Q=[]){let Z=M80($,Q);return Object.freeze({...Z,launch:Object.freeze({...Z.launch,args:Object.freeze(Z.launch.args.map((_)=>_.startsWith("--disable-features=")?`${_},PaintHolding,MacAppCodeSignClone`:_))}),schemaVersion:4})}var Hg0="1.62.0",A80=Object.freeze(["AvoidUnnecessaryBeforeUnloadCheckSync","BoundaryEventDispatchTracksNodeRemoval","DestroyProfileOnBrowserClose","DialMediaRouteProvider","GlobalMediaControls","HttpsUpgrades","LensOverlay","MediaRouter","PaintHolding","ThirdPartyStoragePartitioning","BlockOriginHeaderModificationOnRedirect","Translate","AutoDeElevate","OptimizationHints","msForceBrowserSignIn","msEdgeUpdateLaunchServicesPreferredVersion"]),Kg0=`--disable-features=${A80.join(",")}`;function rA($,Q=[],Z=3){let _=C80.parse(Z);if(_===1)return M80($,Q);let X=Yg0($,Q);if(_===2)return X;if(U80.version!==Hg0)throw Error("The merged HTML-overlay launch policy requires qualified playwright-core 1.62.0 defaults.");return Object.freeze({...X,launch:Object.freeze({...X.launch,args:Object.freeze(X.launch.args.map((F)=>F.startsWith("--disable-features=")?`--disable-features=${[...new Set([...A80,...F.slice(19).split(",")])].join(",")}`:F)),ignoreDefaultArgs:Object.freeze([Kg0])}),schemaVersion:5})}function IO($,Q){if(Q===void 0)return;EQ.parse(Q);let Z=Q==="three-webgl2-hardware-v1"?["three"]:["@sparkjsdev/spark","three","three/addons/postprocessing/Pass.js"];if(R([...$].sort())!==R(Z))throw Error("Hardware execution profile requires its exact approved scene library set.")}function PO($){return _g0("sha256").update($).digest("hex")}function Wg0($,Q){return PO(R({domain:"slopcamera.html-overlay-integrity-leaf/v1",key:$,value:Q}))}function Vg0($){let Q=$.map((Z)=>PO(["slopcamera.html-overlay-integrity-node/v1","leaf",Z.key,Z.sha256].join("\x00")));while(Q.length>1){let Z=[];for(let _=0;_<Q.length;_+=2){let X=Q[_],F=Q[_+1]??X;Z.push(PO(["slopcamera.html-overlay-integrity-node/v1","branch",X,F].join("\x00")))}Q=Z}return Q[0]}function $6($,Q,Z,_=3){let X=kQ.parse($);IO(X.libraries,Z);let F=e$.parse(Q),J=X.libraries.map(lZ),Y=MA(X.libraries),H=Kh({canvas:X.canvas,parameters:X.parameters,resources:X.resources,seed:X.seed,timing:X.timing}),K=Z==="three-spark-webgl2-hardware-v1"?z80(H):H,W=PO(Buffer.from(K,"utf8")),G=[{key:"authoring-config",value:{canvas:X.canvas,kind:X.kind,parameters:X.parameters,schemaVersion:X.schemaVersion,seed:X.seed,timing:X.timing}},{key:"browser-runtime",value:F},{key:"renderer-contract",value:rA(Z,X.resources,_)},{key:"document",value:{bytes:Buffer.byteLength(X.html,"utf8"),sha256:PO(Buffer.from(X.html,"utf8"))}},{key:"import-map",value:Y},{key:"runtime",value:{bytes:Buffer.byteLength(K,"utf8"),sha256:W}},...J.map((D)=>({key:`library:${D.specifier}`,value:D})),...X.resources.map((D)=>({key:`resource:${D.name}`,value:D}))].map((D)=>({key:D.key,sha256:Wg0(D.key,D.value)})).sort((D,L)=>D.key<L.key?-1:D.key>L.key?1:0),N=e9.parse({algorithm:"sha256-merkle-v1",leaves:G,rootSha256:Vg0(G),runtimeSha256:W,schemaVersion:_});return Object.freeze({importMap:Y,integrity:Object.freeze(N),libraryLocks:Object.freeze(J),runtimeSource:K})}var vV="slopcamera-3.9.2",bO=["scene.audit","scene.inspect","scene.patch","scene.evaluate","scene.render","scene.render-audit","scene.review","scene.direction.check","scene.direction.compile","scene.direction.gallery","scene.effects.check","scene.effects.plan","scene.behavior.check","scene.behavior.bake","scene.behavior.gallery","scene.behavior.audit","scene.temporal-audit","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","slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.vectorize","slopcamera.image.generate"],SO=["cpu","local-io","ffmpeg","vision","whisper","network","paid-call","project-render","project-publication","output-publication","capture-device","browser"];import{isAbsolute as Gg0,relative as gh,resolve as T80}from"path";import{z as v1}from"zod";var Ng0=v1.strictObject({path:z0}),jH=536870912,oA=v1.union([Ng0,gj,E0]),iA=v1.strictObject({endBehavior:v1.enum(["hide","loop","freeze-end"]).default("hide"),playbackRate:v1.number().finite().positive().max(64).default(1),sourceInUs:v1.number().int().safe().nonnegative().default(0),sourceOutUs:v1.number().int().safe().positive().optional()}).prefault({}),mh=v1.strictObject({artifact:E0,id:v1.string().min(1).max(256),provider:v1.enum(["apple-emoji-pack","brand-catalog"]),selector:zI,variant:v1.enum(["color","duotone"])}),jg0=v1.discriminatedUnion("kind",[v1.strictObject({artifact:oA,kind:v1.literal("image")}),v1.strictObject({artifact:oA,kind:v1.literal("svg")}),v1.strictObject({artifact:oA,kind:v1.literal("gif"),playback:iA}),v1.strictObject({artifact:oA,audioPolicy:zz.default({kind:"mute"}),kind:v1.literal("video"),playback:iA}),v1.strictObject({kind:v1.literal("emoji"),provider:v1.enum(["apple-emoji-pack","brand-catalog","auto"]).default("auto"),query:v1.string().min(1).max(256),resolved:mh.optional(),variant:v1.enum(["color","duotone"]).optional()})]),R80=v1.discriminatedUnion("kind",[v1.strictObject({artifact:E0,kind:v1.literal("image")}),v1.strictObject({artifact:E0,kind:v1.literal("svg")}),v1.strictObject({artifact:E0,kind:v1.literal("gif"),playback:iA}),v1.strictObject({artifact:E0,audioPolicy:zz,kind:v1.literal("video"),playback:iA}),v1.strictObject({kind:v1.literal("emoji"),provider:v1.enum(["apple-emoji-pack","brand-catalog","auto"]),query:v1.string().min(1).max(256),resolved:mh,variant:v1.enum(["color","duotone"]).optional()})]),uh=v1.strictObject({anchor:CI.default("center"),blendMode:v1.enum(["normal","addition","darken","lighten","multiply","overlay","screen"]).default("normal"),crop:AI.default({kind:"none"}),entrance:Bj.default({kind:"none"}),exit:Bj.default({kind:"none"}),fit:v1.enum(["contain","cover","fill"]).default("fill"),mask:TI.default({kind:"none"}),motion:RI.default({kind:"none"}),opacity:v1.number().finite().min(0).max(1).default(1),position:e6.default({x:0,y:0}),rotationDegrees:v1.number().finite().min(-3600).max(3600).default(0),scale:v1.number().finite().positive().max(128).default(1),size:MI.default({kind:"intrinsic"}),zIndex:v1.number().int().safe().default(0)}).prefault({}),DH=v1.strictObject({capabilityBindings:s4.optional(),identityKey:v1.string().min(1).max(128).optional(),layout:uh,project:V2,range:u0,source:jg0}),lh=DH.extend({source:R80}).strict(),EJ=v1.strictObject({artifact:E0,created:v1.boolean(),operation:z5,receipt:E0}),dh=v1.strictObject({artifact:E0,createdAt:v1.string().datetime({offset:!0}),exactInputSha256:v,ffprobeVersion:v1.string().min(1).max(256).nullable(),kind:v1.union([v1.literal("slopcamera.local-overlay-preparation-receipt"),v1.literal("studio.local-overlay-preparation-receipt")]),operationSha256:v,overlayId:v1.string().min(1).max(128),projectGenerationSha256:v,projectId:V2,schemaVersion:v1.literal(1)});function Dg0($){let Q=$.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test(Q))return{kind:"id",value:Q};if([...$].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test($))return{kind:"unicode",value:$};return{kind:"name",value:$}}function Og0($){if(!("bytes"in $))return $;return E0.parse({bytes:$.bytes,path:$.path,sha256:$.sha256})}function k80($){return $.kind==="image"||$.kind==="gif"||$.kind==="video"?["ffprobe"]:[]}async function Lg0($,Q,Z,_){let X=await _($.paths.repositoryRoot,Q.query,Q.variant,Q.provider),F=gh($.paths.repositoryRoot,X.path),J=await o1($,{path:F},Z,jH);if(J.artifact.sha256!==X.sha256)throw new j("conflict","Resolved emoji bytes disagree with the checked emoji catalog.");let Y=mh.parse({artifact:J.artifact,id:X.id,provider:X.provider,selector:Dg0(Q.query),variant:X.variant});if(Q.resolved!==void 0&&R(Q.resolved)!==R(Y))throw new j("conflict","The checked emoji asset changed after exact node planning.");return R80.parse({...Q,resolved:Y})}async function ch($,Q,Z,_={}){let X=DH.parse(Q),F=k80(X.source),J=X.source.kind==="emoji"?Lg0($,X.source,Z,_.resolveEmoji??xV):o1($,Og0(X.source.artifact),Z,jH).then((K)=>({...X.source,artifact:K.artifact})),[Y,H]=await Promise.all([J,B5($,F,X.capabilityBindings)]);return lh.parse({...X,capabilityBindings:H,source:Y})}function wg0($,Q){let Z=T80($,Q),_=gh(T80($),Z);if(_===""||_.startsWith("..")||Gg0(_))throw new j("unsafe-path","Prepared overlay asset escaped its project bundle.");return Z}function Bg0($,Q,Z){let _=UI.parse(Q),X={bytes:_.asset.bytes,mediaType:_.asset.mediaType,sha256:_.asset.sha256},F=_.kind==="image"||_.kind==="svg"?{asset:X,kind:_.kind}:_.kind==="emoji"?{asset:X,kind:_.kind,provider:_.provider,selector:_.selector}:{asset:X,audioPolicy:_.audioPolicy,kind:_.kind,playback:_.playback};return`overlay_${g({domain:"studio.media-overlay-operation/v1",identityKey:$.identityKey??null,intrinsicSize:Z,layout:$.layout,project:$.project,range:$.range,source:F}).slice(0,32)}`}function zg0($={}){let Q=$.ingestFile??vA,Z=$.ingestEmoji??gA,_=$.inspectPng??GH,X=$.inspectSvg??qJ,F=$.probe??xZ,J=$.resolveEmoji??xV;return{inputSchema:DH,inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",lifecycle:{kind:"local-artifact",execute:async(Y,H)=>{a(Y.abortSignal);let K=await ch(Y.application,H,Y.abortSignal,{resolveEmoji:J}),W=k80(K.source);await a9(Y,Y.application,K.capabilityBindings,W);let V=K.capabilityBindings??await MX(Y.application,W),G=await o2(Y.application,K.project);if(n8(Y.expectedProjectGeneration,G.generation),K.range.endUs>G.plan.timelineDurationUs)throw new j("usage","Overlay range exceeds the project timeline.");let N=J3(F3(G.plan),K.range).reduce((B,z)=>B+z.output.endUs-z.output.startUs,0);if(N<=0)throw new j("conflict","Overlay range has no visible kept output time.");let D=K.source.kind==="emoji"?void 0:await o1(Y.application,K.source.artifact,Y.abortSignal,jH),L=K.source.kind==="emoji"?K.source:void 0,O=L===void 0?void 0:await J(Y.application.paths.repositoryRoot,L.query,L.variant,L.provider);if(O!==void 0&&L!==void 0&&(O.id!==L.resolved.id||O.provider!==L.resolved.provider||O.variant!==L.resolved.variant||O.sha256!==L.resolved.artifact.sha256))throw new j("conflict","Resolved emoji changed immediately before preparation.");let w=await Q5(Y);try{await Y.workflow?.beforePublication(),a(Y.abortSignal);let B=O===void 0?await Q(G.openProject.directory.path,D.absolutePath,K.source.kind):await Z(G.openProject.directory.path,O),z=D?.artifact??L.resolved.artifact;if(B.bytes!==z.bytes||B.sha256!==z.sha256||B.provenance.sourceSha256!==z.sha256)throw new j("conflict","Prepared overlay bytes disagree with the exact bound source.");let U=wg0(G.openProject.directory.path,B.path),C=(await o1(Y.application,{path:gh(Y.application.paths.repositoryRoot,U)},Y.abortSignal,jH)).artifact;if(C.bytes!==B.bytes||C.sha256!==B.sha256)throw new j("conflict","Prepared project asset disagrees with its published bytes.");let M=B.mediaType==="image/svg+xml"?{...await X(U),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:K.source.kind==="emoji"?{...await _(U),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await F(F5(V,"ffprobe"),new H8(o8(Y.application,V),Y.abortSignal),U),T={height:"pixelHeight"in M?M.pixelHeight:M.height,width:"pixelWidth"in M?M.pixelWidth:M.width},q={bytes:B.bytes,mediaType:B.mediaType,path:B.path,provenance:B.provenance,sha256:B.sha256},E;if(K.source.kind==="image"||K.source.kind==="svg")E={asset:q,kind:K.source.kind};else if(K.source.kind==="emoji")E={asset:q,kind:"emoji",provider:K.source.resolved.provider,selector:K.source.resolved.selector};else{if(M.durationUs===null||M.durationUs<=0)throw new j("invalid-data","Animated overlay media must report a positive duration.");let x=hV({mediaDurationUs:M.durationUs,outputDurationUs:N,playbackRate:K.source.playback.playbackRate,sourceInUs:K.source.playback.sourceInUs,sourceOutUs:K.source.playback.sourceOutUs}),b={audioEndUs:M.audioEndUs,audioStartUs:M.audioStartUs,audioStreamIndex:M.audioStreamIndex,endBehavior:K.source.playback.endBehavior,playbackRate:K.source.playback.playbackRate,streamStartUs:M.videoStartUs,videoStreamIndex:M.videoStreamIndex,...x};if(K.source.kind==="gif")E={asset:q,audioPolicy:{kind:"mute"},kind:"gif",playback:b};else{if(K.source.audioPolicy.kind!=="mute"&&!M.hasAudio)throw new j("conflict","The selected video overlay audio policy requires an audio stream.");E={asset:q,audioPolicy:K.source.audioPolicy,kind:"video",playback:b}}}let A=z5.parse({...K.layout,coordinateSpace:"output-pixels",intrinsicSize:T,overlayId:Bg0(K,E,T),range:K.range,source:E}),k=dh.parse({artifact:C,createdAt:Y.application.clock.now().toISOString(),exactInputSha256:g(K),ffprobeVersion:W.length===0?null:t9(V,"ffprobe"),kind:"slopcamera.local-overlay-preparation-receipt",operationSha256:g(A),overlayId:A.overlayId,projectGenerationSha256:G.generation.generationSha256,projectId:G.project.projectId,schemaVersion:1}),P=await T6({context:Y,receipt:k,workspace:w}),I=EJ.parse({artifact:C,created:B.created,operation:A,receipt:P});return await u5(Y,{inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",outputSchemaId:"slopcamera.operation.media.overlay.output/v1",version:1},I),I}finally{await w.dispose()}}},outputSchema:EJ,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:(Y)=>Y.receipt.path,summarize:(Y)=>({fields:{bytes:Y.artifact.bytes,created:Y.created,kind:Y.operation.source.kind,overlayId:Y.operation.overlayId,receipt:Y.receipt.path,sha256:Y.artifact.sha256},kind:"media.overlay"}),version:1}}var q80=zg0();var aA=2097152,tA=134217728,nh=536870912,sh=["ffmpeg","ffprobe","html-browser"],Rg0=n4.union([yV,n4.strictObject({path:z0}),E0]),kg0=n4.union([yV,E0]),qg0=n4.union([f5,gj]),Eg0=RQ.omit({bytes:!0,sha256:!0}).extend({artifact:qg0}).strict(),Pg0=RQ.extend({artifact:E0}).strict(),fO=n4.strictObject({canvas:TX,capabilityBindings:s4.optional(),document:Rg0,identityKey:n4.string().min(1).max(128).optional(),layout:uh,libraries:uZ.default([]),parameters:AJ.default({}),project:V2,range:u0,resources:n4.array(Eg0).max(64).default([]),seed:n4.number().int().min(0).max(4294967295).default(0),timing:I3}),rh=fO.omit({document:!0,resources:!0}).extend({document:kg0,resources:n4.array(Pg0).max(64)}).strict(),oh=n4.strictObject({artifact:E0,browserVersion:n4.string().min(1).max(512),createdAt:n4.string().datetime({offset:!0}),executionIntegrity:e9.optional(),exactInputSha256:v,ffmpegVersion:n4.string().min(1).max(512),ffprobeVersion:n4.string().min(1).max(512),frameCount:n4.number().int().safe().positive(),kind:n4.union([n4.literal("slopcamera.html-overlay-preparation-receipt"),n4.literal("studio.html-overlay-preparation-receipt")]),libraryLocks:_h,libraryLocksSha256:v,operationSha256:v,overlayId:n4.string().min(1).max(128),projectGenerationSha256:v,projectId:V2,schemaVersion:n4.literal(1)}),P80=EJ;function Ig0($){if(!("mediaType"in $.artifact))return $.artifact;if($.artifact.mediaType!==$.mediaType)throw new j("invalid-data",`HTML overlay resource ${$.name} declares ${$.mediaType} but its generated artifact is ${$.artifact.mediaType}.`);return E0.parse({bytes:$.artifact.bytes,path:$.artifact.path,sha256:$.artifact.sha256})}async function bg0($,Q,Z){if("html"in Q)return Q;return(await o1($,Q,Z,aA)).artifact}function Sg0($,Q){return J3(F3($),Q).reduce((Z,_)=>Z+_.output.endUs-_.output.startUs,0)}async function ih($,Q,Z){let _=fO.parse(Q),[X,F,J]=await Promise.all([bg0($,_.document,Z),Promise.all(_.resources.map(async(K)=>({...K,artifact:(await o1($,Ig0(K),Z,tA)).artifact}))),B5($,sh,_.capabilityBindings)]),Y=cZ.parse(F.map(({artifact:K,...W})=>({...W,bytes:K.bytes,sha256:K.sha256}))),H=new Map(F.map((K)=>[K.name,K.artifact]));return rh.parse({..._,capabilityBindings:J,document:X,resources:Y.map((K)=>({...K,artifact:H.get(K.name)}))})}function fg0($){let Q;try{Q=new TextDecoder("utf-8",{fatal:!0}).decode($)}catch{throw new j("invalid-data","The HTML overlay document must be valid UTF-8.")}if(Q.trim()==="")throw new j("invalid-data","The HTML overlay document is empty.");return Q}async function yg0($,Q){let Z=await Mg0($,E80.O_RDONLY|(E80.O_NOFOLLOW??0));try{let _=await Z.stat();if(!_.isFile()||_.size<=0)throw new j("invalid-data","Rendered HTML overlay is empty.");let X=Ug0("sha256"),F=Buffer.allocUnsafe(1048576),J=0;while(J<_.size){a(Q);let H=await Z.read(F,0,Math.min(F.byteLength,_.size-J),J);if(H.bytesRead===0)break;X.update(F.subarray(0,H.bytesRead)),J+=H.bytesRead}let Y=await Z.stat();if(J!==_.size||Y.dev!==_.dev||Y.ino!==_.ino||Y.size!==_.size||Y.mtimeMs!==_.mtimeMs||Y.ctimeMs!==_.ctimeMs)throw new j("conflict","Rendered HTML overlay changed while it was being verified.");return X.digest("hex")}finally{await Z.close()}}var xg0=n4.object({streams:n4.array(n4.object({codec_name:n4.string(),height:n4.number().int().positive(),pix_fmt:n4.string(),width:n4.number().int().positive()})).min(1)});async function hg0($,Q,Z,_,X){let F=await new H8(o8($,Q),X).run([F5(Q,"ffprobe"),"-v","error","-select_streams","v:0","-show_entries","stream=codec_name,pix_fmt,width,height","-of","json",Z],{maxOutputBytes:65536,stdin:"ignore",timeoutMs:30000});if(F.exitCode!==0)throw new j("invalid-data","Rendered HTML overlay could not be inspected as an alpha video.");let J;try{J=JSON.parse(F.stdout)}catch{throw new j("invalid-data","Rendered HTML overlay inspection returned invalid JSON.")}let Y=xg0.parse(J).streams[0];if(Y.codec_name!=="qtrle"||Y.pix_fmt!=="argb"||Y.width!==_.width||Y.height!==_.height)throw new j("invalid-data","Rendered HTML overlay must be a canvas-sized qtrle/argb alpha video.",{stream:Y})}function vg0($,Q,Z){return`overlay_${g({assetSha256:Z,authoring:Q,domain:"studio.media-html-overlay-operation/v1",identityKey:$.identityKey??null,layout:$.layout,project:$.project,range:$.range}).slice(0,32)}`}function ah($={}){let Q=$.ingest??F80,Z=$.probe??xZ,_=$.bindBrowserRuntime??F$,X=$.toolVersion??vV;return{inputSchema:fO,inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",lifecycle:{kind:"local-artifact",execute:async(F,J)=>{a(F.abortSignal);let Y=await ih(F.application,J,F.abortSignal);await a9(F,F.application,Y.capabilityBindings,sh);let H=Y.capabilityBindings??await MX(F.application,sh),K=F.application.htmlOverlayRenderer;if(K===void 0)throw new j("unavailable","This Slopcamera host does not provide an HTML-overlay browser renderer.");let W=await o2(F.application,Y.project);if(n8(F.expectedProjectGeneration,W.generation),Y.range.endUs>W.plan.timelineDurationUs)throw new j("usage","HTML overlay range exceeds the project timeline.");let V=Sg0(W.plan,Y.range);if(V<=0)throw new j("conflict","HTML overlay range has no visible kept output time.");if(Y.timing.durationUs!==V)throw new j("conflict","HTML overlay timing duration must equal the range's visible output duration.",{actualDurationUs:Y.timing.durationUs,expectedDurationUs:V});let[G,N]=await Promise.all(["html"in Y.document?Promise.resolve(Y.document.html):U4(F.application,Y.document,F.abortSignal,aA).then((w)=>fg0(w.data)),Promise.all(Y.resources.map(async(w)=>({...w,absolutePath:(await o1(F.application,w.artifact,F.abortSignal,tA)).absolutePath})))]),D=kQ.parse({canvas:Y.canvas,html:G,kind:"slopcamera.html-overlay",libraries:Y.libraries,parameters:Y.parameters,resources:N.map((w)=>({bytes:w.bytes,mediaType:w.mediaType,name:w.name,sha256:w.sha256,...w.transport===void 0?{}:{transport:w.transport},urlPath:w.urlPath})),schemaVersion:1,seed:Y.seed,timing:Y.timing}),L=await Q5(F),O=await Cg0(ph(L.path,"html-overlay-"));try{let w=await _(l5(H,"html-browser"),F.abortSignal),B=$6(D,w).integrity,z=await K.renderFrames({authoring:D,browserRuntime:w,outputDirectory:O,resources:N},F.abortSignal),U=e9.parse(z.executionIntegrity);if(g(U)!==g(B))throw new j("conflict","HTML-overlay renderer returned integrity evidence that does not match the planned browser execution.");let C=CO.parse(z.libraryLocks),M=D.libraries.map(lZ);if(g(C)!==g(M))throw new j("conflict","HTML-overlay renderer returned library locks that do not exactly match the authoring selection.");let T=b6(D.timing);if(z.frameCount!==T)throw new j("conflict","HTML-overlay renderer returned an unexpected frame count.");let q=ph(O,"overlay.mov"),E=[F5(H,"ffmpeg"),"-hide_banner","-loglevel","error","-nostdin","-n","-framerate",String(D.timing.fps),"-start_number","0","-i",z.framePattern,"-frames:v",String(z.frameCount),"-an","-c:v","qtrle","-pix_fmt","argb","-movflags","+faststart",q],A=await new H8(o8(F.application,H),F.abortSignal).run(E,{cwd:O,maxOutputBytes:1048576,stdin:"ignore",timeoutMs:3600000});if(A.exitCode!==0)throw new j("invalid-data",`FFmpeg could not encode the HTML overlay: ${A.stderr.slice(0,2000)}`);await hg0(F.application,H,q,D.canvas,F.abortSignal);let k=await yg0(q,F.abortSignal);await F.workflow?.beforePublication(),a(F.abortSignal);let P=await Q(W.openProject.directory.path,{command:E,generator:"slopcamera-html-overlay",generatorVersion:X,path:q,sourceSha256:k}),I=ph(W.openProject.directory.path,P.path),x=(await o1(F.application,{path:Tg0(F.application.paths.repositoryRoot,I)},F.abortSignal,nh)).artifact,b=await Z(F5(H,"ffprobe"),new H8(o8(F.application,H),F.abortSignal),I);if(b.durationUs===null||b.durationUs<=0||b.hasAudio||b.pixelWidth!==D.canvas.width||b.pixelHeight!==D.canvas.height)throw new j("invalid-data","Generated HTML overlay has invalid duration, dimensions, or audio streams.");let y=hV({mediaDurationUs:b.durationUs,outputDurationUs:V,playbackRate:1,sourceInUs:0,sourceOutUs:void 0}),r={asset:{bytes:P.bytes,mediaType:P.mediaType,path:P.path,provenance:P.provenance,sha256:P.sha256},audioPolicy:{kind:"mute"},kind:"video",playback:{audioEndUs:null,audioStartUs:0,audioStreamIndex:null,endBehavior:"hide",playbackRate:1,streamStartUs:b.videoStartUs,videoStreamIndex:b.videoStreamIndex,...y}},m=z5.parse({...Y.layout,coordinateSpace:"output-pixels",intrinsicSize:{height:D.canvas.height,width:D.canvas.width},overlayId:vg0(Y,D,x.sha256),range:Y.range,source:r}),p=oh.parse({artifact:x,browserVersion:t9(H,"html-browser"),createdAt:F.application.clock.now().toISOString(),executionIntegrity:U,exactInputSha256:g(Y),ffmpegVersion:t9(H,"ffmpeg"),ffprobeVersion:t9(H,"ffprobe"),frameCount:z.frameCount,kind:"slopcamera.html-overlay-preparation-receipt",libraryLocks:C,libraryLocksSha256:g(C),operationSha256:g(m),overlayId:m.overlayId,projectGenerationSha256:W.generation.generationSha256,projectId:W.project.projectId,schemaVersion:1}),S=await T6({context:F,receipt:p,workspace:L}),i=EJ.parse({artifact:x,created:P.created,operation:m,receipt:S});return await u5(F,{inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",version:1},i),i}finally{await Ag0(O,{force:!0,recursive:!0}),await L.dispose()}}},outputSchema:EJ,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:(F)=>F.receipt.path,summarize:(F)=>({fields:{bytes:F.artifact.bytes,created:F.created,kind:"html",overlayId:F.operation.overlayId,receipt:F.receipt.path,sha256:F.artifact.sha256},kind:"media.html-overlay"}),version:1}}var HA1=ah();var mg0=["media.ingest","media.html-overlay","media.overlay","media.audio-effects","media.color-grade"],OA1=gg0.enum(mg0);async function I80($,Q,Z,_=new AbortController().signal){switch(Q){case"media.ingest":return await t50($,fV.parse(Z),_);case"media.overlay":return await ch($,DH.parse(Z),_);case"media.html-overlay":return await ih($,fO.parse(Z),_);case"media.audio-effects":return await p50($,bV.parse(Z),_);case"media.color-grade":return await r50($,SV.parse(Z),_)}}import{z as yO}from"zod";import{lstat as sg0,realpath as f80}from"fs/promises";import{isAbsolute as ng0,join as rg0,relative as og0,sep as ig0}from"path";import{z as nZ}from"zod";var eA=4096,th=4,ug0=16777216,eh=Object.freeze({maximumCount:64,maximumTotalPixels:67108864,maximumTotalSvgBytes:67108864});function b80($){let Q=1;while(Q<$)Q*=2;return Q}function lg0($){let Q=[],Z=0,_=[],X=0,F=0,J=0,Y=0,H=()=>{if(_.length===0)return;let K=b80(F+J),W=b80(Y),V=W*K;if(Q.length>=eh.maximumCount||Z+V>eh.maximumTotalPixels)throw RangeError("Generated caption sprites exceed the cumulative raster resource bound.");Q.push({cards:_,height:K,width:W}),Z+=V,_=[],X=0,F=0,J=0,Y=0};for(let K of $){let{intrinsicHeight:W,intrinsicWidth:V}=K.rendered;if(V>eA||W>eA)throw RangeError("A social caption card exceeds the sprite dimension bound.");if(X>0&&X+V>eA)X=0,F+=J+th,J=0;if(F>0&&F+W>eA)H();_.push({...K,x:X,y:F}),X+=V+th,J=Math.max(J,W),Y=Math.max(Y,X-th)}return H(),Q}function dg0($){let Q=$.indexOf(">");if(!$.startsWith("<svg ")||Q<0||!$.endsWith("</svg>"))throw TypeError("Social caption renderer returned an unsupported SVG document.");return $.slice(Q+1,-6)}function cg0($){let Q=$.cards.map((X)=>`<g transform="translate(${X.x} ${X.y})">${dg0(X.rendered.svg)}</g>`).join(""),Z=[`<svg xmlns="http://www.w3.org/2000/svg" width="${$.width}" height="${$.height}" viewBox="0 0 ${$.width} ${$.height}" fill="none">`,Q,`</svg>
1574
1574
  `].join(""),_=Buffer.byteLength(Z,"utf8");if(_>ug0)throw RangeError("A generated caption sprite exceeds the 16 MiB SVG bound.");return{bytes:_,contents:Z}}function pg0($){let Q=$.overlays.reduce((Z,_)=>Math.max(Z,_.operation.zIndex),-1);if(Q>=Number.MAX_SAFE_INTEGER)throw RangeError("Existing overlay z-index leaves no safe caption layer.");return Q+1}function S80($){let Q=_J($.plan),Z=v.parse($.sourceSha256),_=cI.parse($.style);if($.cues.length===0)throw TypeError("Captioned render planning requires at least one visible cue.");let X=$.cues.map((V)=>({cue:V,rendered:t00(V,Q.output)})),F=pg0(Q),J=[],Y=[],H=0;for(let[V,G]of lg0(X).entries()){let{bytes:N,contents:D}=cg0(G),L=H0(D);if(H+=N,H>eh.maximumTotalSvgBytes)throw RangeError("Generated caption sprites exceed the cumulative SVG byte bound.");let O=`renders/caption-assets/${L}.svg`,w=`overlay_caption_${g({domain:"slopcamera.social-caption-sprite/v1",sha256:L,sourceSha256:Z,spriteIndex:V,style:_}).slice(0,32)}`,B={asset:{bytes:N,mediaType:"image/svg+xml",path:O,provenance:{command:["slopcamera","caption",_],generator:"slopcamera-social-caption-sprite",generatorVersion:"1",kind:"generated",sourceSha256:Z},sha256:L},kind:"svg"};J.push({contents:D,path:O,sha256:L});for(let z of G.cards){let U={bottom:(G.height-z.y-z.rendered.intrinsicHeight)/G.height,kind:"normalized-insets",left:z.x/G.width,right:(G.width-z.x-z.rendered.intrinsicWidth)/G.width,top:z.y/G.height},C=z5.parse({anchor:"bottom",crop:U,entrance:{kind:"none"},exit:{kind:"none"},intrinsicSize:{height:G.height,width:G.width},opacity:1,overlayId:w,position:{x:0,y:-z.rendered.bottomSafeMargin},range:z.cue.projectRange,rotationDegrees:0,scale:1,size:{height:z.rendered.intrinsicHeight,kind:"pixels",width:z.rendered.intrinsicWidth},source:B,zIndex:F});Y.push({operation:C,outputRange:z.cue.outputRange,playbackOffsetUs:0,projectRange:z.cue.projectRange,visibleDurationUs:z.cue.outputRange.endUs-z.cue.outputRange.startUs})}}let K=iQ.parse({...Q,overlays:[...Q.overlays,...Y],planSha256:"0".repeat(64)}),W=_J(iQ.parse({...K,planSha256:Wy(K)}));return{artifacts:J,plan:W}}var ag0=268435456,y80=nZ.strictObject({background:nZ.string().regex(/^#[0-9a-fA-F]{8}$/u).optional(),frameRate:nZ.number().finite().positive().max(240).optional()}),tg0=y80.extend({captions:XW}).strict(),x80=nZ.strictObject({analysisId:XW.shape.analysisId,analysisPath:z0,analysisSha256:v,assetId:m$,placementId:K2,placementSyncSha256:v,streamId:O5,subjectIntegritySha256:v,wordCount:nZ.number().int().safe().positive().max(1e6)}),Zv=nZ.strictObject({eventsSha256:v,manifestSha256:v,placementId:K2,recordingId:b5}),$v=nZ.strictObject({metadataBindings:nZ.array(Zv).max(256).optional(),revision:Kx,settings:y80.optional()}).superRefine(($,Q)=>{if($.metadataBindings===void 0)return;for(let Z=0;Z<$.metadataBindings.length;Z+=1){let _=$.metadataBindings[Z],X=$.metadataBindings[Z-1];if(X!==void 0&&X.placementId.localeCompare(_.placementId)>=0)Q.addIssue({code:"custom",message:"Render metadata bindings must have unique sorted placement IDs.",path:["metadataBindings",Z,"placementId"]})}}),Qv=nZ.strictObject({captionBinding:x80.optional(),metadataBindings:nZ.array(Zv).max(256).optional(),revision:Kx,settings:tg0}).superRefine(($,Q)=>{if($.metadataBindings===void 0)return;for(let Z=0;Z<$.metadataBindings.length;Z+=1){let _=$.metadataBindings[Z],X=$.metadataBindings[Z-1];if(X!==void 0&&X.placementId.localeCompare(_.placementId)>=0)Q.addIssue({code:"custom",message:"Render metadata bindings must have unique sorted placement IDs.",path:["metadataBindings",Z,"placementId"]})}}),h80=V8;function eg0($){return g({...$,domain:"slopcamera.social-caption-source/v1"})}function $m0($,Q){let Z=og0($,Q);return Z===""||Z!==".."&&!Z.startsWith(`..${ig0}`)&&!ng0(Z)}async function gV($,Q){let Z;try{Z=await f80($.paths.projectRoot)}catch{throw new j("not-found","The project root does not exist.")}let _=rg0(Z,Q),X;try{X=await sg0(_)}catch{throw new j("not-found",`Project does not exist: ${Q}`)}if(X.isSymbolicLink()||!X.isDirectory())throw new j("unsafe-path",`Project must be a physical directory: ${Q}`);let F=await f80(_);if(!$m0(Z,F)||F===Z)throw new j("unsafe-path",`Project directory escapes the configured project root: ${Q}`);return F}function Qm0($){return P6.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 _v($,Q){try{return JSON.parse($)}catch{throw new j("invalid-data",`${Q} is not valid JSON.`)}}function Xv($){return new TextEncoder().encode($).byteLength}async function $T($,Q){let Z=Qm0(Q),_=await gV($,Z.projectId),X=y0(_),F=await X.readText(Z.artifact.path);if(Xv(F)!==Z.artifact.bytes||H0(F)!==Z.artifact.sha256)throw new j("conflict","Immutable project edit revision artifact failed its byte and SHA-256 identity.");let J=A9.parse(_v(F,"Project edit revision artifact"));if(F!==`${R(J)}
1575
1575
  `)throw new j("conflict","Immutable project edit revision artifact is not its canonical document.");if(J.project.projectId!==Z.projectId||J.projectEditPlan.planId!==Z.planId||J.projectSha256!==Z.projectSha256||J.projectEditPlanSha256!==Z.projectEditPlanSha256||J.revisionSha256!==Z.revisionSha256||W2(J.project)!==Z.projectStructureSha256)throw new j("conflict","Immutable project edit revision reference does not match its frozen documents.");return{directory:_,document:J,fileSystem:X,reference:Z}}function v80($,Q,Z){return{...$?.background===void 0?{}:{background:$.background},...$?.frameRate===void 0?{}:{frameRate:$.frameRate},metadata:Z,pixelHeight:Q.pixelHeight,pixelWidth:Q.pixelWidth}}async function QT($,Q,Z){let _=new Set(Z.zooms.map((F)=>F.placementId));if((Z.effects.clicks.enabled||Z.effects.cursor.enabled||Z.effects.keystrokes.enabled||Z.effects.typedText.enabled)&&Z.effects.metadataPlacementId!==null)_.add(Z.effects.metadataPlacementId);let X=await Promise.all([..._].sort().map(async(F)=>{let J=Q.placements.find((W)=>W.placementId===F);if(J===void 0)throw new j("not-found",`Unknown project metadata placement: ${F}`);let Y=Q.assets.find((W)=>W.assetId===J.assetId);if(Y?.source.kind!=="recording")throw new j("conflict",`Placement ${J.placementId} is not backed by a Slopcamera recording with window and input metadata.`);let H=await q$($,Y.source.recordingId),K=await NX(H);return{binding:Zv.parse({eventsSha256:g(K),manifestSha256:g(H.manifest),placementId:J.placementId,recordingId:Y.source.recordingId}),context:{events:K,manifest:H.manifest,placementId:J.placementId}}}));return{bindings:X.map((F)=>F.binding),contexts:X.map((F)=>F.context)}}async function g80($,Q){let Z=XW.parse(Q),_=$.document.project,X=_.analyses.find((G)=>G.kind==="speech"&&G.analysisId===Z.analysisId);if(X===void 0||X.kind!=="speech")throw new j("not-found",`Unknown project speech analysis: ${Z.analysisId}`);let F=_.placements.find((G)=>G.placementId===Z.placementId);if(F===void 0)throw new j("not-found",`Unknown caption placement: ${Z.placementId}`);if(!F.enabled||F.assetId!==X.assetId)throw new j("conflict","Caption placement must be enabled and contain the analyzed audio asset.");if(F.audio.find((G)=>G.streamId===X.streamId)?.presentation.enabled!==!0)throw new j("conflict","Caption source audio must be enabled and audible on the selected placement.");let Y=_.assets.find((G)=>G.assetId===X.assetId),H=Y?.streams.find((G)=>G.streamId===X.streamId);if(Y===void 0||H?.kind!=="audio")throw new j("conflict","Caption speech analysis no longer identifies a project audio stream.");let K,W;try{K=await $.fileSystem.readText(X.path),W=v8.parse(_v(K,"Speech analysis artifact"))}catch(G){if(G instanceof j)throw G;throw new j("invalid-data",`Speech analysis ${X.analysisId} is unreadable or invalid.`)}if(K!==`${R(W)}
1576
1576
  `||H0(K)!==X.sha256||W.analysisId!==X.analysisId||W.subject.assetId!==X.assetId||W.subject.streamId!==X.streamId||W.durationUs!==Y.durationUs)throw new j("conflict",`Speech analysis ${X.analysisId} is stale or failed its exact identity check.`);let V=g({assetDurationUs:Y.durationUs,stream:H});if(W.subject.integritySha256!==V)throw new j("conflict",`Speech analysis ${X.analysisId} no longer matches its audio stream.`);if(W.result.status!=="transcribed"||W.result.words.length===0)throw new j("unsupported-plan","Caption export requires a speech analysis with timed words.");if(X.wordCount!==W.result.words.length||X.fillerCount!==W.result.fillers.length)throw new j("invalid-data",`Speech analysis reference ${X.analysisId} disagrees with its artifact counts.`);return{analysis:W,binding:x80.parse({analysisId:X.analysisId,analysisPath:X.path,analysisSha256:X.sha256,assetId:X.assetId,placementId:F.placementId,placementSyncSha256:y5(F),streamId:X.streamId,subjectIntegritySha256:V,wordCount:W.result.words.length})}}async function ZT($,Q){let Z=$v.parse(Q),_=await $T($,Z.revision),X=await QT($.paths.artifactRoot,_.document.project,_.document.projectEditPlan);return $v.parse({...Z,metadataBindings:X.bindings})}async function m80($,Q){let Z=Qv.parse(Q),_=await $T($,Z.revision),[X,F]=await Promise.all([QT($.paths.artifactRoot,_.document.project,_.document.projectEditPlan),g80(_,Z.settings.captions)]);return Qv.parse({...Z,captionBinding:F.binding,metadataBindings:X.bindings})}function Zm0($,Q,Z){return GO.parse({kind:"slopcamera.project-render-plan-document",outputGeometrySha256:Z.outputGeometrySha256,plan:_J($),projectEditPlanSha256:Q.projectEditPlanSha256,projectSha256:Q.projectSha256,renderPlanSha256:g($),revisionSha256:Q.revisionSha256,schemaVersion:1})}async function kX($,Q){let Z=V8.parse(Q),_=await gV($,Z.projectId),X=y0(_),F=await X.readText(Z.artifact.path);if(Xv(F)!==Z.artifact.bytes||H0(F)!==Z.artifact.sha256)throw new j("conflict","Immutable project render plan artifact failed its byte and SHA-256 identity.");let J=GO.parse(_v(F,"Project render plan artifact"));if(F!==`${R(J)}
@@ -2100,7 +2100,7 @@ ${H}${K}trailer
2100
2100
  startxref
2101
2101
  ${Y}
2102
2102
  %%EOF
2103
- `);let W=Buffer.from(F.join(""));if(W.length>33554432)throw Error("Drawing PDF exceeds output byte limit");return W}var vH="3.9.1";var wZ0="patent-line-art-v1",CR=1048576,Nm=9.070866141732283;class TR extends Error{constructor($){super(`Invalid drawing source: ${$}`);this.name="DrawingValidationError"}}function P2($){throw new TR($)}var AR=($)=>ws0("sha256").update($).digest("hex"),jZ0=($)=>Ts0($)?$:Rs0(new URL($,import.meta.url)),jm=[jZ0(AT),jZ0(SJ)],qs0={background:"#ffffff",foreground:"#000000",muted:"#000000",stroke:"#000000",tones:Object.fromEntries(["neutral","blue","orange","green","red","purple","yellow"].map(($)=>[$,{fill:"#ffffff",stroke:"#000000",text:"#000000"}]))},Es0={font:{family:"Nebula Sans",files:[{path:jm[0],weight:400},{path:jm[1],weight:700}]},theme:{light:qs0}},Ps0=($)=>$.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;");function Om($){if($!=="us-letter"&&$!=="a4")P2("paper must be us-letter or a4");let Q=$==="us-letter"?612:595.2755905511812,Z=$==="us-letter"?792:841.8897637795276,_={left:70.86614173228347,top:70.86614173228347,right:42.51968503937008,bottom:28.34645669291339};return{width:Q,height:Z,margins:_,numberingHeight:30,body:{x:_.left,y:_.top+30,width:Q-_.left-_.right,height:Z-_.top-_.bottom-60}}}function lX($,Q,Z){if(typeof $!=="object"||$===null||Array.isArray($))P2(`${Z} must be an object`);let _=$;for(let X of Object.keys(_))if(!Q.includes(X))P2(`${Z}.${X} is unsupported`);return _}function Is0($){let Q=lX($,["$schema","version","name","canvas","layout","shapes","edges"],"diagram"),Z=(_)=>{for(let X of Object.values(_)){if(typeof X==="number"&&(!Number.isFinite(X)||Math.abs(X)>1e4))P2("numeric drawing values must be finite and within 10000 points");if(typeof X==="string"&&X.length>1024)P2("drawing strings exceed the bounded text limit")}};if(Z(Q),Z(lX(Q.canvas,["width","height","padding"],"canvas")),Q.layout!==void 0)Z(lX(Q.layout,["type","direction","gap","align"],"layout"));if(!Array.isArray(Q.shapes)||Q.shapes.length<1||Q.shapes.length>100)P2("each sheet needs 1 to 100 shapes");for(let _ of Q.shapes){let X=lX(_,["id","type","x","y","tone","opacity","width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap","text","fontSize","fontFamily","weight","align","x2","y2"],"shape");Z(X);let F=["id","type","x","y","tone","opacity"],J=X.type==="text"?["text","width","fontSize","fontFamily","weight","align"]:X.type==="line"?["x2","y2","strokeWidth"]:["width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap"];if(lX(_,[...F,...J],"shape"),X.labelRows!==void 0){if(!Array.isArray(X.labelRows)||X.labelRows.length>4)P2("labelRows must be bounded");for(let Y of X.labelRows)Z(lX(Y,["text","fontSize","fontFamily","weight"],"label row"))}for(let Y of["label","text"])if(typeof X[Y]==="string"&&X[Y].length>500)P2("label exceeds text limit")}if(Q.edges!==void 0){if(!Array.isArray(Q.edges)||Q.edges.length>150)P2("at most 150 edges are supported");for(let _ of Q.edges)Z(lX(_,["id","from","to","label","tone","start","end","bend","arrowhead","startPosition","endPosition","labelFontSize","labelFontFamily","labelWeight","labelPosition","labelOffset"],"edge"))}}function RR($){let Q=lX($,["$schema","version","name","title","paper","sheets"],"drawing");if(Q.version!==1)P2("version must be 1");if(typeof Q.name!=="string"||Q.name.length>100||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(Q.name))P2("name must be a bounded lowercase hyphenated name");if(Q.paper!=="us-letter"&&Q.paper!=="a4")P2("paper must be us-letter or a4");if(Q.title!==void 0&&(typeof Q.title!=="string"||Q.title.length<1||Buffer.byteLength(Q.title)>1024||/[\u0000-\u001f]/u.test(Q.title)))P2("title must be a bounded metadata string");if(Q.$schema!==void 0&&typeof Q.$schema!=="string")P2("$schema must be a string");if(!Array.isArray(Q.sheets)||Q.sheets.length<1||Q.sheets.length>20)P2("sheets must contain 1 to 20 sheets");let Z=Q.sheets.map((X,F)=>{let J=lX(X,["figure","diagram"],`sheets[${F}]`);if(J.figure!==F+1)P2("figure numbers must be consecutive beginning at 1");Is0(J.diagram);let Y=aO(J.diagram),H=S6(Y);if(H.shapes.length<1||H.shapes.length>100||(H.edges?.length??0)>150)P2("each sheet needs 1 to 100 shapes and at most 150 edges");return{figure:F+1,diagram:Y}}),_={version:1,name:Q.name,paper:Q.paper,sheets:Z,...Q.title===void 0?{}:{title:Q.title},...Q.$schema===void 0?{}:{$schema:Q.$schema}};if(Buffer.byteLength(JSON.stringify(_))>CR)P2("source exceeds 1MiB byte limit");return _}function MR($){return new ks0($,{font:{fontFiles:jm,loadSystemFonts:!1,defaultFontFamily:"Nebula Sans"},logLevel:"off"})}function Dm($){let Q=$.getBBox();if(Q===void 0)P2("empty drawing ink");return{x:Q.x,y:Q.y,width:Q.width,height:Q.height}}function DZ0($,Q,Z){if($.x<Q.x-0.01||$.y<Q.y-0.01||$.x+$.width>Q.x+Q.width+0.01||$.y+$.height>Q.y+Q.height+0.01)P2(`${Z} ink extends beyond its bounds`)}async function OZ0($){return(await q9($,"light",Es0,{edgeStrokeWidth:1})).svg.replace('<rect width="100%" height="100%" fill="#ffffff"/>',"")}function BZ0($,Q,Z){let _=`<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><text x="100" y="500" font-family="Nebula Sans" font-size="${Q}" font-weight="${Z}">${Ps0($)}</text></svg>`;return Dm(MR(_)).height}function bs0($,Q){let Z=1/0,_=(X,F,J,Y)=>{if(X.length<1||X.length>500||!Array.from(X).every((H)=>/^[A-Z0-9 \n]$/u.test(H)||".,:;()[]/+=_*'!?%-".includes(H)))P2("visible labels must be uppercase ASCII letters, numbers, spaces, or supported punctuation; labels are never rewritten");if(Y!==void 0&&Y!=="default")P2("only the bundled default font is supported");if(!Number.isFinite(F)||F<=0||F>18)P2("authored font size must be positive and at most 18 points, below the 20 point sheet numbering");for(let H of new Set(X.match(/[A-Z0-9]/gu)??[])){let K=`${H}:${F}:${J}`,W=Q.get(K)??BZ0(H,F,J);if(Q.set(K,W),Q.size>4096)P2("glyph measurement limit exceeded");if(Z=Math.min(Z,W),W+0.001<Nm)P2(`glyph ${H} has ${W.toFixed(3)}pt ink height; minimum is ${Nm.toFixed(3)}pt (3.2mm)`)}};for(let X of $.shapes){if(X.tone!==void 0&&X.tone!=="neutral")P2("colored tones are unsupported; author monochrome relationships explicitly");if(X.opacity!==void 0&&X.opacity!==1)P2("transparency is unsupported");if(X.type==="rect"||X.type==="ellipse"){if(X.icon!==void 0)P2("icons are unsupported");if((X.strokeWidth??2)<0.5||(X.strokeWidth??2)>4)P2("stroke width must be 0.5 to 4 points");for(let F of fJ(X).rows)_(F.text,F.fontSize,F.weight,F.fontFamily)}else if(X.type==="text")_(X.text,X.fontSize??24,X.weight??500,X.fontFamily);else if((X.strokeWidth??3)<0.5||(X.strokeWidth??3)>4)P2("stroke width must be 0.5 to 4 points")}for(let X of $.edges??[]){if(X.tone!==void 0&&X.tone!=="neutral")P2("colored edge tones are unsupported");if(X.label!==void 0)_(X.label,X.labelFontSize??18,X.labelWeight??600,X.labelFontFamily)}return Z}async function kR($,Q){let Z=RR($),_=Q??AR(JSON.stringify(Z));if(!/^[a-f0-9]{64}$/u.test(_))P2("source SHA-256 is invalid");let X=Om(Z.paper),F=[],J=new Map,Y=1/0;for(let K of Z.sheets){let W=S6(K.diagram);if(W.canvas.width>X.body.width+0.001||W.canvas.height>X.body.height+0.001)P2(`figure ${K.figure} canvas exceeds ${X.body.width.toFixed(3)} by ${X.body.height.toFixed(3)}pt body; no automatic scaling is performed`);Y=Math.min(Y,bs0(W,J));let V=await OZ0(W);DZ0(Dm(MR(V)),{x:0,y:0,width:W.canvas.width,height:W.canvas.height},`figure ${K.figure}`);for(let B of W.shapes)if((B.type==="rect"||B.type==="ellipse")&&(B.label!==void 0||B.labelRows!==void 0)){let z=(B.strokeWidth??2)/2,U=await OZ0({...W,shapes:[B],edges:[]});DZ0(Dm(MR(U)),{x:B.x-z,y:B.y-z,width:B.width+z*2,height:B.height+z*2},`shape ${B.id} label`)}let G=V.replace(/^<svg[^>]*>/u,"").replace(/<\/svg>$/u,""),N=X.body.x+(X.body.width-W.canvas.width)/2,D=`${K.figure}/${Z.sheets.length}`,L=Z.sheets.length===1?"":`<text x="${X.width/2}" y="${X.height-X.margins.bottom-8}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">FIG. ${K.figure}</text>`,O=`<svg xmlns="http://www.w3.org/2000/svg" width="${X.width}" height="${X.height}" viewBox="0 0 ${X.width} ${X.height}"><rect width="100%" height="100%" fill="#ffffff"/><text x="${X.width/2}" y="${X.margins.top+21}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">${D}</text><g transform="translate(${N} ${X.body.y})">${G}</g>${L}</svg>`,w=MR(O).toString().replace(/width="[^"]+" height="[^"]+" viewBox="[^"]+"/u,`width="${X.width}pt" height="${X.height}pt" viewBox="0 0 ${X.width} ${X.height}"`);if(Buffer.byteLength(w)>2097152)P2("sheet SVG exceeds output byte limit");F.push({svg:w,width:X.width,height:X.height,figure:K.figure})}for(let K of"FIG0123456789")Y=Math.min(Y,BZ0(K,20,400));if(Y+0.001<Nm)P2("sheet numbering falls below minimum glyph height");let H={profile:wZ0,paper:Z.paper,sheetCount:Z.sheets.length,minGlyphHeightPt:Y,findings:[]};return{sheets:F,checks:H,pdf:NZ0(F,{title:Z.title??Z.name,sourceSha256:_,rendererVersion:vH})}}async function qR($){let Q=LZ0($);if(!Q.endsWith(".drawing.json"))P2("source filename must end in .drawing.json");let Z=await zs0(Q,Wm.O_RDONLY|Wm.O_NOFOLLOW|Wm.O_NONBLOCK),_;try{let F=await Z.stat();if(!F.isFile())P2("source must be a regular file");if(F.size>CR)P2("source exceeds 1MiB byte limit");let J=Buffer.alloc(CR+1),Y=0;while(Y<J.length){let H=await Z.read(J,Y,J.length-Y,Y);if(H.bytesRead===0)break;Y+=H.bytesRead}if(Y>CR)P2("source exceeds 1MiB byte limit");_=J.subarray(0,Y)}finally{await Z.close()}let X=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(_));return{absolutePath:Q,source:RR(X),sourceSha256:AR(_)}}async function zZ0($){let{source:Q,sourceSha256:Z}=await qR($.filePath);return(await kR(Q,Z)).checks}async function Gm($,Q){let Z=`${$}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await Ms0(Z,Q),await Us0(Z,$)}catch(_){throw await Cs0(Z,{force:!0}),_}}async function UZ0($){let{absolutePath:Q,source:Z,sourceSha256:_}=await qR($.filePath),X=await kR(Z,_),F=LZ0($.outDirectory??As0(Q)),J={source:Q,pdf:Vm(F,`${Z.name}.pdf`),sheets:X.sheets.map((H,K)=>Vm(F,`${Z.name}.sheet-${String(K+1).padStart(3,"0")}.svg`)),receipt:Vm(F,`${Z.name}.drawing-receipt.json`)},Y={version:1,profile:wZ0,rendererVersion:vH,sourceSha256:_,paper:Z.paper,minGlyphHeightPt:X.checks.minGlyphHeightPt,sheets:X.sheets.map((H)=>({figure:H.figure,widthPt:H.width,heightPt:H.height,sha256:AR(H.svg)})),pdfSha256:AR(X.pdf)};await Bs0(F,{recursive:!0});for(let[H,K]of X.sheets.entries())await Gm(J.sheets[H],K.svg);return await Gm(J.pdf,X.pdf),await Gm(J.receipt,`${JSON.stringify(Y,null,2)}
2103
+ `);let W=Buffer.from(F.join(""));if(W.length>33554432)throw Error("Drawing PDF exceeds output byte limit");return W}var vH="3.9.2";var wZ0="patent-line-art-v1",CR=1048576,Nm=9.070866141732283;class TR extends Error{constructor($){super(`Invalid drawing source: ${$}`);this.name="DrawingValidationError"}}function P2($){throw new TR($)}var AR=($)=>ws0("sha256").update($).digest("hex"),jZ0=($)=>Ts0($)?$:Rs0(new URL($,import.meta.url)),jm=[jZ0(AT),jZ0(SJ)],qs0={background:"#ffffff",foreground:"#000000",muted:"#000000",stroke:"#000000",tones:Object.fromEntries(["neutral","blue","orange","green","red","purple","yellow"].map(($)=>[$,{fill:"#ffffff",stroke:"#000000",text:"#000000"}]))},Es0={font:{family:"Nebula Sans",files:[{path:jm[0],weight:400},{path:jm[1],weight:700}]},theme:{light:qs0}},Ps0=($)=>$.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;");function Om($){if($!=="us-letter"&&$!=="a4")P2("paper must be us-letter or a4");let Q=$==="us-letter"?612:595.2755905511812,Z=$==="us-letter"?792:841.8897637795276,_={left:70.86614173228347,top:70.86614173228347,right:42.51968503937008,bottom:28.34645669291339};return{width:Q,height:Z,margins:_,numberingHeight:30,body:{x:_.left,y:_.top+30,width:Q-_.left-_.right,height:Z-_.top-_.bottom-60}}}function lX($,Q,Z){if(typeof $!=="object"||$===null||Array.isArray($))P2(`${Z} must be an object`);let _=$;for(let X of Object.keys(_))if(!Q.includes(X))P2(`${Z}.${X} is unsupported`);return _}function Is0($){let Q=lX($,["$schema","version","name","canvas","layout","shapes","edges"],"diagram"),Z=(_)=>{for(let X of Object.values(_)){if(typeof X==="number"&&(!Number.isFinite(X)||Math.abs(X)>1e4))P2("numeric drawing values must be finite and within 10000 points");if(typeof X==="string"&&X.length>1024)P2("drawing strings exceed the bounded text limit")}};if(Z(Q),Z(lX(Q.canvas,["width","height","padding"],"canvas")),Q.layout!==void 0)Z(lX(Q.layout,["type","direction","gap","align"],"layout"));if(!Array.isArray(Q.shapes)||Q.shapes.length<1||Q.shapes.length>100)P2("each sheet needs 1 to 100 shapes");for(let _ of Q.shapes){let X=lX(_,["id","type","x","y","tone","opacity","width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap","text","fontSize","fontFamily","weight","align","x2","y2"],"shape");Z(X);let F=["id","type","x","y","tone","opacity"],J=X.type==="text"?["text","width","fontSize","fontFamily","weight","align"]:X.type==="line"?["x2","y2","strokeWidth"]:["width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap"];if(lX(_,[...F,...J],"shape"),X.labelRows!==void 0){if(!Array.isArray(X.labelRows)||X.labelRows.length>4)P2("labelRows must be bounded");for(let Y of X.labelRows)Z(lX(Y,["text","fontSize","fontFamily","weight"],"label row"))}for(let Y of["label","text"])if(typeof X[Y]==="string"&&X[Y].length>500)P2("label exceeds text limit")}if(Q.edges!==void 0){if(!Array.isArray(Q.edges)||Q.edges.length>150)P2("at most 150 edges are supported");for(let _ of Q.edges)Z(lX(_,["id","from","to","label","tone","start","end","bend","arrowhead","startPosition","endPosition","labelFontSize","labelFontFamily","labelWeight","labelPosition","labelOffset"],"edge"))}}function RR($){let Q=lX($,["$schema","version","name","title","paper","sheets"],"drawing");if(Q.version!==1)P2("version must be 1");if(typeof Q.name!=="string"||Q.name.length>100||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(Q.name))P2("name must be a bounded lowercase hyphenated name");if(Q.paper!=="us-letter"&&Q.paper!=="a4")P2("paper must be us-letter or a4");if(Q.title!==void 0&&(typeof Q.title!=="string"||Q.title.length<1||Buffer.byteLength(Q.title)>1024||/[\u0000-\u001f]/u.test(Q.title)))P2("title must be a bounded metadata string");if(Q.$schema!==void 0&&typeof Q.$schema!=="string")P2("$schema must be a string");if(!Array.isArray(Q.sheets)||Q.sheets.length<1||Q.sheets.length>20)P2("sheets must contain 1 to 20 sheets");let Z=Q.sheets.map((X,F)=>{let J=lX(X,["figure","diagram"],`sheets[${F}]`);if(J.figure!==F+1)P2("figure numbers must be consecutive beginning at 1");Is0(J.diagram);let Y=aO(J.diagram),H=S6(Y);if(H.shapes.length<1||H.shapes.length>100||(H.edges?.length??0)>150)P2("each sheet needs 1 to 100 shapes and at most 150 edges");return{figure:F+1,diagram:Y}}),_={version:1,name:Q.name,paper:Q.paper,sheets:Z,...Q.title===void 0?{}:{title:Q.title},...Q.$schema===void 0?{}:{$schema:Q.$schema}};if(Buffer.byteLength(JSON.stringify(_))>CR)P2("source exceeds 1MiB byte limit");return _}function MR($){return new ks0($,{font:{fontFiles:jm,loadSystemFonts:!1,defaultFontFamily:"Nebula Sans"},logLevel:"off"})}function Dm($){let Q=$.getBBox();if(Q===void 0)P2("empty drawing ink");return{x:Q.x,y:Q.y,width:Q.width,height:Q.height}}function DZ0($,Q,Z){if($.x<Q.x-0.01||$.y<Q.y-0.01||$.x+$.width>Q.x+Q.width+0.01||$.y+$.height>Q.y+Q.height+0.01)P2(`${Z} ink extends beyond its bounds`)}async function OZ0($){return(await q9($,"light",Es0,{edgeStrokeWidth:1})).svg.replace('<rect width="100%" height="100%" fill="#ffffff"/>',"")}function BZ0($,Q,Z){let _=`<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><text x="100" y="500" font-family="Nebula Sans" font-size="${Q}" font-weight="${Z}">${Ps0($)}</text></svg>`;return Dm(MR(_)).height}function bs0($,Q){let Z=1/0,_=(X,F,J,Y)=>{if(X.length<1||X.length>500||!Array.from(X).every((H)=>/^[A-Z0-9 \n]$/u.test(H)||".,:;()[]/+=_*'!?%-".includes(H)))P2("visible labels must be uppercase ASCII letters, numbers, spaces, or supported punctuation; labels are never rewritten");if(Y!==void 0&&Y!=="default")P2("only the bundled default font is supported");if(!Number.isFinite(F)||F<=0||F>18)P2("authored font size must be positive and at most 18 points, below the 20 point sheet numbering");for(let H of new Set(X.match(/[A-Z0-9]/gu)??[])){let K=`${H}:${F}:${J}`,W=Q.get(K)??BZ0(H,F,J);if(Q.set(K,W),Q.size>4096)P2("glyph measurement limit exceeded");if(Z=Math.min(Z,W),W+0.001<Nm)P2(`glyph ${H} has ${W.toFixed(3)}pt ink height; minimum is ${Nm.toFixed(3)}pt (3.2mm)`)}};for(let X of $.shapes){if(X.tone!==void 0&&X.tone!=="neutral")P2("colored tones are unsupported; author monochrome relationships explicitly");if(X.opacity!==void 0&&X.opacity!==1)P2("transparency is unsupported");if(X.type==="rect"||X.type==="ellipse"){if(X.icon!==void 0)P2("icons are unsupported");if((X.strokeWidth??2)<0.5||(X.strokeWidth??2)>4)P2("stroke width must be 0.5 to 4 points");for(let F of fJ(X).rows)_(F.text,F.fontSize,F.weight,F.fontFamily)}else if(X.type==="text")_(X.text,X.fontSize??24,X.weight??500,X.fontFamily);else if((X.strokeWidth??3)<0.5||(X.strokeWidth??3)>4)P2("stroke width must be 0.5 to 4 points")}for(let X of $.edges??[]){if(X.tone!==void 0&&X.tone!=="neutral")P2("colored edge tones are unsupported");if(X.label!==void 0)_(X.label,X.labelFontSize??18,X.labelWeight??600,X.labelFontFamily)}return Z}async function kR($,Q){let Z=RR($),_=Q??AR(JSON.stringify(Z));if(!/^[a-f0-9]{64}$/u.test(_))P2("source SHA-256 is invalid");let X=Om(Z.paper),F=[],J=new Map,Y=1/0;for(let K of Z.sheets){let W=S6(K.diagram);if(W.canvas.width>X.body.width+0.001||W.canvas.height>X.body.height+0.001)P2(`figure ${K.figure} canvas exceeds ${X.body.width.toFixed(3)} by ${X.body.height.toFixed(3)}pt body; no automatic scaling is performed`);Y=Math.min(Y,bs0(W,J));let V=await OZ0(W);DZ0(Dm(MR(V)),{x:0,y:0,width:W.canvas.width,height:W.canvas.height},`figure ${K.figure}`);for(let B of W.shapes)if((B.type==="rect"||B.type==="ellipse")&&(B.label!==void 0||B.labelRows!==void 0)){let z=(B.strokeWidth??2)/2,U=await OZ0({...W,shapes:[B],edges:[]});DZ0(Dm(MR(U)),{x:B.x-z,y:B.y-z,width:B.width+z*2,height:B.height+z*2},`shape ${B.id} label`)}let G=V.replace(/^<svg[^>]*>/u,"").replace(/<\/svg>$/u,""),N=X.body.x+(X.body.width-W.canvas.width)/2,D=`${K.figure}/${Z.sheets.length}`,L=Z.sheets.length===1?"":`<text x="${X.width/2}" y="${X.height-X.margins.bottom-8}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">FIG. ${K.figure}</text>`,O=`<svg xmlns="http://www.w3.org/2000/svg" width="${X.width}" height="${X.height}" viewBox="0 0 ${X.width} ${X.height}"><rect width="100%" height="100%" fill="#ffffff"/><text x="${X.width/2}" y="${X.margins.top+21}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">${D}</text><g transform="translate(${N} ${X.body.y})">${G}</g>${L}</svg>`,w=MR(O).toString().replace(/width="[^"]+" height="[^"]+" viewBox="[^"]+"/u,`width="${X.width}pt" height="${X.height}pt" viewBox="0 0 ${X.width} ${X.height}"`);if(Buffer.byteLength(w)>2097152)P2("sheet SVG exceeds output byte limit");F.push({svg:w,width:X.width,height:X.height,figure:K.figure})}for(let K of"FIG0123456789")Y=Math.min(Y,BZ0(K,20,400));if(Y+0.001<Nm)P2("sheet numbering falls below minimum glyph height");let H={profile:wZ0,paper:Z.paper,sheetCount:Z.sheets.length,minGlyphHeightPt:Y,findings:[]};return{sheets:F,checks:H,pdf:NZ0(F,{title:Z.title??Z.name,sourceSha256:_,rendererVersion:vH})}}async function qR($){let Q=LZ0($);if(!Q.endsWith(".drawing.json"))P2("source filename must end in .drawing.json");let Z=await zs0(Q,Wm.O_RDONLY|Wm.O_NOFOLLOW|Wm.O_NONBLOCK),_;try{let F=await Z.stat();if(!F.isFile())P2("source must be a regular file");if(F.size>CR)P2("source exceeds 1MiB byte limit");let J=Buffer.alloc(CR+1),Y=0;while(Y<J.length){let H=await Z.read(J,Y,J.length-Y,Y);if(H.bytesRead===0)break;Y+=H.bytesRead}if(Y>CR)P2("source exceeds 1MiB byte limit");_=J.subarray(0,Y)}finally{await Z.close()}let X=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(_));return{absolutePath:Q,source:RR(X),sourceSha256:AR(_)}}async function zZ0($){let{source:Q,sourceSha256:Z}=await qR($.filePath);return(await kR(Q,Z)).checks}async function Gm($,Q){let Z=`${$}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await Ms0(Z,Q),await Us0(Z,$)}catch(_){throw await Cs0(Z,{force:!0}),_}}async function UZ0($){let{absolutePath:Q,source:Z,sourceSha256:_}=await qR($.filePath),X=await kR(Z,_),F=LZ0($.outDirectory??As0(Q)),J={source:Q,pdf:Vm(F,`${Z.name}.pdf`),sheets:X.sheets.map((H,K)=>Vm(F,`${Z.name}.sheet-${String(K+1).padStart(3,"0")}.svg`)),receipt:Vm(F,`${Z.name}.drawing-receipt.json`)},Y={version:1,profile:wZ0,rendererVersion:vH,sourceSha256:_,paper:Z.paper,minGlyphHeightPt:X.checks.minGlyphHeightPt,sheets:X.sheets.map((H)=>({figure:H.figure,widthPt:H.width,heightPt:H.height,sha256:AR(H.svg)})),pdfSha256:AR(X.pdf)};await Bs0(F,{recursive:!0});for(let[H,K]of X.sheets.entries())await Gm(J.sheets[H],K.svg);return await Gm(J.pdf,X.pdf),await Gm(J.receipt,`${JSON.stringify(Y,null,2)}
2104
2104
  `),{artifacts:J,checks:X.checks,receipt:Y}}function CZ0(){return{$schema:"https://raw.githubusercontent.com/hraness/slopcamera/main/schema/drawing.schema.json",version:1,name:"sensor-control",title:"Fictional sensor and controller drawings",paper:"us-letter",sheets:[{figure:1,diagram:{version:1,name:"sensor-system",canvas:{width:480,height:500},shapes:[{id:"sensor",type:"rect",x:105,y:40,width:280,height:100,radius:0,label:"SENSOR 100",labelFontSize:16},{id:"controller",type:"rect",x:105,y:280,width:280,height:100,radius:0,label:"CONTROLLER 200",labelFontSize:16}],edges:[{id:"signal",from:"sensor",to:"controller",label:"SIGNAL",labelFontSize:16}]}},{figure:2,diagram:{version:1,name:"control-flow",canvas:{width:480,height:500},shapes:[{id:"receive",type:"rect",x:105,y:40,width:280,height:100,radius:0,label:"RECEIVE SIGNAL 210",labelFontSize:16},{id:"actuate",type:"rect",x:105,y:280,width:280,height:100,radius:0,label:"SET OUTPUT 220",labelFontSize:16}],edges:[{id:"next",from:"receive",to:"actuate"}]}}]}}import{randomUUID as wr0}from"crypto";import{mkdir as Br0,readFile as zr0,rename as Ur0,rm as Cr0,writeFile as Mr0}from"fs/promises";import{dirname as U_0,join as RG,resolve as l3}from"path";import{canonicalJson as ls0,compileProgram as ds0,CONSTRUCTION_VERSION as cs0,CONSTRUCTION_VERSION_V1 as ps0,createRecipe as ss0,parseProgram as ns0,programDigest as rs0,RECIPE_VERSION as os0,renderConstruction as is0,replayRecipe as as0}from"@hraness/iconplace";import{COLLECTION_VERSION as ts0}from"@hraness/iconplace/collections";import{createSceneRecipe as EZ0,DEFAULT_SCENE_RENDER as IR,parseScene as TZ0,replaySceneRecipe as es0,renderScene as $n0,SCENE_RECIPE_VERSION as Qn0,SCENE_VERSION as Zn0,sceneFromComposition as _n0,solveScene as Xn0}from"@hraness/iconplace/scene";import{createHash as Ss0,randomUUID as fs0}from"crypto";import{constants as MZ0}from"fs";import{mkdir as ys0,open as AZ0,rename as xs0,rm as hs0,stat as vs0}from"fs/promises";import{dirname as gs0,join as ms0,resolve as us0}from"path";class Z6 extends Error{code;constructor($,Q){super(Q);this.name="BoundedFileError",this.code=$}}function Lm($){return typeof $==="object"&&$!==null&&"code"in $?String($.code):void 0}async function ER($,Q,Z){let _;try{_=await AZ0($,MZ0.O_RDONLY|MZ0.O_NONBLOCK)}catch(X){if(Lm(X)==="ENOENT")throw new Z6("SOURCE_NOT_FOUND",`${Z} does not exist.`);throw new Z6("SOURCE_UNREADABLE",`${Z} could not be opened.`)}try{let X=await _.stat();if(!X.isFile())throw new Z6("SOURCE_NOT_FILE",`${Z} must be a regular file.`);if(X.size>Q)throw new Z6("SOURCE_TOO_LARGE",`${Z} exceeds the ${String(Q)}-byte limit.`);let F=new Uint8Array(Q+1),J=0;for(;;){let{bytesRead:Y}=await _.read(F,J,F.length-J,J);if(Y===0)break;if(J+=Y,J>Q)throw new Z6("SOURCE_TOO_LARGE",`${Z} exceeds the ${String(Q)}-byte limit.`)}return F.slice(0,J)}finally{await _.close()}}function SL($,Q){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode($)}catch{throw new Z6("SOURCE_UNREADABLE",`${Q} must be UTF-8 text.`)}}function wG($){return Ss0("sha256").update($).digest("hex")}async function PR($,Q){let Z=gs0($);await ys0(Z,{recursive:!0});let _=ms0(Z,`.slopcamera-${fs0()}.tmp`);try{let X=await AZ0(_,"wx");try{await X.writeFile(Q),await X.sync()}finally{await X.close()}await xs0(_,$)}finally{await hs0(_,{force:!0}).catch(()=>{return})}}async function fL($){let Q=new Set,Z=new Set;for(let _ of $){if(_===void 0)continue;let X=us0(_);if(Q.has(X))return!0;Q.add(X);let F;try{let J=await vs0(X,{bigint:!0});F=`${String(J.dev)}:${String(J.ino)}`}catch(J){if(Lm(J)==="ENOENT"||Lm(J)==="ENOTDIR")continue;throw new Z6("SOURCE_UNREADABLE","A declared path could not be inspected.")}if(Z.has(F))return!0;Z.add(F)}return!1}var PZ0=Object.freeze({package:"@hraness/iconplace",version:"0.1.0"}),E5=Object.freeze({sourceBytes:1048576,outputBytes:4194304,sizeMin:16,sizeMax:1024,diagnostics:64,notes:32}),pJ=Object.freeze(["original","ink","earth","night"]),sJ=Object.freeze(["outline","sketch","pen","crosshatch","engraving","stipple","halftone","glyph","flat","shaded","figure","cutpaper","woodcut","offset"]),Fn0="outline";class L8 extends Error{code;constructor($,Q){super(Q);this.name="SlopcameraIconError",this.code=$}}function zG($){throw new L8("INVALID_ICON_SOURCE",$)}function dX($){throw new L8("INVALID_ICON_INPUT",$)}function BG($){let Z=[...$ instanceof Error?$.message:String($)].filter((_)=>{let X=_.codePointAt(0)??0;return X>=32&&X!==127}).join("");return Z.length>240?`${Z.slice(0,237)}...`:Z}function Jn0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Yn0($){let Q;try{Q=JSON.parse(SL($,"Icon source"))}catch(Z){if(Z instanceof Z6)throw Z;zG("Icon source is not valid JSON.")}if(!Jn0(Q)||typeof Q.version!=="string")zG("Icon source must be a JSON object with a version field.");return Q}function IZ0($){let Q=Yn0($),Z=Q.version;try{if(Z===Zn0)return{form:"scene",format:"scene",scene:TZ0(Q)};if(Z===ts0)return{form:"scene",format:"collection",scene:TZ0(_n0(Q))};if(Z===cs0||Z===ps0)return{form:"program",format:"program",drawing:ds0(ns0(Q))};if(Z===Qn0){let _=es0(Q);return{form:"scene",format:"scene-recipe",scene:_.recipe.scene,sources:_.recipe.sources,replay:{recipe:_.recipe,svg:_.svg,width:_.width,height:_.height,options:_.options,style:_.style,notes:_.notes}}}if(Z===os0){let _=as0(Q);return{form:"program",format:"program-recipe",drawing:_.drawing,replay:{svg:_.svg,style:_.style}}}}catch(_){zG(`Icon source was rejected: ${BG(_)}`)}return zG("Icon source version must be a scene, collection, construction program, or recipe version.")}function Hn0($){let{facts:Q}=$;return{regions:Q.regions,components:Q.components,apertures:Q.apertures,vertices:Q.vertices,inkArea:Q.inkArea,bounds:[Q.bounds[0],Q.bounds[1],Q.bounds[2],Q.bounds[3]]}}function bZ0($){return`${JSON.stringify(JSON.parse(ls0($)),null,2)}
2105
2105
  `}var Kn0=new Set(["svg","g","defs","clipPath","mask","title","desc","path","rect","circle","ellipse","line","polyline","polygon"]),Wn0=new Set(["xmlns","width","height","viewBox","role","id","d","fill","fill-rule","fill-opacity","clip-path","clip-rule","mask","opacity","stroke","stroke-width","stroke-linecap","stroke-linejoin","stroke-dasharray","stroke-opacity","stroke-miterlimit","transform","x","y","rx","ry","cx","cy","r","x1","y1","x2","y2","points","preserveAspectRatio"]);function Vn0($){if(Buffer.byteLength($,"utf8")>E5.outputBytes)throw new L8("UNSAFE_ICON_OUTPUT","Rendered SVG exceeds the output byte limit.");if(!$.startsWith("<svg ")||!$.trimEnd().endsWith("</svg>"))throw new L8("UNSAFE_ICON_OUTPUT","Rendered output is not a single SVG document.");if(/<!|<\?|&(?!(?:amp|lt|gt|quot|apos|#\d{1,7}|#x[0-9a-f]{1,6});)/iu.test($))throw new L8("UNSAFE_ICON_OUTPUT","Rendered SVG contains declarations or unknown entities.");let Q=new Set,Z=[];for(let _ of Nn0($)){if(!Kn0.has(_.name))throw new L8("UNSAFE_ICON_OUTPUT",`Rendered SVG contains a disallowed <${_.name}> element.`);for(let[X,F]of _.attributes){if(!Wn0.has(X))throw new L8("UNSAFE_ICON_OUTPUT",`Rendered SVG contains a disallowed ${X} attribute.`);if(X==="id")Q.add(F);Z.push(...jn0(F))}}for(let _ of Z)if(!/^#[A-Za-z0-9_-]+$/u.test(_)||!Q.has(_.slice(1)))throw new L8("UNSAFE_ICON_OUTPUT","Rendered SVG references a non-local resource.")}var wm=($)=>$===" "||$==="\t"||$===`
2106
2106
  `||$==="\r",RZ0=($)=>$!==void 0&&/^[A-Za-z]$/u.test($),kZ0=($)=>$!==void 0&&/^[\w:.-]$/u.test($),Gn0=($)=>$!==void 0&&!wm($)&&$!=="="&&$!=="/"&&$!==">";function Nn0($){let Q=()=>{throw new L8("UNSAFE_ICON_OUTPUT","Rendered SVG contains a malformed element.")},Z=[],_=$.indexOf("<");while(_!==-1){let X=_+1;if($[X]==="/"){if(X+=1,!RZ0($[X]))Q();while(kZ0($[X]))X+=1;while(wm($[X]))X+=1;if($[X]!==">")Q();_=$.indexOf("<",X+1);continue}if(!RZ0($[X]))Q();let F=X;while(kZ0($[X]))X+=1;let J=$.slice(F,X),Y=[];for(;;){let H=X;while(wm($[X]))X+=1;if($[X]==="/"&&$[X+1]===">"){X+=1;break}if($[X]===">")break;if(X===H)Q();let K=X;while(Gn0($[X]))X+=1;if(X===K||$[X]!=="="||$[X+1]!=='"')Q();let W=X+2,V=$.indexOf('"',W);if(V===-1)Q();let G=$.slice(W,V);if(G.includes("<"))Q();Y.push([$.slice(K,X),G]),X=V+1}Z.push({name:J,attributes:Y}),_=$.indexOf("<",X+1)}return Z}function jn0($){let Q=[],Z=$.indexOf("url(");while(Z!==-1){let _=$.indexOf(")",Z+4);if(_===-1)throw new L8("UNSAFE_ICON_OUTPUT","Rendered SVG references a non-local resource.");Q.push($.slice(Z+4,_)),Z=$.indexOf("url(",_+1)}return Q}function Dn0($){let Q=/^<svg\b[^>]*>/u.exec($)?.[0]??"",Z=Number(/\swidth="(\d+)"/u.exec(Q)?.[1]),_=Number(/\sheight="(\d+)"/u.exec(Q)?.[1]);if(!Number.isSafeInteger(Z)||!Number.isSafeInteger(_)||Z<1||_<1)throw new L8("UNSAFE_ICON_OUTPUT","Rendered SVG does not declare integer dimensions.");return{width:Z,height:_}}function qZ0($,Q){let Z=$??Q;if(!Number.isSafeInteger(Z)||Z<E5.sizeMin||Z>E5.sizeMax)dX(`size must be an integer from ${String(E5.sizeMin)} through ${String(E5.sizeMax)}.`);return Z}async function SZ0($){let Q=await ER($,E5.sourceBytes,"Icon source");return{bytes:Q,record:{path:$,sha256:wG(Q),bytes:Q.byteLength}}}async function Bm($,Q){let Z=Buffer.from(Q,"utf8");if(Z.byteLength>E5.outputBytes)throw new L8("UNSAFE_ICON_OUTPUT","Icon output exceeds the output byte limit.");return await PR($,Z),{path:$,sha256:wG(Z),bytes:Z.byteLength}}function zm($,Q,Z){if(!$.toLowerCase().endsWith(Q))dX(`${Z} must end in ${Q}.`)}async function bR($){if($.outputPath!==void 0){if(zm($.outputPath,".json","outputPath"),await fL([$.sourcePath,$.outputPath]))dX("outputPath must differ from sourcePath.")}let{bytes:Q,record:Z}=await SZ0($.sourcePath),_=IZ0(Q),X,F,J,Y,H,K;try{if(_.form==="scene"){let V=Xn0(_.scene,_.sources);X=V.scene,F=V.drawing,J=EZ0(V.scene,IR).digests.scene,H=V.scene.nodes.length,K=V.scene.title,Y=V.diagnostics.map((G)=>({code:G.code,message:BG(G.message),target:G.node}))}else X=_.drawing.program,F=_.drawing,J=rs0(_.drawing.program),H=_.drawing.program.parts.length,K=_.drawing.program.title,Y=_.drawing.issues.map((V)=>({code:V.code,message:BG(V.message),target:V.part??null}))}catch(V){if(V instanceof L8)throw V;zG(`Icon source could not be solved: ${BG(V)}`)}let W=$.outputPath===void 0?null:await Bm($.outputPath,bZ0(X));return{receiptVersion:1,operation:"slopcamera.icon.compose",engine:PZ0,source:{...Z,format:_.format},form:_.form,title:K,elementCount:H,digests:{document:J,geometry:F.digest},geometry:Hn0(F),diagnostics:Y.slice(0,E5.diagnostics),output:W}}async function SR($){if(zm($.outputPath,".svg","outputPath"),$.recipePath!==void 0)zm($.recipePath,".json","recipePath");if(await fL([$.sourcePath,$.outputPath,$.recipePath]))dX("sourcePath, outputPath and recipePath must name different files.");let{bytes:Q,record:Z}=await SZ0($.sourcePath),_=IZ0(Q),X=_.format==="scene-recipe"||_.format==="program-recipe";if(X&&($.size!==void 0||$.background!==void 0||$.palette!==void 0||$.language!==void 0))dX("A recipe fixes its render settings; omit size, background, palette and language.");if(_.form==="scene"&&$.language!==void 0)dX("language applies only to construction programs; scenes use their family's language.");if(_.form==="program"&&$.palette!==void 0)dX("palette applies only to scenes.");if($.palette!==void 0&&!pJ.includes($.palette))dX(`palette must be one of ${pJ.join(", ")}.`);if($.language!==void 0&&!sJ.includes($.language))dX(`language must be one of ${sJ.join(", ")}.`);let F,J,Y,H,K,W,V,G;try{if(_.form==="scene"){let L,O,w;if(_.replay!==void 0)({recipe:L,svg:F,width:J,height:Y,options:O,notes:V}=_.replay),w=_.replay.style.language;else{O={size:qZ0($.size,IR.size),background:$.background??IR.background,palette:$.palette??IR.palette};let B=$n0(_.scene,O);L=EZ0(_.scene,O,B.solution.sources,B.style),{svg:F,width:J,height:Y,notes:V}=B,w=B.style.language}H=L,K={document:L.digests.scene,geometry:L.digests.geometry,svg:L.digests.svg},W={size:O.size,background:O.background,palette:O.palette,language:w},G=_.scene.title}else{let L=_.replay?.style??{language:$.language??Fn0,outputPx:qZ0($.size,512),background:$.background??!1},O=_.replay??is0(_.drawing,L),w=ss0(_.drawing,L);F=O.svg,{width:J,height:Y}=Dn0(F),H=w,K={document:w.digests.program,geometry:w.digests.geometry,svg:w.digests.svg},W={size:L.outputPx??J,background:L.background??!1,palette:null,language:L.language},V="notes"in O?O.notes:[],G=_.drawing.program.title}}catch(L){if(L instanceof L8)throw L;zG(`Icon source could not be drawn: ${BG(L)}`)}Vn0(F);let N=await Bm($.outputPath,F),D=$.recipePath===void 0?null:await Bm($.recipePath,bZ0(H));return{receiptVersion:1,operation:"slopcamera.icon.render",engine:PZ0,source:{...Z,format:_.format},form:_.form,replayed:X,title:G,render:W,width:J,height:Y,digests:K,output:N,recipe:D,notes:V.slice(0,E5.notes).map(BG)}}import{beatGrid as On0,importMidi as Ln0}from"@hraness/soundfish/midi";import{compose as wn0,verify as fZ0}from"@hraness/soundfish/protocol";import{applyTemplate as Bn0}from"@hraness/soundfish/templates";var yZ0=Object.freeze({package:"@hraness/soundfish",version:"0.7.0"}),H$=Object.freeze({sourceBytes:1048576,outputBytes:4194304,sections:512,warnings:64,maxTimeUs:3600000000,minBpm:20,maxBpm:400,minBeatsPerBar:1,maxBeatsPerBar:32}),pX=Object.freeze(["compose","song","json","midi"]);class gH extends Error{code;constructor($,Q){super(Q);this.name="SlopcameraSoundtrackError",this.code=$}}function UG($){throw new gH("INVALID_SOUNDTRACK_SOURCE",$)}function fR($){throw new gH("INVALID_SOUNDTRACK_INPUT",$)}function cX($,Q=240){let Z=[...$].filter((_)=>{let X=_.codePointAt(0)??0;return X>=32&&X!==127}).join("");return Z.length>Q?`${Z.slice(0,Q-3)}...`:Z}function CG($,Q){return UG(`${Q}: ${cX($.error.code,64)}: ${cX($.error.message)}`)}function zn0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function xZ0($){return $.length>=4&&$[0]===77&&$[1]===84&&$[2]===104&&$[3]===100}function Un0($){if(xZ0($))return"midi";let Q=SL($,"Soundtrack source");if(Q.trimStart().startsWith("{"))return"json";return/^[ \t]*section[ \t]/mu.test(Q)?"song":"compose"}async function MG($,Q){try{return await $()}catch(Z){if(Z instanceof gH||Z instanceof Z6)throw Z;return UG(`${Q}: ${cX(Z instanceof Error?Z.message:String(Z))}`)}}async function Cn0($,Q){let Z=Q??Un0($);if(Z==="midi"){if(!xZ0($))UG("A MIDI source must be a Standard MIDI file.");let F=await MG(async()=>await Ln0($.slice()),"MIDI import failed");if(!F.ok)CG(F,"MIDI import failed");return{format:Z,document:F.document,warnings:F.warnings.map((J)=>({code:cX(J.code,64),message:cX(J.message)}))}}let _=SL($,"Soundtrack source");if(Z==="json"){let F;try{F=JSON.parse(_)}catch{UG("Soundtrack JSON is not valid JSON.")}if(!zn0(F))UG("Soundtrack JSON must be an object.");return{format:Z,document:F,warnings:[]}}if(Z==="song"){let F=await MG(async()=>await Bn0("songs/source",{sources:[{kind:"songs",name:"source",text:_}]}),"Song compose failed");if(!F.ok)CG(F,"Song compose failed");if(!("document"in F))UG("Song compose returned no document.");return{format:Z,document:F.document,warnings:F.warnings.map((J)=>({code:"song",message:cX(J)}))}}let X=await MG(async()=>await wn0(_),"Compose failed");if(!X.ok)CG(X,"Compose failed");return{format:Z,document:X.document,warnings:[]}}async function hZ0($,Q){if(Q!==void 0&&!pX.includes(Q))fR(`format must be one of ${pX.join(", ")}.`);let Z=await ER($,H$.sourceBytes,"Soundtrack source"),_=await Cn0(Z,Q);return{score:_,source:{path:$,sha256:wG(Z),bytes:Z.byteLength,format:_.format}}}async function vZ0($){let Q=await MG(async()=>await On0($),"Beat grid failed");if(!Q.ok)CG(Q,"Beat grid failed");return Q}function Q_($){throw new gH("SOUNDTRACK_OUT_OF_RANGE",$)}function Um($,Q){return Math.round($*60000000/Q)}function gZ0($){let Q=H$;if(!Number.isFinite($.bpm)||$.bpm<Q.minBpm||$.bpm>Q.maxBpm)Q_(`Tempo ${String($.bpm)} BPM is outside ${String(Q.minBpm)}\u2013${String(Q.maxBpm)} BPM.`);if(!Number.isSafeInteger($.beatsPerBar)||$.beatsPerBar<Q.minBeatsPerBar||$.beatsPerBar>Q.maxBeatsPerBar)Q_(`Meter of ${String($.beatsPerBar)} beats per bar is outside ${String(Q.minBeatsPerBar)}\u2013${String(Q.maxBeatsPerBar)}.`);if(!Number.isFinite($.secondsPerBeat)||Math.abs($.secondsPerBeat-60/$.bpm)>0.000001)Q_("The beat grid's beat length disagrees with its tempo.");return{bpm:$.bpm,beatsPerBar:$.beatsPerBar}}function mZ0($,Q){if(!Number.isSafeInteger($.beats)||$.beats<1)Q_("The score has no beats.");let Z=Um($.beats,Q);if(Z>H$.maxTimeUs)Q_("The score is longer than the one-hour timeline bound.");return Z}async function uZ0($,Q){let Z=Buffer.from(`${JSON.stringify(Q,null,2)}
@@ -5632,7 +5632,7 @@ export default defineWorkflow({
5632
5632
  `)}async function ME($,Q){let Z=k1(RE($),`.replace-${TE()}`);await MY(Z,Q);try{await l61(Z,$),await p6(RE($))}catch(_){throw await CK(Z).catch(()=>{return}),_}}async function EE($,Q=sW0){if(!Number.isSafeInteger(Q)||Q<0||Q>sW0)throw new j("invalid-data","Run artifact byte bound is invalid.");let Z;try{Z=await x$($)}catch(X){if(i3(X,"ENOENT"))throw new j("not-found",`Run artifact does not exist: ${$}`);throw X}if(!kc(Z)||!Number.isSafeInteger(Z.size)||Z.size<0||Z.size>Q)throw new j("unsafe-path",`Run artifact must be a bounded private physical file: ${$}`);let _=await IE($,a3.O_NOFOLLOW|a3.O_RDONLY|a3.O_NONBLOCK);try{let X=TY(Z),F,J,Y=Buffer.alloc(Z.size+1);for(let H of[1,2]){let K=TY(await _.stat());if(!SN(X,K)||F!==void 0&&!MK(F,K))throw new j("conflict",`Run artifact changed before read: ${$}`);let W=0;while(W<Y.byteLength){let{bytesRead:L}=await _.read(Y,W,Y.byteLength-W,W);if(L===0)break;W+=L}let V=TY(await _.stat()),G=TY(await x$($)),N=VB("sha256").update(Y.subarray(0,W)).digest("hex");if(!SN(K,V)||!SN(V,G)||W!==K.size||J!==void 0&&J!==N)throw new j("conflict",`Run artifact changed during read: ${$}`);if(MK(K,V)&&MK(V,G)&&(H===2||MK(X,K)))return Y.subarray(0,W);if(H===2)throw new j("conflict",`Run artifact changed during read: ${$}`);F=G,J=N}throw new j("conflict",`Run artifact changed during read: ${$}`)}finally{await _.close()}}function YV0($,Q){try{return new TextDecoder("utf-8",{fatal:!0}).decode($)}catch(Z){throw new j("invalid-data",`Run artifact is not UTF-8 (${Q}): ${String(Z)}`)}}async function WQ1($,Q){let Z=await EE($);return Q?.set($,VB("sha256").update(Z).digest("hex")),YV0(Z,$)}async function HV0($,Q){try{return JSON.parse(await WQ1($,Q))}catch(Z){if(Z instanceof j)throw Z;throw new j("invalid-data",`Run artifact is not JSON: ${$}`)}}async function N$($,Q,Z){try{return Q.parse(await HV0($,Z))}catch(_){if(_ instanceof j)throw _;throw new j("invalid-data",`Run artifact failed validation (${$}): ${String(_)}`)}}function KV0($){let Q=$.lastIndexOf(10);return Q<0?$.subarray(0,0):$.subarray(0,Q+1)}function WV0($,Q,Z){let _=KV0($);if(_.byteLength===0)return Object.freeze([]);let X=YV0(_,Q).split(`
5633
5633
  `);if(X.pop(),X.length>kE)throw new j("invalid-data",`Run journal exceeds ${String(kE)} entries: ${Q}`);return Object.freeze(X.map((F,J)=>{try{return Z.parse(JSON.parse(F))}catch(Y){throw new j("invalid-data",`Invalid run journal entry ${String(J+1)} (${Q}): ${String(Y)}`)}}))}async function Ac($,Q){return WV0(await EE($,AE),$,Q)}async function _V0($,Q,Z,_,X,F){let J=await x$($);if(!kc(J)||J.size>AE)throw new j("unsafe-path",`Run journal must be a bounded private physical file: ${$}`);let Y=await IE($,a3.O_NOFOLLOW|a3.O_RDWR);try{let H=await Y.stat();if(!AY(y9(J),y9(H)))throw new j("conflict",`Run journal changed before append: ${$}`);let K=F!==void 0&&MK(F.snapshot,TY(J))&&MK(F.snapshot,TY(H)),W,V,G;if(K)W=H.size,V=F.cursor,G=F.entryCount;else{let B=new Uint8Array(await Y.readFile());if(B.byteLength>AE)throw new j("invalid-data",`Run journal exceeds its byte limit: ${$}`);let z=KV0(B),U=WV0(B,$,Q);if(V=Z(U),G=U.length,W=z.byteLength,B.byteLength!==W)await Y.truncate(W),await Y.sync()}if(G>=kE)throw new j("conflict",`Run journal already contains ${String(kE)} entries.`);let N=_({cursor:V,entryCount:G}),D=Q.parse(N.entry),L=new TextEncoder().encode(`${R(D)}
5634
5634
  `);if(L.byteLength>p61)throw new j("invalid-data","Run journal entry exceeds its byte limit.");if(W+L.byteLength>AE)throw new j("conflict","Run journal has reached its byte limit.");let O=0;while(O<L.byteLength){let B=await Y.write(L,O,L.byteLength-O,W+O);if(B.bytesWritten<1)throw new j("unavailable",`Run journal append made no progress: ${$}`);O+=B.bytesWritten}await Y.sync();let w=await Y.stat();if(!_Q1(y9(H),y9(w))||w.size!==W+L.byteLength)throw new j("conflict",`Run journal changed during append: ${$}`);return{result:N.result,state:{cursor:X(V,D),entryCount:G+1,snapshot:TY(w)}}}finally{await Y.close()}}function XV0($,Q){let Z=0;for(let[_,X]of $.entries()){if(X.runId!==Q||X.sequence!==_+1)throw new j("invalid-data",`Run event sequence is inconsistent for ${Q}.`);if(X.fenceGeneration<Z)throw new j("invalid-data",`Run event fence generation regressed for ${Q}.`);Z=X.fenceGeneration}return{lastFenceGeneration:Z,lastSequence:$.at(-1)?.sequence??0}}function Tc($,Q,Z){let _=new Set;for(let X of $){if(X.runId!==Q||X.graphPlanSha256!==Z)throw new j("invalid-data",`Run grant identity is inconsistent for ${Q}.`);if(_.has(X.grantId))throw new j("invalid-data",`Run grant ID is duplicated: ${X.grantId}`);_.add(X.grantId)}return{grantIds:_}}function Rc($){return{cancelled:$.filter((Q)=>Q.status==="cancelled").length,completed:$.filter((Q)=>Q.status==="completed").length,failed:$.filter((Q)=>Q.status==="failed"||Q.status==="incompatible"||Q.status==="ambiguous").length,pending:$.filter((Q)=>Q.status==="pending"||Q.status==="ready"||Q.status==="preparing"||Q.status==="running"||Q.status==="approval-required"||Q.status==="ambiguous-code").length,skipped:$.filter((Q)=>Q.status==="skipped").length}}function VQ1($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.hasOwn($,"$ref")}function GQ1($){return Array.isArray($)}function PE($,Q,Z){if(VQ1($)){let X=Q.get($.$ref.nodeKey);if(X?.status!=="completed"||X.output===void 0)return;return Z[X.nodeKey]=X.output.digestSha256,KB($,X.output.value)}if(GQ1($)){let X=[];for(let F of $){let J=PE(F,Q,Z);if(J===void 0)return;X.push(J)}return X}let _={};for(let[X,F]of Object.entries($).sort(([J],[Y])=>J.localeCompare(Y))){let J=PE(F,Q,Z);if(J===void 0)return;_[X]=J}return _}function FV0($){if($.some((Z)=>Z.status==="approval-required"))return"approval-required";if($.some((Z)=>Z.status==="ambiguous-code"))return"ambiguous-code";if($.some((Z)=>Z.status==="pending"||Z.status==="ready"||Z.status==="preparing"||Z.status==="running"))return"running";let Q=Rc($);if(Q.cancelled>0)return"cancelled";if(Q.failed===0&&Q.skipped===0&&Q.completed===$.length)return"completed";if($.some((Z)=>Z.status==="incompatible")&&Q.completed===0)return"incompatible";if(Q.completed>0)return"partial";return"failed"}class qc{#$=new Map;#Q=0;#_;#F;constructor($){let Q=$.claimSessionCacheBudgetBytes??Uc;if(!Number.isSafeInteger(Q)||Q<0||Q>Uc)throw new j("usage",`Run claim-session cache budget must be a safe integer from 0 through ${String(Uc)}.`);this.#_=Q,this.#F=c61($.root)}async#X(){let $=this.#F,Q=d61($),Z=$.slice(Q.root.length).split("/").filter(Boolean),_=Q.root;for(let F of Z){_=k1(_,F);let J;try{J=await x$(_)}catch(Y){if(!i3(Y,"ENOENT"))throw Y;try{await WB(_,{mode:448})}catch(H){if(!i3(H,"EEXIST"))throw H}J=await x$(_)}if(J.isSymbolicLink()||!J.isDirectory())throw new j("unsafe-path",`Run root crosses a non-physical directory component: ${_}`)}let X=await x$($);if(!UE(X))throw new j("unsafe-path",`Run root must be an owner-only physical directory (0700): ${$}`);if(await Lc($)!==$)throw new j("unsafe-path",`Run root crosses a symbolic link: ${$}`);return $}async#J($,Q=!0){let Z=G6.shape.runId.parse($),_=await this.#X(),X=k1(_,Z);if(Q){let F=await x$(X).catch((J)=>{if(i3(J,"ENOENT"))throw new j("not-found",`Workflow run does not exist: ${Z}`);throw J});if(!UE(F)||await Lc(X)!==X)throw new j("unsafe-path",`Workflow run must be an owner-only physical directory (0700): ${Z}`)}return X}async#H($){return await this.#W($,"nodes")}async#W($,Q){let Z=k1($,Q),_=await x$(Z);if(!UE(_)||await Lc(Z)!==Z)throw new j("unsafe-path",`Run ${Q} storage must be a physical 0700 directory.`);return Z}async#Y($,Q){let Z=k1($,Q);try{await WB(Z,{mode:448})}catch(_){if(!i3(_,"EEXIST"))throw _}return await this.#W($,Q)}async#V($,Q){let Z=await this.#J($),_=k1(Z,e61),X=Cc.parse({acquiredAt:new Date().toISOString(),hostname:BE(),pid:process.pid,token:TE(),version:V6}),F=Date.now()+s61,J;while(J===void 0)try{await CE(_,X),J=y9(await x$(_))}catch(Y){if(!i3(Y,"EEXIST"))throw Y;let H,K;try{K=await x$(_),H=await N$(_,Cc)}catch(W){let V=await x$(_).catch(()=>{return});if(K===void 0||V===void 0||!AY(y9(K),y9(V))){if(Date.now()>=F)throw new j("conflict",`Timed out waiting for run serialization: ${$}`);await wc(zc);continue}if(i3(W,"ENOENT")||W instanceof j&&(W.code==="not-found"||W.code==="conflict")){if(Date.now()>=F)throw new j("conflict",`Timed out waiting for run serialization: ${$}`);await wc(zc);continue}throw new j("unsafe-path",`Run serialization lock is malformed: ${String(W)}`)}if(H.hostname===BE()&&!eW0(H.pid)){let W=await x$(_).catch(()=>{return});if(W!==void 0&&AY(y9(K),y9(W))){await CK(_),await p6(Z);continue}}if(Date.now()>=F)throw new j("conflict",`Timed out waiting for run serialization: ${$}`);await wc(zc)}try{return await Q(Z)}finally{let Y=await x$(_).catch(()=>{return});if(Y!==void 0&&AY(J,y9(Y))){if((await N$(_,Cc).catch(()=>{return}))?.token===X.token)await CK(_).catch(()=>{return}),await p6(Z).catch(()=>{return})}}}async#j($,Q,Z){await this.#W($,"staging");let _;try{_=bd(await HV0(k1($,"graph-plan.json"),Z))}catch(W){if(W instanceof j)throw W;throw new j("invalid-data",`Persisted graph plan is invalid: ${String(W)}`)}let X=await N$(k1($,zE),tW0,Z);if(X.runId!==Q||X.graphPlanSha256!==_.graphPlanSha256)throw new j("invalid-data","Run initialization identity is inconsistent.");let F=await N$(k1($,"graph.json"),o6,Z);if(!T4(F,_.graph))throw new j("invalid-data","Persisted authored graph differs from its graph plan.");let J=await N$(k1($,"workflow.json"),jc,Z);if(!T4(J.bundle,_.bundle)||!T4(J.workflow,_.graph.workflow))throw new j("invalid-data","Persisted workflow identity differs from its graph plan.");let Y=await N$(k1($,"runtime.json"),WE,Z);if(!T4(Y.runtime,_.runtime)||!T4(Y.computes,QV0(_))||!T4(Y.operations,$V0(_)))throw new j("invalid-data","Persisted runtime identity differs from its graph plan.");let H=await EE(k1($,"workflow.bundle.js"),Bc),K=VB("sha256").update(H).digest("hex");if(Z?.set(k1($,"workflow.bundle.js"),K),H.byteLength!==_.bundle.bytes||K!==_.bundle.bundleSha256)throw new j("invalid-data","Persisted workflow bundle bytes changed.");return{bundleBytes:H,directory:$,graphPlan:_,runtime:Y,workflow:J}}#A($){return[k1($,"graph-plan.json"),k1($,zE),k1($,"graph.json"),k1($,"workflow.json"),k1($,"runtime.json"),k1($,"workflow.bundle.js")]}async#Z($){let Q=await Promise.all(this.#A($).map(async(Z)=>{let _=await x$(Z);if(!kc(_))throw new j("unsafe-path",`Run identity must be stored in a private physical file: ${Z}`);return[Z,TY(_)]}));return new Map(Q)}#z($,Q){if($.size!==Q.size)return!1;for(let[Z,_]of $){let X=Q.get(Z);if(X===void 0||!MK(_,X))return!1}return!0}async#D($){let Q=new Map;for(let[Z,_]of $){let X=await EE(Z,_.size);Q.set(Z,VB("sha256").update(X).digest("hex"))}return Q}async#O($,Q){let Z=await this.#Z($),_=new Map,X=await this.#j($,Q,_),F=await this.#Z($);if(!this.#z(Z,F)){for(let[K,W]of Z){let V=F.get(K);if(V===void 0||!SN(W,V))throw new j("conflict",`Run identity changed while it was validated: ${Q}`)}let Y=await this.#D(F),H=await this.#Z($);if(!this.#z(F,H)||[..._].some(([K,W])=>Y.get(K)!==W))throw new j("conflict",`Run identity changed while it was validated: ${Q}`);F=H}let J={directory:X.directory,graphPlan:X.graphPlan,runtime:X.runtime,workflow:X.workflow};return{identity:J,retainedBytes:FQ1(J,F),sha256ByPath:_,snapshots:F}}#K($){let Q=this.#$.get($.runId);if(Q===void 0||Q.fenceGeneration!==$.generation||Q.fenceToken!==$.token)return;return this.#$.delete($.runId),this.#$.set($.runId,Q),Q}#N($){let Q=this.#$.get($);if(Q===void 0)return;this.#$.delete($),this.#Q=Math.max(0,this.#Q-Q.retainedBytes)}#w($,Q){let Z=this.#K($),_={...Z?.eventJournal===void 0?{}:{eventJournal:Z.eventJournal},...Z?.grantJournal===void 0?{}:{grantJournal:Z.grantJournal},...Z?.identity===void 0?{}:{identity:Z.identity},...Q,fenceGeneration:$.generation,fenceToken:$.token},X=JQ1($.runId,_);if(this.#N($.runId),X>r61||X>this.#_)return;this.#$.set($.runId,{..._,retainedBytes:X}),this.#Q=RY(this.#Q,X);while(this.#$.size>n61||this.#Q>this.#_){let F=this.#$.keys().next().value;if(F===void 0)break;this.#N(F)}}#q($){let Q=this.#$.get($.runId);if(Q?.fenceGeneration===$.generation&&Q.fenceToken===$.token)this.#N($.runId)}async#M($,Q){let Z=this.#K(Q)?.identity;if(Z!==void 0)try{let X=await this.#Z($);if(this.#z(Z.snapshots,X))return Z.identity;for(let[Y,H]of Z.snapshots){let K=X.get(Y);if(K===void 0||!SN(H,K))throw new j("conflict",`Run identity metadata changed: ${Y}`)}let F=await this.#D(X),J=await this.#Z($);if(!this.#z(X,J))throw new j("conflict","Run identity changed during revalidation.");for(let[Y,H]of Z.sha256ByPath)if(F.get(Y)!==H)throw new j("conflict",`Run identity bytes changed: ${Y}`);return this.#w(Q,{identity:{...Z,snapshots:J}}),Z.identity}catch(X){throw this.#q(Q),new j("conflict",`Run identity changed while its claim was active: ${Q.runId} (${String(X)})`)}let _=await this.#O($,Q.runId);return this.#w(Q,{identity:_}),_.identity}async#L($){let Q=await this.#J($);return await this.#j(Q,$)}async create($){let Q=cW0.parse($),Z=bd(Q.graphPlan);if(Q.bundleBytes.byteLength>Bc)throw new j("invalid-data",`Workflow bundle exceeds ${String(Bc)} bytes.`);let _=VB("sha256").update(Q.bundleBytes).digest("hex");if(Q.bundleBytes.byteLength!==Z.bundle.bytes||_!==Z.bundle.bundleSha256||!T4(Q.workflow.bundle,Z.bundle))throw new j("invalid-data","Workflow bundle identity or bytes do not match.");if(!T4(Q.workflow.workflow,Z.graph.workflow)||Q.workflow.sourceLocator!==Q.sourceLocator)throw new j("invalid-data","Workflow source identity does not match the graph plan.");if(!T4(Q.runtime.runtime,Z.runtime)||!T4(Q.runtime.computes,QV0(Z))||!T4(Q.runtime.operations,$V0(Z)))throw new j("invalid-data","Workflow runtime or operation identities do not match.");let X=await this.#J(Q.runId,!1),F=RE(X);try{await WB(X,{mode:448})}catch(K){if(i3(K,"EEXIST"))throw new j("conflict",`Workflow run already exists: ${Q.runId}`);throw K}if(await p6(F),!UE(await x$(X)))throw new j("unsafe-path","New workflow run directory is not private.");await WB(k1(X,"nodes"),{mode:448}),await WB(k1(X,"staging"),{mode:448}),await MY(k1(X,"runtime.json"),Q.runtime),await MY(k1(X,"workflow.json"),Q.workflow),await NB(k1(X,"workflow.bundle.js"),Q.bundleBytes),await MY(k1(X,"graph.json"),Z.graph),await MY(k1(X,"graph-plan.json"),Z),await NB(k1(X,"events.jsonl"),""),await NB(k1(X,"grants.jsonl"),"");let J=await this.#H(X);for(let K of Z.graph.nodes){let W=N6.parse({attempt:0,dependencies:K.dependencies,executor:K.executor,nodeKey:K.key,status:K.dependencies.length===0?"ready":"pending",version:zY});await MY(k1(J,UY(K.key)),W)}let Y=new Date().toISOString(),H=FF.parse({counts:{cancelled:0,completed:0,failed:0,pending:Z.graph.nodes.length,skipped:0},graphPlanSha256:Z.graphPlanSha256,runId:Q.runId,status:"planned",updatedAt:Y,version:V6});return await MY(k1(X,"summary.json"),H),await MY(k1(X,zE),{graphPlanSha256:Z.graphPlanSha256,runId:Q.runId,version:V6}),await p6(J),await p6(k1(X,"staging")),await p6(X),H}async list(){let $=await this.#X(),Q=await u61($,{withFileTypes:!0}),Z=[];for(let _ of Q.sort((X,F)=>X.name.localeCompare(F.name))){if(!_.isDirectory()||!_.name.startsWith("run_"))continue;try{let X=await this.#J(_.name),F=await N$(k1(X,zE),tW0),J=await N$(k1(X,"summary.json"),FF);if(F.runId!==J.runId||F.graphPlanSha256!==J.graphPlanSha256)continue;Z.push(J)}catch{}}return Object.freeze(Z.sort((_,X)=>X.updatedAt.localeCompare(_.updatedAt)))}async graphPlan($){return(await this.#L($)).graphPlan}async graph($){return(await this.#L($)).graphPlan.graph}async workflow($){return(await this.#L($)).workflow}async runtime($){return(await this.#L($)).runtime}async bundle($){return new Uint8Array((await this.#L($)).bundleBytes)}async stagingDirectory($,Q,Z){let _=G6.parse($),X=u4.parse(Q),F=N2.parse(Z);return await this.#V(_.runId,async(J)=>{await this.#C(J,_);let Y=await this.#M(J,_),H=await N$(k1(await this.#H(J),UY(X)),N6);if(H.nodeKey!==X||H.executionPlan?.nodePlanSha256!==F)throw new j("conflict",`Node staging identity does not match its exact execution plan: ${X}`);let K=await this.#W(Y.directory,"staging"),W=UY(X).slice(0,-5),V=await this.#Y(K,W),G=await this.#Y(V,F);return await p6(V),await p6(K),G})}async summary($){let Q=await this.#L($),Z=await N$(k1(Q.directory,"summary.json"),FF);if(Z.runId!==$||Z.graphPlanSha256!==Q.graphPlan.graphPlanSha256)throw new j("invalid-data","Run summary identity is inconsistent.");if(Z.outputs!==void 0){let _=await this.outputs($);if(_===void 0||!T4(_.outputs,Z.outputs))throw new j("invalid-data","Run summary output identity is inconsistent.")}if(Mc.has(Z.status)){let _=await this.#U(Q);if(!T4(Z.counts,Rc(_))||Z.status!==FV0(_)||Z.finishedAt===void 0)throw new j("invalid-data","Terminal run summary is inconsistent with node state.")}return Z}async#U($){let Q=await this.#H($.directory),Z=await Promise.all($.graphPlan.graph.nodes.map(async(X)=>await N$(k1(Q,UY(X.key)),N6))),_=new Map(Z.map((X)=>[X.nodeKey,X]));if(_.size!==$.graphPlan.graph.nodes.length)throw new j("invalid-data","Run node identities are duplicated or missing.");for(let X of $.graphPlan.graph.nodes){let F=_.get(X.key);if(F===void 0)throw new j("invalid-data",`Run is missing authored node ${X.key}.`);this.#T($.graphPlan,X,F,_)}return Object.freeze(Z)}async#P($,Q){let Z=$.graphPlan.graph.nodes.find((V)=>V.key===Q);if(Z===void 0)throw new j("not-found",`Workflow run node does not exist: ${Q}`);let _=await this.#H($.directory),X=new Map($.graphPlan.graph.nodes.map((V)=>[V.key,V])),F=new Set,J=[Z.key];while(J.length>0){let V=J.pop();if(V===void 0||F.has(V))continue;let G=X.get(V);if(G===void 0)throw new j("invalid-data",`Run graph is missing dependency ${V}.`);F.add(V),J.push(...G.dependencies)}let Y=[...F],H=await Promise.all(Y.map(async(V)=>await N$(k1(_,UY(V)),N6))),K=new Map(H.map((V)=>[V.nodeKey,V]));if(K.size!==Y.length)throw new j("invalid-data",`Run node context contains duplicated or missing identities: ${Q}`);for(let V of Y){let G=K.get(V),N=X.get(V);if(G===void 0||N===void 0)throw new j("invalid-data",`Run is missing authored node ${V}.`);this.#T($.graphPlan,N,G,K)}let W=K.get(Z.key);if(W===void 0)throw new j("invalid-data",`Run is missing authored node ${Z.key}.`);return{authored:Z,record:W,recordsByKey:K}}#T($,Q,Z,_){if(Z.nodeKey!==Q.key||!T4(Z.dependencies,Q.dependencies)||!T4(Z.executor,Q.executor))throw new j("invalid-data",`Persisted node identity changed: ${Q.key}`);let X=ZV0($,Q);if(Z.executionPlan!==void 0&&Z.preparationPlan===void 0)throw new j("invalid-data",`Execution plan has no preparation plan for node ${Q.key}.`);if(Z.preparationPlan!==void 0){let{preparationPlanSha256:F,...J}=Z.preparationPlan;if(Z.preparationPlan.version!==_B||F!==FB(J)||Z.preparationPlan.graphPlanSha256!==$.graphPlanSha256||Z.preparationPlan.nodeKey!==Q.key||!T4(Z.preparationPlan.executor,Q.executor)||!T4(Z.preparationPlan.requestedPreparation,[...X.preparation].sort((Y,H)=>Y.localeCompare(H)))||Z.preparationPlan.upperDurationMs>X.maxDurationMs||Z.preparationPlan.upperInputBytes>X.maxInputBytes)throw new j("invalid-data",`Preparation plan digest or identity is invalid for node ${Q.key}.`)}if(Z.executionPlan!==void 0){let{nodePlanSha256:F,...J}=Z.executionPlan,Y=Object.fromEntries([...Q.dependencies].sort((K,W)=>K.localeCompare(W)).map((K)=>{let W=_.get(K);if(W?.status!=="completed"||W.output===void 0)throw new j("invalid-data",`Execution plan for ${Q.key} references incomplete dependency ${K}.`);return[K,W.output.digestSha256]})),H=[...Z.executionPlan.publicationKeys].sort((K,W)=>K.localeCompare(W));if(Z.executionPlan.version!==XB||F!==JB(J)||Z.executionPlan.inputSha256!==lW0(Z.executionPlan.exactInput)||Z.executionPlan.graphPlanSha256!==$.graphPlanSha256||Z.executionPlan.nodeKey!==Q.key||Z.executionPlan.preparationPlanSha256!==Z.preparationPlan?.preparationPlanSha256||!T4(Z.executionPlan.executor,Q.executor)||!T4(Z.executionPlan.policy,YQ1(X))||!T4(Z.executionPlan.dependencyOutputDigests,Y)||!T4(Z.executionPlan.publicationKeys,H)||new Set(H).size!==H.length)throw new j("invalid-data",`Execution plan digest or identity is invalid for node ${Q.key}.`)}if(Z.output!==void 0&&Z.output.digestSha256!==dW0(Z.output.value))throw new j("invalid-data",`Output digest is invalid for node ${Q.key}.`)}async node($,Q){let Z=u4.parse(Q),_=await this.#L($);return(await this.#P(_,Z)).record}async nodes($){let Q=await this.#L($);return await this.#U(Q)}async events($){let Q=await this.#J($),Z=await Ac(k1(Q,"events.jsonl"),LE);return XV0(Z,$),Z}async grants($){let Q=await this.#L($),Z=await Ac(k1(Q.directory,"grants.jsonl"),YB);return Tc(Z,$,Q.graphPlan.graphPlanSha256),Z}async outputs($){let Q=await this.#L($),Z=k1(Q.directory,"outputs.json"),_=await N$(Z,wE).catch((H)=>{if(H instanceof j&&H.code==="not-found")return;throw H});if(_===void 0)return;if(_.runId!==$||_.graphPlanSha256!==Q.graphPlan.graphPlanSha256||_.outputsSha256!==Oc(_.outputs))throw new j("invalid-data","Persisted run outputs have an invalid identity.");let X=await this.#U(Q),F=new Map(X.map((H)=>[H.nodeKey,H])),J={},Y=PE(Q.graphPlan.graph.outputs,F,J);if(Y===void 0||!T4(_.outputs,Y)||!T4(_.nodeOutputDigests,J))throw new j("invalid-data","Persisted run outputs differ from completed nodes.");return _}async#R($){let Q=k1($,CY),Z;try{Z=await x$(Q)}catch(X){if(i3(X,"ENOENT"))return;throw X}return{fence:await N$(Q,G6),snapshot:y9(Z)}}async#C($,Q){let Z=G6.parse(Q),_=await this.#R($);if(_===void 0||_.fence.generation!==Z.generation||_.fence.token!==Z.token||_.fence.owner!==Z.owner||_.fence.runId!==Z.runId)throw this.#q(Z),new j("conflict",`Workflow run fence is stale: ${Z.runId}`);return Z}async#E($,Q,Z){let _=this.#K(Q)?.eventJournal,X=await _V0(k1($,"events.jsonl"),LE,(F)=>XV0(F,Q.runId),({cursor:F})=>{if(Q.generation<F.lastFenceGeneration)throw new j("invalid-data",`Run event fence generation regressed for ${Q.runId}.`);let J=LE.parse({...Z,fenceGeneration:Q.generation,runId:Q.runId,sequence:F.lastSequence+1,version:Kc});return{entry:J,result:J}},(F,J)=>({lastFenceGeneration:J.fenceGeneration,lastSequence:J.sequence}),_);return this.#w(Q,{eventJournal:X.state}),X.result}async acquireClaim($,Q){return await this.#V($,async(Z)=>{let _=await this.#O(Z,$),X=(Q.now??(()=>new Date))(),F=Q.staleAfterMs??30000;if(!Number.isSafeInteger(F)||F<0)throw new j("usage","Run claim stale interval must be a nonnegative safe integer.");let J=await this.#R(Z),Y=J?.fence.generation??0;if(J!==void 0){let V=X.getTime()-Date.parse(J.fence.acquiredAt),G=J.fence.hostname!==BE()||(Q.processAlive??eW0)(J.fence.pid);if(V<F||G)throw new j("conflict",`Workflow run is already claimed: ${$}`,{acquiredAt:J.fence.acquiredAt,owner:J.fence.owner,pid:J.fence.pid});let N=await x$(k1(Z,CY)).catch(()=>{return});if(N===void 0||!AY(J.snapshot,y9(N)))throw new j("conflict",`Workflow run claim changed during reclaim: ${$}`);await CK(k1(Z,CY)),await p6(Z)}this.#N($);let H=await N$(k1(Z,aW0),$Q1).catch((V)=>{if(V instanceof j&&V.code==="not-found")return;throw V});Y=Math.max(Y,H?.generation??0);let K=Y+1,W=G6.parse({acquiredAt:X.toISOString(),generation:K,hostname:BE(),owner:Q.owner,pid:process.pid,runId:$,token:TE(),version:Vc});await ME(k1(Z,aW0),{generation:K,version:V6});try{return await CE(k1(Z,CY),W),await this.#E(Z,W,{details:{owner:W.owner},kind:"run-claimed",timestamp:W.acquiredAt}),this.#w(W,{identity:_}),W}catch(V){this.#q(W);let G=await this.#R(Z).catch(()=>{return});if(G?.fence.token===W.token&&G.fence.generation===W.generation){let N=await x$(k1(Z,CY)).catch(()=>{return});if(N!==void 0&&AY(G.snapshot,y9(N)))await CK(k1(Z,CY)).catch(()=>{return}),await p6(Z).catch(()=>{return})}throw V}})}async assertFence($){let Q=G6.parse($);await this.#C(await this.#J(Q.runId),Q)}async releaseClaim($){let Q=G6.parse($);await this.#V(Q.runId,async(Z)=>{await this.#C(Z,Q);let _=await this.#R(Z);if(_===void 0)throw new j("conflict",`Workflow run fence is stale: ${Q.runId}`);let X=await x$(k1(Z,CY));if(!AY(_.snapshot,y9(X)))throw new j("conflict",`Workflow run claim changed during release: ${Q.runId}`);await CK(k1(Z,CY)),await p6(Z),this.#q(Q)})}async appendEvent($,Q){let Z=G6.parse($);return await this.#V(Z.runId,async(_)=>{if(await this.#C(_,Z),Q.nodeKey!==void 0){if(!(await this.#M(_,Z)).graphPlan.graph.nodes.some((F)=>F.key===Q.nodeKey))throw new j("invalid-data",`Run event names an unknown node: ${Q.nodeKey}`)}return await this.#E(_,Z,Q)})}#B($,Q,Z,_,X){if(QQ1.has(Z.status)){if(!T4(Z,_))throw new j("conflict",`Terminal run node ${Z.nodeKey} is immutable.`);return}if(!ZQ1[Z.status].has(_.status))throw new j("invalid-data",`Illegal run node transition ${Z.status} -> ${_.status} for ${Z.nodeKey}.`);let F=Z.status==="ready"&&_.status==="running"?Z.attempt+1:Z.attempt;if(_.attempt!==F)throw new j("invalid-data",`Run node attempt changed outside ready -> running for ${Z.nodeKey}.`);if(Z.preparationPlan!==void 0&&!T4(Z.preparationPlan,_.preparationPlan))throw new j("conflict",`Preparation plan changed for ${Z.nodeKey}.`);if(Z.executionPlan!==void 0&&!T4(Z.executionPlan,_.executionPlan))throw new j("conflict",`Execution plan changed for ${Z.nodeKey}.`);if(!(Z.status==="ready"&&_.status==="running")&&Z.startedAt!==_.startedAt)throw new j("invalid-data",`Run node startedAt changed illegally: ${Z.nodeKey}`);if(Z.status==="ready"&&_.status==="running"&&Z.startedAt!==void 0&&Date.parse(_.startedAt)<Date.parse(Z.startedAt))throw new j("invalid-data",`Run node startedAt regressed: ${Z.nodeKey}`);if(Z.status==="pending"&&_.status==="ready"&&Q.dependencies.some((J)=>X.get(J)?.status!=="completed"))throw new j("invalid-data",`Run node ${Z.nodeKey} became ready before all dependencies completed.`);if(Z.status==="running"&&_.status==="ready"){let J=ZV0($,Q).resume;if(J!=="deterministic"&&J!=="verified-receipt"&&J!=="recoverable-transaction")throw new j("conflict",`Interrupted node ${Z.nodeKey} cannot be retried under ${J}.`)}}async writeNode($,Q){let Z=G6.parse($);await this.#V(Z.runId,async(_)=>{await this.#C(_,Z);let X=N6.parse(Q),F=await this.#M(_,Z),J=await this.#P(F,X.nodeKey),Y=new Map(J.recordsByKey);Y.set(X.nodeKey,X),this.#B(F.graphPlan,J.authored,J.record,X,Y),this.#T(F.graphPlan,J.authored,X,Y);let H=await this.#H(_);await ME(k1(H,UY(X.nodeKey)),X)})}async writeSummary($,Q){let Z=G6.parse($);await this.#V(Z.runId,async(_)=>{await this.#C(_,Z);let X=FF.parse(Q),F=await this.#M(_,Z);if(X.runId!==Z.runId||X.graphPlanSha256!==F.graphPlan.graphPlanSha256)throw new j("invalid-data","Run summary identity is inconsistent.");let J=await N$(k1(_,"summary.json"),FF);if(Mc.has(J.status)){if(!T4(J,X))throw new j("conflict","Terminal run summary is immutable.");return}if(Date.parse(X.updatedAt)<Date.parse(J.updatedAt))throw new j("invalid-data","Run summary updatedAt regressed.");if(J.startedAt!==void 0&&X.startedAt!==J.startedAt)throw new j("invalid-data","Run summary startedAt changed.");if(X.status!=="planned"&&X.startedAt===void 0)throw new j("invalid-data","Started run summaries require startedAt.");if(Mc.has(X.status)!==(X.finishedAt!==void 0))throw new j("invalid-data","Only terminal run summaries require finishedAt.");let H=await this.#U(F);if(!T4(X.counts,Rc(H)))throw new j("invalid-data","Run summary counts do not match node state.");let K=FV0(H);if(X.status!==K)throw new j("invalid-data",`Run summary status ${X.status} does not match ${K}.`);if(X.status==="completed"){let W={},V=new Map(H.map((D)=>[D.nodeKey,D])),G=PE(F.graphPlan.graph.outputs,V,W);if(G===void 0||X.outputs===void 0||!T4(X.outputs,G))throw new j("invalid-data","Completed run outputs do not match the authored output bindings.");let N=wE.parse({graphPlanSha256:F.graphPlan.graphPlanSha256,nodeOutputDigests:W,outputs:G,outputsSha256:Oc(G),runId:Z.runId,version:Gc});try{await CE(k1(_,"outputs.json"),N)}catch(D){if(!i3(D,"EEXIST"))throw D;let L=await N$(k1(_,"outputs.json"),wE);if(!T4(L,N))throw new j("conflict","Run outputs were already published differently.")}}else if(X.outputs!==void 0)throw new j("invalid-data","Only completed runs may publish outputs.");await ME(k1(_,"summary.json"),X)})}async appendGrant($,Q){let Z=G6.parse($);return await this.#V(Z.runId,async(_)=>{await this.#C(_,Z);let X=await this.#M(_,Z),F=YB.parse({...Q,runId:Z.runId,version:Wc});if(F.graphPlanSha256!==X.graphPlan.graphPlanSha256)throw new j("invalid-data","Run grant targets a different graph plan.");if("nodeKey"in F&&!X.graphPlan.graph.nodes.some((H)=>H.key===F.nodeKey))throw new j("invalid-data",`Run grant targets unknown node ${F.nodeKey}.`);if(F.kind==="compute-replay"&&F.bundleSha256!==X.graphPlan.bundle.bundleSha256)throw new j("invalid-data","Compute replay grant targets a different bundle.");if(F.kind==="compute-replay"){let H=X.graphPlan.graph.nodes.find((V)=>V.key===F.nodeKey);if(H===void 0||!F8(H))throw new j("invalid-data",`Compute replay grant targets a non-compute node: ${F.nodeKey}`);let W=(await this.#U(X)).find((V)=>V.nodeKey===F.nodeKey);if(W?.status!=="ambiguous-code"||W.executionPlan===void 0||F.computeKey!==H.executor.compute.key||F.nodePlanSha256!==W.executionPlan.nodePlanSha256||F.attempt!==W.attempt+1)throw new j("conflict",`Compute replay grant does not match the exact next attempt for ${F.nodeKey}.`)}let J=this.#K(Z)?.grantJournal,Y=await _V0(k1(_,"grants.jsonl"),YB,(H)=>Tc(H,Z.runId,X.graphPlan.graphPlanSha256),({cursor:H})=>{if(H.grantIds.has(F.grantId))throw new j("conflict",`Run grant already exists: ${F.grantId}`);return{entry:F,result:F}},(H,K)=>{return H.grantIds.add(K.grantId),H},J);return this.#w(Z,{grantJournal:Y.state}),Y.result})}async reopenComputeNode($,Q){let Z=G6.parse($),_=u4.parse(Q);return await this.#V(Z.runId,async(X)=>{await this.#C(X,Z);let F=await this.#M(X,Z),J=F.graphPlan.graph.nodes.find((D)=>D.key===_);if(J===void 0||!F8(J))throw new j("invalid-data",`Only a trusted compute node may be reopened: ${_}`);let Y=await this.#U(F),H=Y.find((D)=>D.nodeKey===_);if(H?.status!=="ambiguous-code"||H.executionPlan===void 0)throw new j("conflict",`Compute node is not awaiting an explicit replay: ${_}`);let K=await Ac(k1(X,"grants.jsonl"),YB);if(Tc(K,Z.runId,F.graphPlan.graphPlanSha256),!K.some((D)=>D.kind==="compute-replay"&&D.nodeKey===_&&D.attempt===H.attempt+1&&D.bundleSha256===F.graphPlan.bundle.bundleSha256&&D.computeKey===J.executor.compute.key&&D.nodePlanSha256===H.executionPlan?.nodePlanSha256))throw new j("authorization-required",`Compute node ${_} requires an exact replay grant for attempt ${String(H.attempt+1)}.`);let V={...H};delete V.failure,delete V.finishedAt;let G=N6.parse({...V,status:"ready"}),N=new Map(Y.map((D)=>[D.nodeKey,D.nodeKey===_?G:D]));return this.#T(F.graphPlan,J,G,N),await ME(k1(await this.#H(X),UY(_)),G),G})}async requestCancellation($,Q,Z=new Date){return await this.#V($,async(_)=>{await this.#j(_,$);let X=k1(_,"cancel-request.json"),F=await N$(X,HB).catch((Y)=>{if(Y instanceof j&&Y.code==="not-found")return;throw Y});if(F!==void 0)return F;let J=HB.parse({requestedAt:Z.toISOString(),requestedBy:Q,runId:$,version:V6});try{return await CE(X,J),J}catch(Y){let H=await N$(X,HB).catch(()=>{return});if(H!==void 0)return H;throw Y}})}async cancellation($){let Q=await this.#J($);return await N$(k1(Q,"cancel-request.json"),HB).then((Z)=>{if(Z.runId!==$)throw new j("invalid-data","Cancellation request targets a different run.");return Z}).catch((Z)=>{if(Z instanceof j&&Z.code==="not-found")return;throw Z})}}import{Deferred as fE,Effect as c1,Either as jB,Exit as VV0,Fiber as NQ1,Queue as Ec}from"effect";import{randomUUID as Pc}from"crypto";import{performance as kY}from"perf_hooks";var jQ1=32,DQ1=128,OQ1=2000,LQ1=4000,wQ1=100,BQ1=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 GV0($,Q){return Q>Number.MAX_SAFE_INTEGER-$?Number.MAX_SAFE_INTEGER:$+Q}function fc($){return c1.suspend(()=>{let Q=$-kY.now();return Q<=0?c1.void:c1.zipRight(c1.sleep(Math.min(Q,2147483647)),fc($))})}class wV0{#$=new AbortController;deadlineMonotonicMs;#Q;#_;#F;#X;#J;constructor($,Q,Z){this.#F=$,this.deadlineMonotonicMs=Q,this.#_=Z,this.#Q=$.deferred(),this.#X=$.watch(c1.zipRight(fc(Q),c1.sync(()=>{this.interrupt("deadline",new j("cancelled","Workflow exceeded the host wall-clock bound."))})))}get interruption(){return this.#J}get signal(){return this.#$.signal}interrupt($,Q){if(this.#J!==void 0)return;let Z={error:Q,kind:$};this.#J=Z,this.#$.abort(Q),this.#_(Z),fE.unsafeDone(this.#Q,c1.fail(B_(Q,"monitor")))}assertActive(){if(this.#J!==void 0)throw this.#J.error}async race($){return this.assertActive(),await this.#F.run(c1.raceFirst(R1("authority",$),fE.await(this.#Q)))}async custody($){return await this.#F.custody($)}async runNative($){return await this.#F.run($)}async stop(){await this.#X()}}function DB($,Q){if(!Number.isSafeInteger($)||$<1)throw new j("usage",`${Q} must be a positive safe integer.`);return $}function zQ1($,Q){if(!Number.isSafeInteger($)||$<0)throw new j("usage",`${Q} must be a nonnegative safe integer.`);return $}function UQ1($){let Q=DB($.hostLimits?.maxJobs??4,"Host job limit"),Z=$.jobs===void 0?Q:DB($.jobs,"Requested job limit"),_=$.hostLimits?.resources??{},X=Object.fromEntries(SO.map((F)=>[F,zQ1(_[F]??BQ1[F],`Host ${F} limit`)]));return{cancellationPollMs:DB($.cancellationPollMs??wQ1,"Cancellation poll interval"),jobs:Math.min(Q,Z),maxNodes:DB($.hostLimits?.maxNodes??4096,"Host node limit"),maxWallClockMs:DB($.hostLimits?.maxWallClockMs??86400000,"Host workflow wall-clock limit"),resources:X}}function CQ1($){return OE($).sha256}function BV0($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.hasOwn($,"$ref")}function MQ1($){return Array.isArray($)}function AQ1($){return Array.isArray($)}function yc($){if($.status!=="completed"||$.output===void 0)throw new j("invalid-data",`Dependency ${$.nodeKey} does not have a completed output.`);let Q=B1.parse($.output.value);if(CQ1(Q)!==$.output.digestSha256)throw new j("invalid-data",`Completed output digest does not match for node ${$.nodeKey}.`);return $.output}function bc($,Q){if(BV0($)){let Z=Q.get($.$ref.nodeKey);if(Z===void 0)throw new j("invalid-data",`Node input references unavailable output ${$.$ref.nodeKey}.`);return KB($,Z.value)}if(MQ1($))return $.map((Z)=>bc(Z,Q));if(typeof $==="object"&&$!==null)return Object.fromEntries(Object.entries($).sort(([Z],[_])=>Z.localeCompare(_)).map(([Z,_])=>[Z,bc(_,Q)]));return $}function NV0($,Q){let Z=new Map,_={};for(let X of[...$.dependencies].sort((F,J)=>F.localeCompare(J))){let F=Q.get(X);if(F===void 0)throw new j("invalid-data",`Missing dependency node ${X}.`);let J=yc(F);Z.set(X,J),_[X]=J}return{dependencyOutputs:_,input:B1.parse(bc($.input,Z))}}function xc($){return PK.parse({...$,preparation:[...$.preparation].sort((Q,Z)=>Q.localeCompare(Z)),resources:[...$.resources].sort((Q,Z)=>Q.resource.localeCompare(Z.resource))})}function jV0($){return{...$,inputSchemaId:$.inputSchemaId.replace(/^studio\./u,"slopcamera."),outputSchemaId:$.outputSchemaId.replace(/^studio\./u,"slopcamera."),policy:EK.parse(xc($.policy))}}function OB($,Q,Z){let _=Q.executor.operation,X=Z.get(_.kind,_.version),F=$.registry.discovery.find((J)=>J.kind===_.kind&&J.version===_.version);if(F===void 0)throw new j("incompatible",`Graph plan omits operation ${_.kind}@${String(_.version)}.`);if(R(jV0(X.discovery))!==R(jV0(F)))throw new j("incompatible",`Registered operation changed after planning: ${_.kind}@${String(_.version)}.`);return X}function DV0($,Q,Z){if(R4(Q)){let _=OB($,Q,Z);return{kind:"operation",operation:_,policy:_.discovery.policy}}if(F8(Q))return{compute:Q.executor.compute,kind:"compute",policy:IK(Q.executor.compute)};throw new j("internal",`Unknown node executor for ${Q.key}.`)}function zV0($){if($.length>64)throw new j("invalid-data","A node may claim at most 64 publication keys.");let Q=[...$].map((Z)=>{if(Z.length<1||Z.length>512)throw new j("invalid-data","Publication keys must contain between 1 and 512 characters.");return Z}).sort((Z,_)=>Z.localeCompare(_));if(new Set(Q).size!==Q.length)throw new j("invalid-data","A node cannot claim a publication key twice.");return Q}function TQ1($){let Q=A_($.input,"studio.workflow.compute-input-descriptor/v1\x00");return{inputDescriptors:B1.parse({bytes:Q.bytes,inputSha256:Q.sha256}),upperInputBytes:Q.bytes}}function RQ1($,Q,Z,_){let X=_.upperDurationMs??Z.maxDurationMs,F=_.upperInputBytes??Z.maxInputBytes;if(!Number.isSafeInteger(X)||X<0||X>Z.maxDurationMs)throw new j("invalid-data",`Preparation duration bound exceeds policy for node ${Q.key}.`);if(!Number.isSafeInteger(F)||F<0||F>Z.maxInputBytes)throw new j("invalid-data",`Preparation input bound exceeds policy for node ${Q.key}.`);let J=VE.parse({exactInputBound:!0,executor:Q.executor,graphPlanSha256:$.graphPlanSha256,inputDescriptors:B1.parse(_.inputDescriptors),nodeKey:Q.key,requestedPreparation:[...Z.preparation].sort((Y,H)=>Y.localeCompare(H)),upperDurationMs:X,upperInputBytes:F,version:_B});return GE.parse({...J,preparationPlanSha256:FB(J)})}function kQ1($,Q,Z,_,X,F){let J=B1.parse(F.exactInput),Y=DE(J),H=Y.bytes,K=_.exactInputBound===!0?_.upperInputBytes:Z.maxInputBytes;if(H>K)throw new j("invalid-data",`Exact input for node ${Q.key} uses ${String(H)} canonical JSON bytes; the ${_.exactInputBound===!0?"prepared upper bound":"operation input limit"} is ${String(K)}.`);let W=Object.fromEntries(Object.entries(X.dependencyOutputs).sort(([G],[N])=>G.localeCompare(N)).map(([G,N])=>[G,N.digestSha256])),V=NE.parse({dependencyOutputDigests:W,executor:Q.executor,exactInput:J,...F.expectedProjectGeneration===void 0?{}:{expectedProjectGeneration:F.expectedProjectGeneration},graphPlanSha256:$.graphPlanSha256,inputSha256:Y.sha256,nodeKey:Q.key,policy:xc(Z),preparationPlanSha256:_.preparationPlanSha256,publicationKeys:zV0(F.publicationKeys),version:XB});return jE.parse({...V,nodePlanSha256:JB(V)})}function qQ1($,Q,Z,_){let X=GE.parse($),{preparationPlanSha256:F,...J}=X;if(F!==FB(J)||X.graphPlanSha256!==Q.graphPlanSha256||X.nodeKey!==Z.key||R(X.executor)!==R(Z.executor)||X.upperDurationMs>_.maxDurationMs||X.upperInputBytes>_.maxInputBytes||R(X.requestedPreparation)!==R([..._.preparation].sort((Y,H)=>Y.localeCompare(H))))throw new j("invalid-data",`Persisted preparation plan no longer matches node ${Z.key}.`)}function EQ1($,Q,Z,_,X,F){let J=jE.parse($),{nodePlanSha256:Y,...H}=J,K=DE(J.exactInput),W=K.bytes,V=X.exactInputBound===!0?X.upperInputBytes:_.maxInputBytes,G=Object.fromEntries(Object.entries(F.dependencyOutputs).sort(([N],[D])=>N.localeCompare(D)).map(([N,D])=>[N,D.digestSha256]));if(Y!==JB(H)||W>V||J.inputSha256!==K.sha256||J.graphPlanSha256!==Q.graphPlanSha256||J.nodeKey!==Z.key||J.preparationPlanSha256!==X.preparationPlanSha256||R(J.executor)!==R(Z.executor)||R(J.policy)!==R(xc(_))||R(J.dependencyOutputDigests)!==R(G)||R(J.publicationKeys)!==R(zV0(J.publicationKeys)))throw new j("invalid-data",`Persisted execution plan no longer matches node ${Z.key}.`)}function OV0($){return typeof $==="boolean"?$:$.allowed}function PQ1($,Q,Z,_){return $.some((X)=>X.kind==="preparation"&&X.graphPlanSha256===Q&&X.nodeKey===Z&&X.preparationPlanSha256===_)}function IQ1($,Q,Z,_){return $.some((X)=>X.kind==="effect"&&X.graphPlanSha256===Q&&X.nodeKey===Z&&X.nodePlanSha256===_)}function bQ1($){return($.length===0?"Unknown scheduler failure.":$).slice(0,LQ1)}function F9($,Q=!1){let Z=lY($),_=D8.safeParse(Z.details?.spatialPublication);return{code:(()=>{switch(Z.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 Z.code;case"not-found":case"unsafe-path":case"usage":return"invalid-data"}})(),message:bQ1(Z.message),retryable:Q,..._.success?{spatialPublication:_.data}:{}}}function SQ1($){let Q=Object.entries($).sort(([Z],[_])=>Z.localeCompare(_));if(Q.length>jQ1)throw new j("internal","Operation summary exceeds the scheduler field limit.");return Object.fromEntries(Q.map(([Z,_])=>{if(Z.length<1||Z.length>DQ1)throw new j("internal","Operation summary contains an invalid field name.");if(typeof _==="number"&&!Number.isFinite(_))throw new j("internal","Operation summary contains a non-finite number.");if(typeof _==="string"&&_.length>OQ1)throw new j("internal","Operation summary contains an oversized string.");return[Z,_]}))}function Ic($,Q,Z,_){let X=B1.parse($),F=OE(X),J=F.bytes;if(J>Z)throw new j("invalid-data",`Operation output uses ${String(J)} bytes; the limit is ${String(Z)}.`);return{digestSha256:F.sha256,..._===void 0?{}:{receiptReference:_},summary:SQ1(Q),value:X}}function fQ1($){return["ambiguous","cancelled","failed","incompatible","skipped"].includes($.status)}function yQ1($){return $.status==="pending"||$.status==="ready"||$.status==="preparing"||$.status==="approval-required"}class UV0{#$;#Q;#_=new Set;#F;#X=0;constructor($){this.#$=$.jobs,this.#Q=$.resources,this.#F=Object.fromEntries(SO.map((Q)=>[Q,0]))}impossible($){return $.some((Q)=>Q.amount>this.#Q[Q.resource])}acquire($,Q){if(this.#X>=this.#$)return!1;if(Q.some((Z)=>this.#_.has(Z)))return!1;if($.some((Z)=>this.#F[Z.resource]+Z.amount>this.#Q[Z.resource]))return!1;this.#X+=1;for(let Z of $)this.#F[Z.resource]+=Z.amount;for(let Z of Q)this.#_.add(Z);return!0}release($,Q){this.#X-=1;for(let Z of $)this.#F[Z.resource]-=Z.amount;for(let Z of Q)this.#_.delete(Z)}}function bE($,Q){return{...$,hostResourceLease:{assertOwned:async()=>await Q.assertOwned(),claims:Q.claims,inheritedFileDescriptor:Q.inheritedFileDescriptor,inheritedFileDescriptors:[Q.inheritedFileDescriptor],profile:Q.profile,ticket:Q.ticket},runner:{run:async(Z,_={})=>{await Q.assertOwned();let X=[..._.inheritedFileDescriptors??[],Q.inheritedFileDescriptor].filter((F,J,Y)=>Y.indexOf(F)===J);if(X.length>16)throw new j("incompatible","A workflow subprocess cannot inherit more than 16 file descriptors.");return await $.runner.run(Z,{..._,inheritedFileDescriptors:X})}}}}function xQ1($){if(!($ instanceof I2))return lY($);switch($.code){case"WAIT_ABORTED":return new j("cancelled",$.message);case"WAIT_TIMEOUT":return new j("unavailable",$.message);case"OWNERSHIP_LOST":return new j("conflict",$.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":return new j("incompatible",$.message);default:return $.code}}function CV0($){return{cancelled:$.filter((Q)=>Q.status==="cancelled").length,completed:$.filter((Q)=>Q.status==="completed").length,failed:$.filter((Q)=>Q.status==="failed"||Q.status==="incompatible"||Q.status==="ambiguous").length,pending:$.filter((Q)=>Q.status==="pending"||Q.status==="ready"||Q.status==="preparing"||Q.status==="running"||Q.status==="approval-required"||Q.status==="ambiguous-code").length,skipped:$.filter((Q)=>Q.status==="skipped").length}}function LV0($,Q,Z){if(Q.pause!==void 0)return"approval-required";if($.some((X)=>X.status==="approval-required"))return"approval-required";if($.some((X)=>X.status==="ambiguous-code"))return"ambiguous-code";if(Z>0||$.some((X)=>X.status==="running")||$.some(yQ1))return"running";let _=CV0($);if(_.cancelled>0)return"cancelled";if(_.failed===0&&_.skipped===0&&_.completed===$.length)return"completed";if(Q.cancelled)return"cancelled";if($.some((X)=>X.status==="incompatible")&&_.completed===0)return"incompatible";if(_.completed>0)return"partial";return"failed"}function SE($){return $==="cancelled"||$==="completed"||$==="failed"||$==="incompatible"||$==="partial"}function Sc($,Q){if(BV0($)){let _=Q.get($.$ref.nodeKey);if(_===void 0||_.status!=="completed")return;return KB($,yc(_).value)}if(AQ1($)){let _=[];for(let X of $){let F=Sc(X,Q);if(F===void 0)return;_.push(F)}return _}let Z={};for(let[_,X]of Object.entries($).sort(([F],[J])=>F.localeCompare(J))){let F=Sc(X,Q);if(F===void 0)return;Z[_]=F}return Z}class hc{#$;#Q;#_;#F;#X;#J;#H;#W;#Y;#V;#j;#A=new Set;#Z;constructor($){if($.owner.length<1||$.owner.length>256)throw new j("usage","Scheduler owner must contain between 1 and 256 characters.");if($.authorization.grantedBy.length<1||$.authorization.grantedBy.length>256)throw new j("usage","Authorization owner must contain between 1 and 256 characters.");if(this.#$=$.application,this.#Q=$.authorization,this.#_=$.compute,this.#F=$.compute?.kind==="fresh"?$.compute.executor:void 0,$.currentApplicationBuild.length<1||$.currentApplicationBuild.length>160)throw new j("usage","Current application build must contain between 1 and 160 characters.");this.#X=$.currentApplicationBuild,this.#J=$.hostResourceCoordinator,this.#H=UQ1($),this.#W=$.nodePlanner,this.#Y=$.now??(()=>new Date),this.#V=$.owner,this.#j=$.registry,this.#Z=$.store}async run($){let Q=new Hc;try{return await Q.run(this.#z($,Q))}finally{await Q.stop()}}#z($,Q){return fW0(c1.gen(this,function*(){let Z=yield*R1("authority",()=>this.#Z.graphPlan($));if(Z.graph.nodes.length>this.#H.maxNodes)return yield*c1.fail(B_(new j("incompatible",`Workflow has ${String(Z.graph.nodes.length)} nodes; the host limit is ${String(this.#H.maxNodes)}.`)));let _=!0,X=yield*Yc(R1("admission",()=>this.#Z.acquireClaim($,{owner:this.#V})),(w)=>_?this.#D(w):c1.void),F;yield*Yc(c1.void,()=>R1("cleanup",()=>F?.release()));let J=GV0(kY.now(),this.#H.maxWallClockMs),H={cancelled:!1,monitorError:void 0,pause:void 0,reconciliationDeferred:!1,startedAt:(yield*R1("authority",()=>this.#O($))).startedAt??this.#Y().toISOString()},K=new Map,W=yield*Ec.unbounded(),V=new Map,G=new UV0(this.#H),N=new wV0(Q,J,(w)=>{if(w.kind==="monitor")H.monitorError=w.error;else H.cancelled=!0;if(w.kind!=="deadline"){for(let B of K.values())if(B.admissionAbortController.abort(),B.cancellable)B.abortController.abort()}}),D=Q.watch(c1.forever(c1.gen(this,function*(){yield*c1.sleep(this.#H.cancellationPollMs);let w=yield*c1.either(R1("monitor",()=>this.#K($)));if(jB.isLeft(w))N.interrupt("monitor",lY(w.left.cause));else if(w.right!==void 0)N.interrupt("cancellation",new j("cancelled","Workflow cancellation requested."))}))),L=yield*c1.exit(c1.catchAll(c1.gen(this,function*(){yield*R1("authority",()=>this.#Z.assertFence(X)),yield*R1("authority",()=>this.#Z.appendEvent(X,{details:{status:"running"},kind:"run-status",timestamp:this.#Y().toISOString()}));let w=yield*c1.either(c1.gen(this,function*(){yield*R1("authority",()=>this.#q($,Z)),F=yield*R1("authority",()=>this.#M(X,Z,H,N))}));if(jB.isLeft(w)){let B=w.left.cause,z=lY(B);if(z.code!=="incompatible"&&z.code!=="unsupported-plan")return yield*c1.fail(B_(B));yield*R1("authority",()=>this.#x(X,Z,H,z));let U=yield*R1("authority",()=>this.#k(X,Z,H,0));return yield*R1("authority",()=>this.#Z.appendEvent(X,{details:{status:U.status},kind:"run-finalized",timestamp:this.#Y().toISOString()})),yield*R1("authority",()=>this.#Z.releaseClaim(X)),_=!1,{summary:U}}if(yield*R1("authority",()=>this.#L(X,Z,H,N)),yield*R1("authority",()=>this.#k(X,Z,H,K.size)),H.reconciliationDeferred){let B=yield*R1("authority",()=>this.#k(X,Z,H,0));return yield*R1("authority",()=>this.#Z.appendEvent(X,{details:{status:B.status},kind:"run-status",timestamp:this.#Y().toISOString()})),yield*R1("authority",()=>this.#Z.releaseClaim(X)),_=!1,{summary:B}}while(!0){if(H.monitorError!==void 0)return yield*c1.fail(B_(H.monitorError));if(yield*R1("authority",()=>this.#Z.assertFence(X)),(yield*R1("authority",()=>this.#K($)))!==void 0){H.cancelled=!0;for(let C of K.values())if(C.admissionAbortController.abort(),C.cancellable)C.abortController.abort()}if(kY.now()>=J){H.cancelled=!0;for(let C of K.values())if(C.admissionAbortController.abort(),C.cancellable)C.abortController.abort()}if(yield*R1("authority",()=>this.#T(X,Z,H)),H.cancelled)yield*R1("authority",()=>this.#I(X,Z));else if(H.pause===void 0){if(yield*R1("authority",()=>this.#R(X,Z,H,N,V)),H.pause===void 0){if(yield*R1("authority",()=>this.#B(X,V,K,G,J,N,Q,W)),H.cancelled)yield*R1("authority",()=>this.#I(X,Z))}}if(K.size>0){let C=yield*Ec.take(W),M=K.get(C.nodeKey);if(M===void 0)continue;let T={item:M,outcome:yield*C.outcome};K.delete(T.item.nodeKey),G.release(T.item.resources,T.item.publicationKeys);let q=yield*R1("authority",()=>this.#S(X,Z,T.item,T.outcome,N));if(yield*R1("authority",()=>this.#k(X,Z,H,K.size)),q){H.reconciliationDeferred=!0;let E=yield*R1("authority",()=>this.#k(X,Z,H,K.size));return yield*R1("authority",()=>this.#Z.appendEvent(X,{details:{status:E.status},kind:"run-status",timestamp:this.#Y().toISOString()})),yield*R1("authority",()=>this.#Z.releaseClaim(X)),_=!1,{summary:E}}continue}let B=yield*R1("authority",()=>this.#Z.nodes($));if(LV0(B,H,0)==="running"){if(yield*R1("authority",()=>this.#b(X,Z,G)))continue;return yield*c1.fail(B_(new j("internal","Workflow scheduler reached a nonterminal state without runnable work.")))}let U=yield*R1("authority",()=>this.#k(X,Z,H,0));return yield*R1("authority",()=>this.#Z.appendEvent(X,{details:{status:U.status},kind:SE(U.status)?"run-finalized":"run-status",timestamp:this.#Y().toISOString()})),yield*R1("authority",()=>this.#Z.releaseClaim(X)),_=!1,{...H.pause===void 0?{}:{pause:H.pause},summary:U}}}),(w)=>c1.gen(this,function*(){let B=w.cause;if(_&&(N.interruption?.kind==="cancellation"||N.interruption?.kind==="deadline")){let z=[...K.values()].sort((C,M)=>C.nodeKey.localeCompare(M.nodeKey));if(z.length>0){let C=yield*c1.forEach(z,(M)=>c1.flatMap(NQ1.join(M.fiber),(T)=>c1.map(T,(q)=>({item:M,outcome:q}))),{concurrency:"unbounded"});K.clear();for(let M of C){G.release(M.item.resources,M.item.publicationKeys);let T=yield*R1("authority",()=>this.#S(X,Z,M.item,M.outcome,N));H.reconciliationDeferred||=T}}yield*R1("authority",()=>this.#I(X,Z));let U=yield*R1("authority",()=>this.#k(X,Z,H,K.size));return yield*R1("authority",()=>this.#Z.appendEvent(X,{details:{status:U.status},kind:SE(U.status)?"run-finalized":"run-status",timestamp:this.#Y().toISOString()})),yield*R1("authority",()=>this.#Z.releaseClaim(X)),_=!1,{summary:U}}if(_){let z=lY(B);if(z.code!=="conflict")yield*R1("authority",()=>this.#y(X,Z,H,z).catch(()=>{return}))}return yield*c1.fail(B_(B))}))),O=yield*c1.exit(c1.gen(this,function*(){yield*R1("authority",()=>D()),yield*R1("authority",()=>N.stop())}));return yield*VV0.zipLeft(L,O)}))}#D($){return c1.gen(this,function*(){let Q=yield*c1.either(R1("cleanup",()=>this.#Z.assertFence($)));if(jB.isLeft(Q)){if(Q.left.cause instanceof j&&Q.left.cause.code==="conflict")return;return yield*c1.fail(Q.left)}let Z=yield*c1.either(R1("cleanup",()=>this.#Z.releaseClaim($)));if(jB.isRight(Z))return;if(Z.left.cause instanceof j&&Z.left.cause.code==="conflict"){let _=yield*c1.either(R1("cleanup",()=>this.#Z.assertFence($)));if(jB.isLeft(_)&&_.left.cause instanceof j&&_.left.cause.code==="conflict")return}return yield*c1.fail(Z.left)})}async#O($){return await this.#Z.summary($)}async#K($){let Q;for(let Z=0;Z<4;Z+=1)try{return await this.#Z.cancellation($)}catch(_){let X=lY(_);if(X.code!=="conflict")throw _;Q=X,await Promise.resolve()}throw Q??new j("conflict",`Could not read a stable cancellation marker for ${$}.`)}async#N($,Q){if(Q.assertActive(),await Q.race(async()=>await this.#K($.runId))!==void 0)Q.interrupt("cancellation",new j("cancelled","Workflow cancellation requested.")),Q.assertActive()}async#w($,Q,Z){await this.#N($,Q);let _=await Q.race(Z);return Q.assertActive(),_}async#q($,Q){if(Q.runtime.applicationBuild!==this.#X)throw new j("incompatible","Persisted workflow application build differs from the current host build.");let Z=await this.#Z.runtime($);if(R(Z.runtime)!==R(Q.runtime))throw new j("incompatible","Persisted workflow runtime identity changed.");let _=[...new Set(Q.graph.nodes.filter(R4).map((J)=>`${J.executor.operation.kind}@${String(J.executor.operation.version)}`))].sort((J,Y)=>J.localeCompare(Y)),X=Z.operations.map((J)=>`${J.kind}@${String(J.version)}`).sort((J,Y)=>J.localeCompare(Y));if(R(_)!==R(X))throw new j("incompatible","Persisted operation runtime set changed.");let F=[...new Map(Q.graph.nodes.filter(F8).map((J)=>[J.executor.compute.key,J.executor.compute])).values()].sort((J,Y)=>J.key.localeCompare(Y.key));if(R(F)!==R(Z.computes))throw new j("incompatible","Persisted compute runtime set changed.");for(let J of Q.graph.nodes)if(R4(J))OB(Q,J,this.#j)}async#M($,Q,Z,_){let X=this.#_;if(X===void 0)return;if(X.kind==="fresh"){if(X.executor.bundleSha256!==Q.bundle.bundleSha256)throw new j("incompatible","Fresh code worker bundle does not match the persisted graph plan.");this.#F=X.executor;return}let F=[...new Set(X.nodeKeys.map((G)=>u4.parse(G)))].sort((G,N)=>G.localeCompare(N));if(F.length===0)throw new j("usage","A compute replay requires at least one exact node key.");if(await this.#K($.runId)!==void 0){Z.cancelled=!0;return}let J=await this.#Z.nodes($.runId),Y=new Map(Q.graph.nodes.map((G)=>[G.key,G])),H=[];for(let G of F){let N=Y.get(G),D=J.find((L)=>L.nodeKey===G);if(N===void 0||!F8(N)||D?.status!=="ambiguous-code"||D.executionPlan===void 0)throw new j("conflict",`Compute node is not awaiting exact replay: ${G}`);H.push({attempt:D.attempt+1,bundleSha256:Q.bundle.bundleSha256,computeKey:N.executor.compute.key,createdAt:this.#Y().toISOString(),graphPlanSha256:Q.graphPlanSha256,grantedBy:this.#Q.grantedBy,grantId:Pc(),kind:"compute-replay",nodeKey:G,nodePlanSha256:D.executionPlan.nodePlanSha256})}for(let G of H){if(await this.#K($.runId)!==void 0){Z.cancelled=!0;return}await this.#Z.appendGrant($,G)}if(await this.#K($.runId)!==void 0){Z.cancelled=!0;return}await this.#N($,_);let K=_.deadlineMonotonicMs-kY.now();if(K<=0)_.interrupt("deadline",new j("cancelled","Workflow exceeded the host wall-clock bound.")),_.assertActive();let W=X.load({signal:_.signal,waitTimeoutMilliseconds:Math.min(xQ,Math.max(1,Math.ceil(K)))}),V;try{V=await _.race(async()=>await W)}catch(G){throw W.then(async(N)=>await N.release(),()=>{return}).catch(()=>{return}),G}try{if(_.assertActive(),V.executor.bundleSha256!==Q.bundle.bundleSha256)throw new j("incompatible","Replay code worker bundle does not match the persisted graph plan.");this.#F=V.executor;for(let G of F)this.#A.add(G);for(let G of F)await this.#Z.reopenComputeNode($,G);return V}catch(G){throw await V.release().catch(()=>{return}),G}}async#L($,Q,Z,_){let X=await this.#Z.nodes($.runId),F=new Map(X.map((J)=>[J.nodeKey,J]));for(let J of[...Q.graph.nodes].sort((Y,H)=>Y.key.localeCompare(H.key))){let Y=F.get(J.key);if(Y===void 0)throw new j("invalid-data",`Run is missing node ${J.key}.`);if(Y.status==="completed"){yc(Y),await this.#Z.appendEvent($,{details:{digestSha256:Y.output?.digestSha256??""},kind:"node-reused",nodeKey:J.key,timestamp:this.#Y().toISOString()});continue}if(Y.status==="approval-required")continue;if(Y.status==="preparing"){await this.#G($,{...Y,status:"ready"});continue}if(Y.status!=="running")continue;if(F8(J)){await this.#G($,{...Y,failure:F9(new j("ambiguous","Interrupted trusted compute requires an explicit exact-bundle replay.")),finishedAt:this.#Y().toISOString(),status:"ambiguous-code"});continue}if(!R4(J))throw new j("internal",`Unknown node executor for ${J.key}.`);let H=OB(Q,J,this.#j).discovery.policy.resume;if(H==="deterministic"){await this.#G($,{...Y,failure:void 0,finishedAt:void 0,status:"ready"});continue}let K=await this.#U($,Q,J,Y,F,_);if(K.deferred){if(Z.reconciliationDeferred=!0,_.interruption!==void 0)break;continue}if(K.reconciliation?.kind==="ambiguous"&&H==="non-resumable-live")Z.cancelled=!1}}async#U($,Q,Z,_,X,F){let J=OB(Q,Z,this.#j),Y=NV0(Z,X),H=J.discovery.policy.resume;await this.#Z.assertFence($);let K=_.executionPlan===void 0?void 0:await this.#Z.stagingDirectory($,Z.key,_.executionPlan.nodePlanSha256),W;try{let V=this.#W.reconcile,G=this.#W.reconcileEffect;W=V===void 0&&G===void 0?void 0:await this.#w($,F,async()=>{let N=async()=>await this.#J.withLease(N_(J.discovery.policy.resources,this.#J),async(D)=>{await D.assertOwned();let L=async()=>{if(await D.assertOwned(),F.assertActive(),F.signal.aborted)throw new j("cancelled","Workflow reconciliation was cancelled before publication.");await this.#Z.assertFence($),await this.#N($,F),await this.#Z.assertFence($),F.assertActive(),await D.assertOwned()},O={abortSignal:F.signal,application:bE(this.#$,D),beforePublication:L,dependencyOutputs:Y.dependencyOutputs,executionPlan:_.executionPlan,graphPlan:Q,node:Z,operation:J.discovery,preparationPlan:_.preparationPlan,previous:_,resolvedInput:Y.input,resumeClass:H,runId:$.runId,...K===void 0?{}:{workspaceDirectory:K}};return G===void 0?await V.call(this.#W,O):await F.runNative(G.call(this.#W,O))},{signal:F.signal,waitTimeoutMilliseconds:xQ});return G===void 0?await N():await F.custody(R1("authority",N))})}catch{return await this.#Z.assertFence($),{deferred:!0,reconciliation:void 0}}return await this.#Z.assertFence($),await this.#P($,_,J,H,W),{deferred:!1,reconciliation:W}}async#P($,Q,Z,_,X){if(X?.kind==="completed"){let H=Ic(X.output,X.summary,Z.discovery.policy.maxOutputBytes,X.receiptReference);await this.#G($,{...Q,failure:void 0,finishedAt:this.#Y().toISOString(),output:H,status:"completed"});return}let F=_==="verified-receipt"||_==="recoverable-transaction";if(X?.kind==="retry"&&F){await this.#G($,{...Q,failure:void 0,finishedAt:void 0,status:"ready"});return}if(X?.kind==="incompatible"){await this.#G($,{...Q,failure:F9(new j("incompatible",X.message)),finishedAt:this.#Y().toISOString(),status:"incompatible"});return}let J=X?.kind==="ambiguous"?X.message:_==="non-resumable-live"?"Interrupted live operation requires explicit operator reconciliation.":_==="ambiguous-after-dispatch"?"Interrupted paid operation has an ambiguous dispatch outcome.":"Interrupted operation has no compatible reconciliation implementation.",Y=_==="verified-receipt"||_==="recoverable-transaction"?"incompatible":"ambiguous";await this.#G($,{...Q,failure:F9(new j(Y==="incompatible"?"incompatible":"ambiguous",J)),finishedAt:this.#Y().toISOString(),status:Y})}async#T($,Q,Z){let _=!0;while(_){_=!1;let X=await this.#Z.nodes($.runId),F=new Map(X.map((J)=>[J.nodeKey,J]));for(let J of[...Q.graph.nodes].sort((Y,H)=>Y.key.localeCompare(H.key))){let Y=F.get(J.key);if(Y===void 0||Y.status!=="pending")continue;let H=J.dependencies.map((K)=>F.get(K));if(H.some((K)=>K===void 0))throw new j("invalid-data",`Node ${J.key} has a missing dependency.`);if(H.some((K)=>K!==void 0&&fQ1(K))){let K={...Y,finishedAt:this.#Y().toISOString(),status:Z.cancelled?"cancelled":"skipped"};await this.#G($,K),F.set(J.key,K),_=!0;continue}if(H.every((K)=>K?.status==="completed")){let K={...Y,status:"ready"};await this.#G($,K),F.set(J.key,K),_=!0}}}}async#R($,Q,Z,_,X){let F=await this.#Z.nodes($.runId),J=new Map(F.map((H)=>[H.nodeKey,H])),Y=new Map(Q.graph.nodes.map((H)=>[H.key,H]));for(let H of F.filter((K)=>K.status==="ready"||K.status==="approval-required").sort((K,W)=>K.nodeKey.localeCompare(W.nodeKey))){if(Z.pause!==void 0||Z.cancelled)break;if(X.has(H.nodeKey))continue;await this.#N($,_);let K=Y.get(H.nodeKey);if(K===void 0)throw new j("invalid-data",`Run contains unknown node ${H.nodeKey}.`);let W=DV0(Q,K,this.#j),V=NV0(K,J),G;if(W.kind==="operation"){if(!R4(K))throw new j("internal",`Node executor classification changed for ${K.key}.`);G={dependencyOutputs:V.dependencyOutputs,graphPlan:Q,node:K,operation:W.operation.discovery,resolvedInput:V.input,runId:$.runId}}let N=H.preparationPlan;if(N===void 0){await this.#G($,{...H,status:"preparing"}),await this.#Z.assertFence($);let B=G===void 0?TQ1(V):await this.#w($,_,async()=>await this.#W.prepare(G));N=RQ1(Q,K,W.policy,B)}else qQ1(N,Q,K,W.policy);if(!await this.#C($,Q,K,W,N,_)){let B=N6.parse({...H,preparationPlan:N,status:"approval-required",version:zY});await this.#G($,B),Z.pause={nodeKey:K.key,phase:"preparation",planSha256:N.preparationPlanSha256},await this.#Z.appendEvent($,{details:{phase:"preparation",planSha256:N.preparationPlanSha256},kind:"approval-required",nodeKey:K.key,timestamp:this.#Y().toISOString()});break}let L=H.executionPlan;if(L===void 0){await this.#Z.assertFence($);let B=G===void 0?{exactInput:V.input,publicationKeys:[]}:await this.#w($,_,async()=>{if(G.operation.kind!=="slopcamera.studio.run")return await this.#W.plan({...G,preparationPlan:N});return await this.#J.withLease(N_(G.operation.policy.resources,this.#J),async(z)=>{let U=async()=>{await z.assertOwned(),await this.#Z.assertFence($),await this.#N($,_),await this.#Z.assertFence($),await z.assertOwned()};return await U(),await this.#W.plan({...G,preparationPlan:N,application:bE(this.#$,z),abortSignal:_.signal,beforePublication:U})},{signal:_.signal})});L=kQ1(Q,K,W.policy,N,V,B)}else EQ1(L,Q,K,W.policy,N,V);if(!await this.#E($,Q,K,W,L,_)){let B=N6.parse({...H,executionPlan:L,preparationPlan:N,status:"approval-required",version:zY});await this.#G($,B),Z.pause={nodeKey:K.key,phase:"effect",planSha256:L.nodePlanSha256},await this.#Z.appendEvent($,{details:{phase:"effect",planSha256:L.nodePlanSha256},kind:"approval-required",nodeKey:K.key,timestamp:this.#Y().toISOString()});break}let w=N6.parse({...H,executionPlan:L,failure:void 0,preparationPlan:N,status:"ready",version:zY});if(H.status!=="ready"||H.preparationPlan===void 0||H.executionPlan===void 0||H.failure!==void 0)await this.#G($,w);J.set(K.key,w),X.set(K.key,{executionPlan:L,executor:W,record:w,resolved:V})}}async#C($,Q,Z,_,X,F){if(X.requestedPreparation.length===0)return!0;let J=await this.#Z.grants($.runId);if(PQ1(J,Q.graphPlanSha256,X.nodeKey,X.preparationPlanSha256))return!0;if(!OV0(await this.#w($,F,async()=>await this.#Q.authorizePreparation({executor:Z.executor,graphPlanSha256:Q.graphPlanSha256,nodeKey:X.nodeKey,..._.kind==="operation"?{operation:_.operation.discovery}:{},policy:_.policy,preparationPlan:X,runId:$.runId}))))return!1;let H={createdAt:this.#Y().toISOString(),graphPlanSha256:Q.graphPlanSha256,grantedBy:this.#Q.grantedBy,grantId:Pc(),kind:"preparation",nodeKey:X.nodeKey,preparationPlanSha256:X.preparationPlanSha256};return await this.#N($,F),await this.#Z.appendGrant($,H),!0}async#E($,Q,Z,_,X,F){if(_.kind==="operation"&&_.operation.discovery.kind==="slopcamera.studio.run"){let K=this.#$.studioAuthorization;if(K===void 0||!await this.#w($,F,async()=>await K.authorize(qu(X.exactInput))))return!1}let J=await this.#Z.grants($.runId);if(IQ1(J,Q.graphPlanSha256,X.nodeKey,X.nodePlanSha256))return!0;if(!OV0(await this.#w($,F,async()=>await this.#Q.authorizeEffect({executor:Z.executor,executionPlan:X,graphPlanSha256:Q.graphPlanSha256,nodeKey:X.nodeKey,..._.kind==="operation"?{operation:_.operation.discovery}:{},policy:_.policy,runId:$.runId}))))return!1;let H={createdAt:this.#Y().toISOString(),graphPlanSha256:Q.graphPlanSha256,grantedBy:this.#Q.grantedBy,grantId:Pc(),kind:"effect",nodeKey:X.nodeKey,nodePlanSha256:X.nodePlanSha256};return await this.#N($,F),await this.#Z.appendGrant($,H),!0}async#B($,Q,Z,_,X,F,J,Y){for(let H of[...Q.values()].sort((K,W)=>K.record.nodeKey.localeCompare(W.record.nodeKey))){if(kY.now()>=X){F.interrupt("deadline",new j("cancelled","Workflow exceeded the host wall-clock bound."));break}let K=H.executor.policy.resources;if(_.impossible(K)){await this.#G($,{...H.record,failure:F9(new j("incompatible",`Node ${H.record.nodeKey} exceeds the host resource ceiling.`)),finishedAt:this.#Y().toISOString(),status:"incompatible"}),Q.delete(H.record.nodeKey);continue}if(!_.acquire(K,H.executionPlan.publicationKeys))continue;try{if(await this.#Z.assertFence($),await this.#K($.runId)!==void 0){_.release(K,H.executionPlan.publicationKeys),F.interrupt("cancellation",new j("cancelled","Workflow cancellation requested."));break}let W=new AbortController,V=new AbortController,G=N6.parse({...H.record,attempt:H.record.attempt+1,startedAt:this.#Y().toISOString(),status:"running",version:zY});await this.#G($,G),Q.delete(H.record.nodeKey);let N={admissionAbortController:W,abortController:V,cancellable:H.executor.policy.cancellable,executionPlan:H.executionPlan,nodeKey:H.record.nodeKey,fiber:J.fork(c1.exit(this.#f($,H,W,V,X,J)).pipe(c1.tap((D)=>Ec.offer(Y,{nodeKey:H.record.nodeKey,outcome:D})))),publicationKeys:H.executionPlan.publicationKeys,resources:K};Z.set(H.record.nodeKey,N)}catch(W){throw _.release(K,H.executionPlan.publicationKeys),W}}}#f($,Q,Z,_,X,F){return c1.gen(this,function*(){let J=!1,Y,H=!1,K=!1,W=GV0(kY.now(),Q.executor.policy.maxDurationMs),V=Math.min(W,X),G=X<=W?"workflow":"node",N=F.deferred(),D=()=>new j("unavailable",G==="workflow"?"Workflow exceeded the host wall-clock bound.":"Operation exceeded its registered duration bound."),L=F.watch(c1.zipRight(fc(V),c1.sync(()=>{if(J=!0,Y=G,fE.unsafeDone(N,c1.fail(B_(D(),"admission"))),Z.abort(),Q.executor.policy.cancellable)_.abort()})),!0),O=async(U)=>{if(J)throw D();return await F.run(c1.raceFirst(R1("authority",U),fE.await(N)))},w=()=>{if(J)throw new j("cancelled","Workflow node deadline expired before publication.")},B=yield*c1.exit(c1.catchAll(c1.gen(this,function*(){if(yield*R1("operation",()=>O(async()=>await this.#Z.assertFence($))),(yield*R1("operation",()=>O(async()=>await this.#K($.runId))))!==void 0)return yield*c1.fail(B_(new j("cancelled","Workflow cancellation requested."),"operation"));if(Q.executor.policy.effect==="paid-cloud"||Q.executionPlan.publicationKeys.length>0){if(yield*R1("operation",()=>O(async()=>await this.#Z.assertFence($))),(yield*R1("operation",()=>O(async()=>await this.#K($.runId))))!==void 0)return yield*c1.fail(B_(new j("cancelled","Workflow cancellation requested before dispatch or publication."),"operation"))}let U=this.#$,C=async(E,A=U)=>{if(Q.executor.kind!=="operation")throw new j("internal",`Compute node ${Q.record.nodeKey} entered operation execution.`);if(await O(async()=>await this.#Z.assertFence($)),await O(async()=>await this.#Z.cancellation($.runId))!==void 0)throw new j("cancelled","Workflow cancellation requested before project publication.");let k=await O(async()=>await this.#Z.stagingDirectory($,Q.record.nodeKey,Q.executionPlan.nodePlanSha256));await E.assertOwned();let P=bE(A,E),I=Q.executor.operation,x={abortSignal:_.signal,application:P,...Q.executionPlan.expectedProjectGeneration===void 0?{}:{expectedProjectGeneration:Q.executionPlan.expectedProjectGeneration},runFence:{generation:$.generation,owner:$.owner,token:$.token},workflow:{beforePublication:async()=>{if(w(),await E.assertOwned(),await O(async()=>await this.#Z.assertFence($)),w(),await O(async()=>await this.#K($.runId))!==void 0)throw new j("cancelled","Workflow cancellation requested before publication.");w(),H=!0},nodeKey:Q.record.nodeKey,nodePlanSha256:Q.executionPlan.nodePlanSha256,runId:$.runId,workspaceDirectory:k}},b=I.executeEffect===void 0?await I.execute(x,Q.executionPlan.exactInput):oj(await F.run(c1.exit(I.executeEffect(x,Q.executionPlan.exactInput))));if(I.discovery.kind.startsWith("spatial.project.")&&I.discovery.kind!=="spatial.project.snapshot"){let y=b.output;if(y.kind!=="completed")throw new j(y.kind==="ambiguous"?"ambiguous":"conflict",y.message??"Spatial publication did not complete.",{spatialPublication:b.output})}return b},M=N_(Q.executor.policy.resources,this.#J),T={signal:Z.signal,waitTimeoutMilliseconds:Math.min(xQ,Math.max(1,Math.floor(V-kY.now())))},q;if(Q.executor.kind==="compute"){let E=Q.executor.compute,A=this.#F,k=this.#_?.kind!=="replay"||this.#A.has(Q.record.nodeKey);if(A===void 0||!k)return{failure:F9(new j("ambiguous","Trusted compute requires explicit authorization to reload its exact persisted bundle.")),kind:"ambiguous-code"};let P=F.custody(R1("admission",()=>this.#J.withLease(M,async(x)=>{return await x.assertOwned(),K=!0,await A.execute({abortSignal:_.signal,computeKey:E.key,...x.inheritedFileDescriptor<3?{}:{inheritedHostResourceFileDescriptor:x.inheritedFileDescriptor},input:Q.executionPlan.exactInput,nodeKey:Q.record.nodeKey,replayAcknowledged:this.#_?.kind==="replay",timeoutMs:Math.max(1,Math.floor(V-kY.now()))})},T))),I=yield*R1("operation",()=>O(async()=>await P));yield*R1("operation",()=>O(async()=>await this.#Z.assertFence($))),q=yield*PN("operation",()=>Ic(I,{computeKey:E.key,trustedCode:!0},Q.executor.policy.maxOutputBytes))}else{let E=Q.executor.operation,A=Q.executionPlan.publicationKeys.some((I)=>I.startsWith("project:")),k=F.custody(R1("admission",()=>this.#J.withLease(M,async(I)=>E.discovery.kind.startsWith("spatial.project.")?await QK(bE(this.#$,I),String(Q.executionPlan.exactInput.project),async(x)=>await C(I,x),async()=>{if(w(),await I.assertOwned(),_.signal.aborted)throw new j("cancelled","Spatial project custody was cancelled before publication.");if(await O(async()=>await this.#Z.assertFence($)),await O(async()=>await this.#K($.runId))!==void 0)throw new j("cancelled","Workflow cancellation requested before spatial publication.");if(w(),_.signal.aborted)throw new j("cancelled","Spatial project custody was cancelled before publication.");await I.assertOwned()},E.discovery.kind==="spatial.project.migrate"?"mutation":"read"):A?await JV(this.#$,E.discovery.kind,Q.executionPlan.exactInput,async()=>await C(I)):await C(I),T))),P=yield*R1("operation",()=>O(async()=>await k));yield*R1("operation",()=>O(async()=>await this.#Z.assertFence($))),q=yield*PN("operation",()=>Ic(P.output,P.summary.fields,Q.executor.policy.maxOutputBytes,P.receiptReference))}return{kind:"completed",output:q}}),(U)=>PN("operation",()=>{let C=U.cause,M=xQ1(C);if(Q.executor.kind==="compute"){if(M.code==="cancelled"&&!K)return{failure:F9(new j("cancelled","Workflow node was cancelled.")),kind:"cancelled"};if(M.code==="invalid-data"||M.code==="unsupported-plan"||M.code==="incompatible")return{failure:F9(M),kind:"failed"};return{failure:F9(new j("ambiguous",J?Y==="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: ${M.message}`)),kind:"ambiguous-code"}}let T=M.details?.spatialPublication;if(Q.executor.operation.discovery.kind.startsWith("spatial.project.")&&T!==void 0){let E=D8.safeParse(T);if(E.success&&E.data.kind!=="completed")return{failure:F9(M),kind:E.data.kind==="ambiguous"?"ambiguous":"failed"}}if(H&&(Q.executor.policy.resume==="verified-receipt"||Q.executor.policy.resume==="recoverable-transaction"))return{failure:F9(new j("ambiguous",J?Y==="workflow"?"Recoverable publication exceeded the workflow wall-clock bound.":"Recoverable publication exceeded its duration bound.":`Recoverable publication requires reconciliation: ${M.message}`,M.details)),kind:"interrupted"};if(M.code==="cancelled"||_.signal.aborted&&!J)return{failure:F9(new j("cancelled","Workflow node was cancelled.")),kind:"cancelled"};if(Q.executor.policy.resume==="ambiguous-after-dispatch"||Q.executor.policy.resume==="non-resumable-live")return{failure:F9(new j("ambiguous",J?Y==="workflow"?"Operation exceeded the workflow wall-clock bound after dispatch.":"Operation exceeded its duration bound after dispatch.":M.message,M.details)),kind:"ambiguous"};return{failure:F9(J?new j("unavailable",Y==="workflow"?"Operation exceeded the workflow wall-clock bound.":"Operation exceeded its registered duration bound."):M,M.code==="unavailable"||M.code==="subprocess"),kind:"failed"}}))),z=yield*c1.exit(c1.gen(this,function*(){yield*R1("operation",()=>L())}));return yield*VV0.zipLeft(B,z)})}async#S($,Q,Z,_,X){await this.#Z.assertFence($);let F=await this.#Z.node($.runId,Z.nodeKey);if(_.kind==="completed")return await this.#G($,{...F,failure:void 0,finishedAt:this.#Y().toISOString(),output:_.output,status:"completed"}),!1;if(_.kind==="interrupted"){let J=Q.graph.nodes.find((W)=>W.key===Z.nodeKey);if(J===void 0||!R4(J))throw new j("invalid-data",`Missing recoverable operation node ${Z.nodeKey}.`);let Y=await this.#Z.nodes($.runId),H=new Map(Y.map((W)=>[W.nodeKey,W]));return(await this.#U($,Q,J,F,H,X)).deferred}if(await this.#G($,{...F,failure:_.failure,finishedAt:this.#Y().toISOString(),status:_.kind}),_.kind==="ambiguous"){if(Q.graph.nodes.find((Y)=>Y.key===Z.nodeKey)===void 0)throw new j("invalid-data",`Missing graph node ${Z.nodeKey}.`)}return!1}async#I($,Q){let Z=await this.#Z.nodes($.runId),_=new Set(Q.graph.nodes.map((X)=>X.key));for(let X of Z.filter((F)=>F.status==="pending"||F.status==="ready"||F.status==="preparing"||F.status==="approval-required"||F.status==="ambiguous-code").sort((F,J)=>F.nodeKey.localeCompare(J.nodeKey))){if(!_.has(X.nodeKey))continue;await this.#G($,{...X,finishedAt:this.#Y().toISOString(),status:"cancelled"})}}async#b($,Q,Z){let _=await this.#Z.nodes($.runId),X=new Map(Q.graph.nodes.map((J)=>[J.key,J])),F=!1;for(let J of _.filter((Y)=>Y.status==="ready").sort((Y,H)=>Y.nodeKey.localeCompare(H.nodeKey))){let Y=X.get(J.nodeKey);if(Y===void 0)continue;let H=DV0(Q,Y,this.#j);if(!Z.impossible(H.policy.resources))continue;await this.#G($,{...J,failure:F9(new j("incompatible",`Node ${Y.key} exceeds the host resource ceiling.`)),finishedAt:this.#Y().toISOString(),status:"incompatible"}),F=!0}return F}async#G($,Q){let Z=N6.parse(Q),_=N6.parse({attempt:Z.attempt,dependencies:Z.dependencies,...Z.executionPlan===void 0?{}:{executionPlan:Z.executionPlan},...Z.failure===void 0?{}:{failure:Z.failure},...Z.finishedAt===void 0?{}:{finishedAt:Z.finishedAt},executor:Z.executor,nodeKey:Z.nodeKey,...Z.output===void 0?{}:{output:Z.output},...Z.preparationPlan===void 0?{}:{preparationPlan:Z.preparationPlan},...Z.startedAt===void 0?{}:{startedAt:Z.startedAt},status:Z.status,version:Z.version});await this.#Z.assertFence($),await this.#Z.writeNode($,_),await this.#Z.appendEvent($,{details:{status:_.status},kind:"node-status",nodeKey:_.nodeKey,timestamp:this.#Y().toISOString()})}async#k($,Q,Z,_){let X=await this.#Z.summary($.runId);if(SE(X.status))return X;let F=await this.#Z.nodes($.runId),J=new Map(F.map((V)=>[V.nodeKey,V])),Y=LV0(F,Z,_),H=this.#Y().toISOString(),K=Y==="completed"?Sc(Q.graph.outputs,J):void 0,W=FF.parse({counts:CV0(F),...SE(Y)?{finishedAt:H}:{},graphPlanSha256:Q.graphPlanSha256,...K===void 0?{}:{outputs:K},runId:$.runId,startedAt:Z.startedAt,status:Y,updatedAt:H,version:V6});return await this.#Z.writeSummary($,W),W}async#y($,Q,Z,_){let F=(await this.#Z.nodes($.runId)).filter((J)=>J.status==="ready"||J.status==="preparing"||J.status==="running").sort((J,Y)=>J.nodeKey.localeCompare(Y.nodeKey))[0];if(F!==void 0){let J=Q.graph.nodes.find((K)=>K.key===F.nodeKey),Y=J!==void 0&&R4(J)?OB(Q,J,this.#j).discovery.policy.resume:void 0;if(F.status==="running"&&(Y==="verified-receipt"||Y==="recoverable-transaction")){await this.#k($,Q,Z,0);return}await this.#G($,{...F,failure:F9(_),finishedAt:this.#Y().toISOString(),status:_.code==="incompatible"?"incompatible":"failed"})}await this.#k($,Q,Z,0)}async#x($,Q,Z,_){let X=await this.#Z.nodes($.runId);for(let F of[...X].sort((J,Y)=>J.nodeKey.localeCompare(Y.nodeKey))){if(F.status==="approval-required")await this.#G($,{...F,status:"ready"});let J=F.status==="approval-required"?await this.#Z.node($.runId,F.nodeKey):F;if(J.status!=="ready"&&J.status!=="preparing"&&J.status!=="running"&&J.status!=="ambiguous-code")continue;await this.#G($,{...J,failure:F9(new j("incompatible",_.message)),finishedAt:this.#Y().toISOString(),status:"incompatible"})}await this.#T($,Q,Z)}}var vQ1="workflow-runs",gQ1=100;async function MV0($,Q,Z={}){try{return await $.withLease(VN($),async(_)=>{return await _.assertOwned(),await Q(_)},{...Z.signal===void 0?{}:{signal:Z.signal},waitTimeoutMilliseconds:Z.waitTimeoutMilliseconds??xQ})}catch(_){if(!(_ instanceof I2))throw _;switch(_.code){case"WAIT_ABORTED":throw new j("cancelled",_.message);case"OWNERSHIP_LOST":throw new j("conflict",_.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":case"WAIT_TIMEOUT":throw new j("unavailable",_.message,{hostResourceCode:_.code})}}}async function mQ1($){let[Q,Z]=await Promise.all([$.store.graphPlan($.runId),$.store.bundle($.runId)]);if(Q.runtime.externals.kind==="deny-all"&&Q.runtime.externals.modules.length!==0)throw new j("incompatible","A deny-all trusted-code runtime cannot contain external modules.");let _=lK0({bundle:Q.bundle,bytes:Z,externalModules:Q.runtime.externals.modules}),X=await ew({applicationBuild:$.currentApplicationBuild,bundle:_});if(R(X)!==R(Q.runtime))throw new j("incompatible","The trusted-code runtime changed since this run was planned.",{current:X,planned:Q.runtime});let F=wY({bundle:Q.bundle,graph:Q.graph,limits:Q.limits,registry:$.registry,runtime:X,staticBindings:Q.staticBindings,workflowInput:Q.workflowInput});if(R(F)!==R(Q))throw new j("incompatible","Persisted trusted code no longer compiles to the exact authorized graph plan.");return await JE({bundle:_,expectedBuild:{graph:Q.graph,input:Q.workflowInput},...$.inheritedHostResourceFileDescriptor===void 0?{}:{inheritedHostResourceFileDescriptor:$.inheritedHostResourceFileDescriptor},maximumWorkers:$.maximumWorkers,registry:$.registry,temporaryRoot:$.application.paths.privateRoot,workflowInput:Q.workflowInput,workflowInputMode:"parsed"})}function AV0(){return`slopcamera-cli:${String(process.pid)}:${vc()}`}function uQ1(){return`run_${vc().replaceAll("-","")}`}function lQ1($){let Q=new Map;for(let Z of $.graph.nodes){if(!R4(Z))continue;let _=Z.executor.operation;Q.set(`${_.kind}@${String(_.version)}`,_)}return[...Q.entries()].sort(([Z],[_])=>Z.localeCompare(_)).map(([,Z])=>Z)}function dQ1($){let Q=new Map;for(let Z of $.graph.nodes)if(F8(Z))Q.set(Z.executor.compute.key,Z.executor.compute);return[...Q.entries()].sort(([Z],[_])=>Z.localeCompare(_)).map(([,Z])=>Z)}function qY($){return new qc({root:hQ1($.paths.privateRoot,vQ1)})}async function gc($){let Q=qY($.application),Z=uQ1(),_=await Q.create({bundleBytes:new Uint8Array($.bundleBytes),graphPlan:$.graphPlan,runId:Z,runtime:{computes:dQ1($.graphPlan),operations:lQ1($.graphPlan),runtime:$.graphPlan.runtime,version:V6},sourceLocator:$.sourceLocator,workflow:{bundle:$.graphPlan.bundle,sourceLocator:$.sourceLocator,workflow:$.graphPlan.graph.workflow}});return{runId:Z,store:Q,summary:_}}function cQ1($){let Q=new Set(["local-media","project-state"]);return $.preparation.every((Z)=>Q.has(Z))}function pQ1($){return $.effect!=="paid-cloud"&&$.effect!=="live-control"}function sQ1(){return{authorizeEffect:($)=>Promise.resolve(pQ1($.policy)),authorizePreparation:($)=>Promise.resolve(cQ1($.policy)),grantedBy:"slopcamera-local-cli"}}async function nQ1($,Q,Z,_){let X;try{X=await $.events(Q)}catch(J){if(J instanceof j&&J.code==="conflict")return Z;throw J}let F=Z;for(let J of X){if(J.sequence<=Z)continue;_(J),F=Math.max(F,J.sequence)}return F}async function yE($){let Q=$.store??qY($.application),Z=$.hostResourceCoordinator??F_(),_=await MV0(Z,async(W)=>await tw($.application,W.inheritedFileDescriptor<3?{}:{inheritedFileDescriptors:[W.inheritedFileDescriptor]})),X=$.replayAmbiguousCode??[];if($.compute!==void 0&&X.length>0)throw new j("usage","A workflow run cannot use a fresh code worker and persisted compute replay together.");let F=!1,J=X.length===0?$.compute:{kind:"replay",load:async({signal:W,waitTimeoutMilliseconds:V})=>{if(F)throw new j("conflict","The persisted trusted-code worker pool was already loaded.");F=!0;let G=await MV0(Z,async(N)=>await mQ1({application:$.application,currentApplicationBuild:_,inheritedHostResourceFileDescriptor:N.inheritedFileDescriptor,maximumWorkers:j70($.jobs,X,Z),registry:$.registry,runId:$.runId,store:Q}),{signal:W,waitTimeoutMilliseconds:V});return{executor:G,release:async()=>await G.close()}},nodeKeys:X},Y=new hc({application:$.application,authorization:sQ1(),currentApplicationBuild:_,...J===void 0?{}:{compute:J},hostLimits:{maxJobs:$.jobs},hostResourceCoordinator:Z,jobs:$.jobs,nodePlanner:gW0($.application),owner:AV0(),registry:$.registry,store:Q});if($.onEvent===void 0)return await Y.run($.runId);let H=Y.run($.runId).then((W)=>({kind:"result",result:W}),(W)=>({error:W,kind:"error"})),K=0;while(!0){let W=await Promise.race([H,new Promise((V)=>{setTimeout(V,gQ1)})]);if(K=await nQ1(Q,$.runId,K,$.onEvent),W===void 0)continue;if(W.kind==="error")throw W.error;return W.result}}async function TV0($){let Q=qY($.application),Z=AV0(),_=await Q.acquireClaim($.runId,{owner:Z});try{let[X,F]=await Promise.all([Q.graphPlan($.runId),Q.node($.runId,$.nodeKey)]);if(F.status!=="approval-required")throw new j("conflict",`Node ${$.nodeKey} is not awaiting approval.`);let J={createdAt:new Date().toISOString(),graphPlanSha256:X.graphPlanSha256,grantedBy:"slopcamera-local-cli",grantId:vc(),nodeKey:$.nodeKey},Y;if($.planKind==="preparation"){let H=F.preparationPlan?.preparationPlanSha256;if(H!==$.planHash)throw new j("conflict","The preparation approval hash does not match the pending node plan.",{actual:H,requested:$.planHash});Y={...J,kind:"preparation",preparationPlanSha256:$.planHash}}else{let H=F.executionPlan?.nodePlanSha256;if(H!==$.planHash)throw new j("conflict","The effect approval hash does not match the pending node plan.",{actual:H,requested:$.planHash});Y={...J,kind:"effect",nodePlanSha256:$.planHash}}return await Q.appendGrant(_,Y)}finally{await Q.releaseClaim(_).catch(()=>{return})}}async function RV0($){return await qY($.application).requestCancellation($.runId,"slopcamera-local-cli")}async function kV0($,Q){return(await qY($).list()).slice(0,Q)}async function qV0($){let Q=qY($.application),[Z,_,X,F]=await Promise.all([Q.summary($.runId),Q.workflow($.runId),Q.nodes($.runId),Q.outputs($.runId)]),J=$.nodes==="all"?X:X.filter((Y)=>["ambiguous","ambiguous-code","approval-required","failed","incompatible"].includes(Y.status));return{graphPlanSha256:Z.graphPlanSha256,nodes:J,outputs:F?.outputs??null,summary:Z,workflow:_.workflow}}function xE($){let Q=$.summary,Z=[`${Q.runId} ${Q.status} ${Q.graphPlanSha256}`,`nodes completed=${String(Q.counts.completed)} failed=${String(Q.counts.failed)} skipped=${String(Q.counts.skipped)} pending=${String(Q.counts.pending)} cancelled=${String(Q.counts.cancelled)}`];if($.pause!==void 0){let _=$.pause.phase==="effect"?"--node-plan":"--preparation-plan";Z.push(`next slopcamera runs approve ${Q.runId} ${$.pause.nodeKey} ${_} ${$.pause.planSha256}`,`then slopcamera runs resume ${Q.runId}`)}else if(Q.status!=="completed"&&Q.status!=="cancelled")Z.push(`next slopcamera runs show ${Q.runId} --nodes failed`);return Z.join(`
5635
- `)}var LB="3.9.1",aQ1=34359738368,uV0=34359738368;function tQ1($,Q){return uc($,{assertOwned:async()=>await Q.assertOwned(),claims:Q.claims,inheritedFileDescriptor:Q.inheritedFileDescriptor,inheritedFileDescriptors:[Q.inheritedFileDescriptor],profile:Q.profile,ticket:Q.ticket})}function uc($,Q){let Z=$.hostResourceLease,_=Z?.inheritedFileDescriptors??[],X=Q.inheritedFileDescriptors.every((K)=>_.includes(K)),F=_.every((K)=>Q.inheritedFileDescriptors.includes(K));if(Z!==void 0&&(Z.profile.id!==Q.profile.id||Z.profile.capacities.length!==Q.profile.capacities.length||Z.profile.capacities.some((K)=>{return Q.profile.capacities.find((V)=>V.resource===K.resource)?.limit!==K.limit})))throw new j("unavailable","Nested host-resource phases must use the same machine profile.");let J=[..._,...Q.inheritedFileDescriptors].filter((K,W,V)=>V.indexOf(K)===W);if(J.length>16)throw new j("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");let Y=Z===void 0||F?Q:X?Z:{assertOwned:async()=>{await Z.assertOwned(),await Q.assertOwned()},claims:N70(Z.claims,Q.claims),inheritedFileDescriptor:Q.inheritedFileDescriptor,inheritedFileDescriptors:J,profile:Q.profile,ticket:Q.ticket},H=(K=[])=>[...K,...Y.inheritedFileDescriptors].filter((W,V,G)=>G.indexOf(W)===V);return{...$,capabilities:async(K)=>await $.capabilities(H(K)),capability:async(K,W,V)=>await $.capability(K,W,H(V)),hostResourceLease:Y,runner:{run:async(K,W={})=>{await Y.assertOwned();let V=H(W.inheritedFileDescriptors);if(V.length>16)throw new j("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");return await $.runner.run(K,{...W,inheritedFileDescriptors:V})}}}}function eQ1($){switch($.code){case"WAIT_ABORTED":return new j("cancelled",$.message);case"OWNERSHIP_LOST":return new j("conflict",$.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":case"WAIT_TIMEOUT":return new j("unavailable",$.message,{hostResourceCode:$.code})}}async function $31($,Q,Z){let _=D70(Q,$.hostResourceCoordinator);await bY($,_,Z,$.abortSignal)}async function bY($,Q,Z,_){if(Q.length===0)return await Z($);try{return await $.hostResourceCoordinator.withLease(Q,async(X)=>{return await X.assertOwned(),await Z(tQ1($,X))},{..._===void 0?{}:{signal:_},waitTimeoutMilliseconds:xQ})}catch(X){if(X instanceof I2)throw eQ1(X);throw X}}async function mc($,Q,Z){let _=N_([{amount:1,resource:"cpu"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"local-io"}],$.hostResourceCoordinator);if($.hostResourceLease!==void 0){if(await $.hostResourceLease.assertOwned(),rl($.hostResourceLease.claims,_))return await Z($4($))}return await bY($,Wq($.hostResourceLease?.claims??[],_),async(X)=>await Z($4(X)),Q)}function $4($,Q){let Z=(X)=>({available:X.available,...X.command===void 0?{}:{command:X.command},name:X.name,...X.reason===void 0?{}:{reason:X.reason},...X.version===void 0?{}:{version:X.version}}),_={capabilities:async(X)=>(await $.capabilities(X)).map(Z),capability:async(X)=>Z(await $.capability(X)),clock:{now:()=>new Date($.clock()),timestampMilliseconds:$.clock},htmlOverlayRenderer:new xl({cacheRoot:G5($.paths.privateRoot,"html-overlay-modules-v1"),fetch:$.fetch}),...$.hostResourceLease===void 0?{}:{hostResourceLease:$.hostResourceLease},machineStateRoot:$.stateRoot,paths:$.paths,runner:$.runner,spatialReviewProvider:$.spatialReviewProviderFactory({credential:()=>fU($.io.env),fetch:$.fetch,transport:$.gatewayCatalogTransport})};return{..._,gatewayPort:JK0({application:_,createService:async(X,F)=>await HG0(F===void 0?$:uc($,F),X),inspectMedia:async(X,F,J)=>{let Y=J===void 0?$:uc($,J);return(await vN(Y,X.map((K)=>({data:K.data,mediaType:K.mediaType,path:K.path})),F)).map((K)=>{if(K.url!==void 0)throw new j("internal","Gateway workflow preparation unexpectedly produced a remote media input.");let W=K.facts;return{...W?.durationSeconds===void 0?{}:{durationSeconds:W.durationSeconds},...W?.height===void 0?{}:{height:W.height},...W?.width===void 0?{}:{width:W.width}}})},now:$.io.now,resolveProviderOptions:(X,F)=>{if(F.aborted)throw new j("cancelled","Gateway provider-options resolution was cancelled.");return Promise.resolve(Q)}})}}function s6($){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 E8($,Q){let Z=FY($,Q);if((!Z.available||Z.command===void 0)&&Q==="face-analyzer")throw new j("unavailable","Face analysis needs a small helper that isn't built on this Mac yet. In a Slopcamera checkout, run bun run build:desktop:analysis:macos; it uses Apple's command line tools and asks before installing them.",{capability:Q,...Z.reason===void 0?{}:{reason:Z.reason}});if(!Z.available||Z.command===void 0)throw new j("unavailable",`${Q} is unavailable${Z.reason===void 0?".":`: ${Z.reason}`}`,{capability:Q});return Z.command}async function TK($,Q){return await Promise.all(Q.map(async(Z)=>await $.capability(Z)))}async function xY($,Q){return E8([await $.capability(Q)],Q)}function l0($,Q,Z,_){if(Q)XQ($,Z);else FQ($,_())}function lV0($,Q,Z){let _=AY0(H5({toolVersion:Z}),Z);l0($,Q,_,()=>_.modules.map((X)=>`${X.moduleId}@${X.version} ${X.trust} operations=${X.operations.length} workflows=${X.workflows.length} tools=${X.tools.length} ${X.title}`).join(`
5635
+ `)}var LB="3.9.2",aQ1=34359738368,uV0=34359738368;function tQ1($,Q){return uc($,{assertOwned:async()=>await Q.assertOwned(),claims:Q.claims,inheritedFileDescriptor:Q.inheritedFileDescriptor,inheritedFileDescriptors:[Q.inheritedFileDescriptor],profile:Q.profile,ticket:Q.ticket})}function uc($,Q){let Z=$.hostResourceLease,_=Z?.inheritedFileDescriptors??[],X=Q.inheritedFileDescriptors.every((K)=>_.includes(K)),F=_.every((K)=>Q.inheritedFileDescriptors.includes(K));if(Z!==void 0&&(Z.profile.id!==Q.profile.id||Z.profile.capacities.length!==Q.profile.capacities.length||Z.profile.capacities.some((K)=>{return Q.profile.capacities.find((V)=>V.resource===K.resource)?.limit!==K.limit})))throw new j("unavailable","Nested host-resource phases must use the same machine profile.");let J=[..._,...Q.inheritedFileDescriptors].filter((K,W,V)=>V.indexOf(K)===W);if(J.length>16)throw new j("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");let Y=Z===void 0||F?Q:X?Z:{assertOwned:async()=>{await Z.assertOwned(),await Q.assertOwned()},claims:N70(Z.claims,Q.claims),inheritedFileDescriptor:Q.inheritedFileDescriptor,inheritedFileDescriptors:J,profile:Q.profile,ticket:Q.ticket},H=(K=[])=>[...K,...Y.inheritedFileDescriptors].filter((W,V,G)=>G.indexOf(W)===V);return{...$,capabilities:async(K)=>await $.capabilities(H(K)),capability:async(K,W,V)=>await $.capability(K,W,H(V)),hostResourceLease:Y,runner:{run:async(K,W={})=>{await Y.assertOwned();let V=H(W.inheritedFileDescriptors);if(V.length>16)throw new j("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");return await $.runner.run(K,{...W,inheritedFileDescriptors:V})}}}}function eQ1($){switch($.code){case"WAIT_ABORTED":return new j("cancelled",$.message);case"OWNERSHIP_LOST":return new j("conflict",$.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":case"WAIT_TIMEOUT":return new j("unavailable",$.message,{hostResourceCode:$.code})}}async function $31($,Q,Z){let _=D70(Q,$.hostResourceCoordinator);await bY($,_,Z,$.abortSignal)}async function bY($,Q,Z,_){if(Q.length===0)return await Z($);try{return await $.hostResourceCoordinator.withLease(Q,async(X)=>{return await X.assertOwned(),await Z(tQ1($,X))},{..._===void 0?{}:{signal:_},waitTimeoutMilliseconds:xQ})}catch(X){if(X instanceof I2)throw eQ1(X);throw X}}async function mc($,Q,Z){let _=N_([{amount:1,resource:"cpu"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"local-io"}],$.hostResourceCoordinator);if($.hostResourceLease!==void 0){if(await $.hostResourceLease.assertOwned(),rl($.hostResourceLease.claims,_))return await Z($4($))}return await bY($,Wq($.hostResourceLease?.claims??[],_),async(X)=>await Z($4(X)),Q)}function $4($,Q){let Z=(X)=>({available:X.available,...X.command===void 0?{}:{command:X.command},name:X.name,...X.reason===void 0?{}:{reason:X.reason},...X.version===void 0?{}:{version:X.version}}),_={capabilities:async(X)=>(await $.capabilities(X)).map(Z),capability:async(X)=>Z(await $.capability(X)),clock:{now:()=>new Date($.clock()),timestampMilliseconds:$.clock},htmlOverlayRenderer:new xl({cacheRoot:G5($.paths.privateRoot,"html-overlay-modules-v1"),fetch:$.fetch}),...$.hostResourceLease===void 0?{}:{hostResourceLease:$.hostResourceLease},machineStateRoot:$.stateRoot,paths:$.paths,runner:$.runner,spatialReviewProvider:$.spatialReviewProviderFactory({credential:()=>fU($.io.env),fetch:$.fetch,transport:$.gatewayCatalogTransport})};return{..._,gatewayPort:JK0({application:_,createService:async(X,F)=>await HG0(F===void 0?$:uc($,F),X),inspectMedia:async(X,F,J)=>{let Y=J===void 0?$:uc($,J);return(await vN(Y,X.map((K)=>({data:K.data,mediaType:K.mediaType,path:K.path})),F)).map((K)=>{if(K.url!==void 0)throw new j("internal","Gateway workflow preparation unexpectedly produced a remote media input.");let W=K.facts;return{...W?.durationSeconds===void 0?{}:{durationSeconds:W.durationSeconds},...W?.height===void 0?{}:{height:W.height},...W?.width===void 0?{}:{width:W.width}}})},now:$.io.now,resolveProviderOptions:(X,F)=>{if(F.aborted)throw new j("cancelled","Gateway provider-options resolution was cancelled.");return Promise.resolve(Q)}})}}function s6($){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 E8($,Q){let Z=FY($,Q);if((!Z.available||Z.command===void 0)&&Q==="face-analyzer")throw new j("unavailable","Face analysis needs a small helper that isn't built on this Mac yet. In a Slopcamera checkout, run bun run build:desktop:analysis:macos; it uses Apple's command line tools and asks before installing them.",{capability:Q,...Z.reason===void 0?{}:{reason:Z.reason}});if(!Z.available||Z.command===void 0)throw new j("unavailable",`${Q} is unavailable${Z.reason===void 0?".":`: ${Z.reason}`}`,{capability:Q});return Z.command}async function TK($,Q){return await Promise.all(Q.map(async(Z)=>await $.capability(Z)))}async function xY($,Q){return E8([await $.capability(Q)],Q)}function l0($,Q,Z,_){if(Q)XQ($,Z);else FQ($,_())}function lV0($,Q,Z){let _=AY0(H5({toolVersion:Z}),Z);l0($,Q,_,()=>_.modules.map((X)=>`${X.moduleId}@${X.version} ${X.trust} operations=${X.operations.length} workflows=${X.workflows.length} tools=${X.tools.length} ${X.title}`).join(`
5636
5636
  `))}function z_($,Q){let Z=YF($,Q);return Z===""||!Z.startsWith("..")&&!dE(Z)}async function lc($,Q){let Z=await d$($.directory.path,Q);if(!cM($,Z).startsWith("renders/"))throw new j("unsafe-path","Render outputs must remain under the bundle's renders/ directory so raw capture files stay immutable.");let X=await d$($.directory.path,"renders");await d1(X),await d1(mQ(Z));let[F,J]=await Promise.all([gQ(X),gQ(mQ(Z))]);if(!z_(F,J))throw new j("unsafe-path",`Render output crosses a symlink outside renders/: ${Q}`);try{if((await U_(Z)).isSymbolicLink())throw new j("unsafe-path",`Render output may not be a symlink: ${Q}`)}catch(Y){if(Y instanceof j)throw Y;if(!(Y instanceof Error&&("code"in Y)&&Y.code==="ENOENT"))throw Y}return Z}async function Q31($,Q,Z){let _=await lc($,Q),X=cM($,_),F=X.toLowerCase();if(yY(X).toLowerCase()!==".json")throw new j("usage","A resolved render plan output must use a .json path under renders/.");if(F.endsWith(".mp4.plan.json"))throw new j("unsafe-path",`A render plan alias may not overwrite a video receipt: ${Q}`);if(/^renders\/resolved-[a-f0-9]{64}\.json$/u.test(F)&&X!==Z)throw new j("unsafe-path",`A render plan alias may not use the canonical resolved-plan namespace: ${Q}`);return{absolute:_,relative:X}}async function wB($,Q,Z={}){let _=await d$($,Q),X=YF($,_);if(!X.startsWith("renders/")||dE(X))throw new j("unsafe-path","Project render artifacts must remain under the project's renders/ directory.");if(Z.videoOutput){let H=X.split("/"),K=H.at(-1),W=new Set([".filter-graphs",".overlay-cache","derived","plans"]);if(H[0]!=="renders"||W.has(H[1]?.toLowerCase()??""))throw new j("unsafe-path",`Project video output may not use a reserved render-artifact subtree: ${Q}`);if(K===void 0||K.toLowerCase()===".mp4"||yY(K).toLowerCase()!==".mp4")throw new j("usage","Project render output must be a final .mp4 file under renders/.")}let F=G5($,"renders");await d1(F),await d1(mQ(_));let[J,Y]=await Promise.all([gQ(F),gQ(mQ(_))]);if(!z_(J,Y))throw new j("unsafe-path",`Project render path crosses a symlink outside renders/: ${Q}`);try{let H=await U_(_);if(H.isSymbolicLink()||!H.isFile())throw new j("unsafe-path",`Project render leaf must be a physical regular file: ${Q}`)}catch(H){if(H instanceof j)throw H;if(!(H instanceof Error&&("code"in H)&&H.code==="ENOENT"))throw H}return{absolute:_,relative:X}}async function cE($){return await NX($)}function dV0($,Q,Z){return{operation:Q,planHash:HX(Z),planId:Z.planId,planPath:DJ,recordingId:$.manifest.recordingId}}async function EV0($,Q,Z,_,X){let F=q2(Z);await d1(G5($.directory.path,"edits")),await uj($.fileSystem,F,DJ);let J=dV0($,Q,F);l0(X,_,J,()=>`${Q} ${Z.planId} ${String(J.planHash)}`)}function SY($){if($!=="linear"&&$!=="ease-in"&&$!=="ease-out"&&$!=="ease-in-out"&&$!=="spring")throw new j("usage",`Unsupported easing: ${$}`);return{kind:$}}function PV0($,Q,Z,_,X,F){let J=$??"none";if(J==="none")return{kind:"none"};let Y=I4(Q??Z);if(J==="fade")return{durationUs:Y,easing:SY(_),kind:J};if(J==="scale")return{durationUs:Y,easing:SY(_),fromScale:X,kind:J};let H=/^slide-(up|down|left|right)$/u.exec(J);if(H?.[1]==="up"||H?.[1]==="down"||H?.[1]==="left"||H?.[1]==="right")return{direction:H[1],distancePx:F,durationUs:Y,easing:SY(_),kind:"slide"};throw new j("usage",`Unsupported overlay animation: ${J}`)}function Z31($){let Q=$.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test(Q))return{kind:"id",value:Q};if([...$].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test($))return{kind:"unicode",value:$};return{kind:"name",value:$}}function JF($,Q,Z){let _=I4($,Z),X=I4(Q,Z);if(X<=_)throw new j("usage",`Time range must increase: ${$}..${Q}`);return{endUs:X,startUs:_}}function _31($){let Q=$.length+1;while($.some(({overlayId:Z})=>Z===`overlay_manual${String(Q).padStart(4,"0")}`))Q+=1;return`overlay_manual${String(Q).padStart(4,"0")}`}function X31($){let Q=$.length+1;while($.includes(`zoom_manual${String(Q).padStart(4,"0")}`))Q+=1;return`zoom_manual${String(Q).padStart(4,"0")}`}async function cV0($,Q,Z,_,X,F){let{startUs:J,endUs:Y}=JF(_.from,_.to,X),H=F?.({endUs:Y,startUs:J})??Y-J;if(H<=0)throw new j("conflict","Overlay range has no visible kept output time.");let K=_.overlayKind==="emoji"?await xV($.paths.repositoryRoot,_.source,_.variant,_.provider):void 0,W=_.overlayKind==="emoji"?await gA(Q,K):await vA(Q,_.source,_.overlayKind),{created:V,...G}=W,N=async()=>{let D=Z.some((L)=>L.source.asset.path===G.path);if(V&&!D)await hN(G5(Q,G.path),{force:!0})};try{let D=await d$(Q,G.path),L=G.mediaType==="image/svg+xml"?{...await qJ(D),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await xZ(await xY($,"ffprobe"),$.runner,D),O={height:"pixelHeight"in L?L.pixelHeight:L.height,width:"pixelWidth"in L?L.pixelWidth:L.width},w;if(_.overlayKind==="image"||_.overlayKind==="svg")w={asset:G,kind:_.overlayKind};else if(_.overlayKind==="emoji")w={asset:G,kind:"emoji",provider:K.provider,selector:Z31(_.source)};else{if(_.loop&&_.freezeEnd)throw new j("usage","Use only one of --loop and --freeze-end.");let z=I4(_.sourceIn??"0us",X),U=_.sourceOut===void 0?void 0:I4(_.sourceOut,X);if(L.durationUs===null||L.durationUs<=0)throw new j("invalid-data","Animated overlay media must report a positive finite duration.");if(_.overlayKind==="video"&&_.animatedAudio!=="mute"&&!L.hasAudio)throw new j("conflict",`Video overlay audio policy ${_.animatedAudio} requires an audio stream in the source media.`);let C=hV({mediaDurationUs:L.durationUs,outputDurationUs:H,playbackRate:_.playbackRate,sourceInUs:z,sourceOutUs:U}),M={audioEndUs:L.audioEndUs,audioStartUs:L.audioStartUs,audioStreamIndex:L.audioStreamIndex,endBehavior:_.loop?"loop":_.freezeEnd?"freeze-end":"hide",playbackRate:_.playbackRate,streamStartUs:L.videoStartUs,videoStreamIndex:L.videoStreamIndex,...C};if(_.overlayKind==="gif")w={asset:G,audioPolicy:{kind:"mute"},kind:"gif",playback:M};else{let T=_.animatedAudio==="mute"?{kind:"mute"}:_.animatedAudio==="mix"?{kind:"mix",volume:_.audioVolume}:{duckPrimaryTo:_.duckPrimaryTo,kind:"duck-primary",volume:_.audioVolume};w={asset:G,audioPolicy:T,kind:"video",playback:M}}}if(_.width===void 0!==(_.height===void 0))throw new j("usage","Overlay pixel size requires both --width and --height.");let B=z5.safeParse({anchor:_.anchor,blendMode:_.blendMode,coordinateSpace:"output-pixels",crop:_.crop===void 0?{kind:"none"}:{bottom:_.crop[3],kind:"normalized-insets",left:_.crop[0],right:_.crop[2],top:_.crop[1]},entrance:PV0(_.entrance,_.entranceDuration,"250ms",_.easing,_.entranceFromScale,_.slideDistance),exit:PV0(_.exit,_.exitDuration,"250ms",_.easing,_.exitToScale,_.slideDistance),fit:_.fit,intrinsicSize:O,mask:_.cornerRadius===void 0?{kind:"none"}:{kind:"rounded-rectangle",radiusPx:_.cornerRadius},motion:_.motionKeyframes.length===0?{kind:"none"}:{keyframes:_.motionKeyframes.map((z)=>({easing:SY(_.easing),offset:z.offset,opacityMultiplier:z.opacity,positionOffset:{x:z.position[0],y:z.position[1]},rotationOffsetDegrees:z.rotation,scaleMultiplier:z.scale})),kind:"keyframes",timeline:"visible-output"},opacity:_.opacity,overlayId:_31(Z),position:{x:_.position[0],y:_.position[1]},range:{endUs:Y,startUs:J},rotationDegrees:_.rotation,scale:_.scale,size:_.width===void 0||_.height===void 0?{kind:"intrinsic"}:{height:_.height,kind:"pixels",width:_.width},source:w,zIndex:_.zIndex});if(!B.success)throw new j("usage",`Invalid overlay: ${B.error.issues[0]?.message??"unknown error"}`);return{operation:B.data,rollback:N}}catch(D){throw await N(),D}}function F31($,Q,Z,_){let X=pV0($,Q,void 0,_),F=X.displayId??Z.sources.displays.find(({isPrimary:J})=>J)?.displayId;if(F===void 0)throw new j("not-found","Manual zoom requires a selected or primary display.");return x_.parse({...X,displayId:F,kind:"manual"})}function pV0($,Q,Z,_){let{startUs:X,endUs:F}=JF($.from,$.to,_),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}},Y=F-X,H=Math.min(300000,Math.max(0,Math.floor(Y/2))),K=$.enterDuration===void 0?H:I4($.enterDuration,_),W=$.exitDuration===void 0?H:I4($.exitDuration,_),V=Fx.safeParse({...$.display===void 0?{}:{displayId:$.display},easing:SY($.easing),enterDurationUs:K,exitDurationUs:W,...Z===void 0?{}:{placementId:Z},range:{endUs:F,startUs:X},scale:$.scale,target:J,zoomId:X31(Q)});if(!V.success)throw new j("usage",`Invalid zoom: ${V.error.issues[0]?.message??"unknown error"}`);return V.data}async function J31($,Q){let Z=await q$($.paths.artifactRoot,Q.recording);if(Z.manifest.state!=="stopped")throw new j("conflict","Editing requires a stopped recording with an immutable timeline, media, and events.");if(Q.edit.operation==="init"){let Y=await ty(Z),H=Y??C00(Z.manifest,Q40(Z.manifest),$.io.now().toISOString());await EV0(Z,Y===null?"init":"init-existing",H,Q.json,$.io);return}let _=await HO(Z);if(Q.edit.operation==="show"){l0($.io,Q.json,_,()=>`${_.planId} ${HX(_)} keep=${_.keep.length} speed=${_.speed.length} zooms=${_.zooms.length} overlays=${_.overlays.length}`);return}let X=$.io.now().toISOString(),F,J=Q.edit;switch(J.operation){case"trim":F=M00(_,JF(J.from,J.to,Q.fps),X);break;case"cut":F=_M(_,JF(J.from,J.to,Q.fps),X);break;case"speed":F=tf(_,JF(J.from,J.to,Q.fps),J.rate,X);break;case"zoom-add":F=A00(_,F31(J,_.zooms.map((Y)=>Y.zoomId),Z.manifest,Q.fps),X);break;case"zoom-remove":F=T00(_,J.id,X);break;case"overlay-add":{let Y=await cV0($,Z.directory.path,_.overlays,J,Q.fps,(K)=>p7(wM(_),K).reduce((W,V)=>W+V.output.endUs-V.output.startUs,0));try{F=q2(R00(_,Y.operation,X)),await d1(G5(Z.directory.path,"edits")),await uj(Z.fileSystem,F,DJ)}catch(K){throw await Y.rollback(),K}let H=dV0(Z,J.operation,F);l0($.io,Q.json,H,()=>`${J.operation} ${F.planId} ${String(H.planHash)}`);return}case"overlay-remove":F=k00(_,J.id,X);break;case"cursor":F=ZJ({..._,effects:{..._.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:X});break;case"clicks":F=ZJ({..._,effects:{..._.effects,clicks:J.enabled?{color:J.color,durationUs:I4(J.duration,Q.fps),enabled:!0,radiusPx:J.radius,style:J.style}:{enabled:!1}},updatedAt:X});break;case"keystrokes":F=ZJ({..._,effects:{..._.effects,keystrokes:J.enabled?{enabled:!0,holdUs:I4(J.stopAfter??"1200ms",Q.fps),maxKeys:8,position:"bottom-right",secureText:"hide"}:{enabled:!1}},updatedAt:X});break;case"typed-text":if(J.enabled&&Z.manifest.capture.typedText!=="enabled")throw new j("conflict","Typed-text rendering cannot be enabled because typed-text capture was disabled for this recording.");F=ZJ({..._,effects:{..._.effects,typedText:J.enabled?{enabled:!0,idleTimeoutUs:I4(J.idleTimeout,Q.fps),maxCharacters:J.maxCharacters,placement:J.placement,secureText:"hide"}:{enabled:!1}},updatedAt:X});break}await EV0(Z,J.operation,F,Q.json,$.io)}async function sV0($,Q,Z){if(Q.manifest.state!=="stopped")throw new j("conflict","Inactivity analysis requires a stopped recording with immutable media and events.");let _=await TK($,["ffmpeg","ffprobe"]),X=E8(_,"ffmpeg"),F=E8(_,"ffprobe"),J=new KO({ffmpeg:X,ffprobe:F,runner:$.runner}),Y=Q.manifest.tracks.filter((L)=>L.enabled&&L.kind==="display-video");if(Y.length===0)throw new j("invalid-data","Recording has no enabled display tracks to analyze.");let H=await PZ(Y,4,async(L)=>{let O=[];for(let w of L.segments){if(w.integrity.state!=="verified"||w.integrity.bytes<=0)throw new j("invalid-data",`Inactivity media ${w.path} does not have verified integrity.`);let B=await t1({expected:w.integrity,label:`Inactivity media ${w.path}:${w.streamIndex}`,path:w.path,repositoryRoot:Q.directory.path}),z=await J.freeze(B,w.streamIndex,Z.minDurationUs,Z.motionThreshold,w.startUs);O.push(...z.filter(({startUs:U,endUs:C})=>U<w.endUs&&C>w.startUs).map(({startUs:U,endUs:C})=>({confidence:1,meanFrameDifference:Z.motionThreshold,range:{startUs:Math.max(U,w.startUs),endUs:Math.min(C,w.endUs)}})))}return{intervals:O,trackId:L.trackId}}),K=Z.protectAudio?Q.manifest.tracks.filter((L)=>L.enabled&&(L.kind==="system-audio"||L.kind==="microphone-audio")):[],W=await PZ(K,4,async(L)=>{let O=[];for(let w of L.segments){if(w.integrity.state!=="verified"||w.integrity.bytes<=0)throw new j("invalid-data",`Inactivity media ${w.path} does not have verified integrity.`);let B=await t1({expected:w.integrity,label:`Inactivity media ${w.path}:${w.streamIndex}`,path:w.path,repositoryRoot:Q.directory.path}),z=await J.silence(B,w.streamIndex,Z.minDurationUs,w.startUs);O.push(...z.filter(({startUs:U,endUs:C})=>U<w.endUs&&C>w.startUs).map(({startUs:U,endUs:C})=>({peakDb:-45,range:{startUs:Math.max(U,w.startUs),endUs:Math.min(C,w.endUs)}})))}return{intervals:O,trackId:L.trackId}}),V=FY(_,"ffmpeg").version??"unknown",G=Cz.parse({audio:W,displays:H,kind:"slopcamera.analyzer-evidence",schemaVersion:1,sourceDurationUs:Q.manifest.timeline.durationUs,tool:{name:"ffmpeg-freezedetect-silencedetect",version:V.slice(0,128)}});await d1(G5(Q.directory.path,"analysis")),await Q.fileSystem.writeTextAtomic("analysis/inactivity-v1.json",`${R(G)}
5637
5637
  `);let N=await cE(Q),D=L00(G,N,{edgeHandleUs:250000,interactionHandleUs:750000,minimumCutUs:Z.minDurationUs,cursorMovementThresholdPx:2,requireAudioSilence:Z.protectAudio});return{evidence:G,result:D}}async function Y31($,Q){let Z=await q$($.paths.artifactRoot,Q.recording);if(Z.manifest.state!=="stopped")throw new j("conflict","Inactivity analysis requires a stopped recording with immutable media and events.");let _=await HO(Z),X=await sV0($,Z,{minDurationUs:I4(Q.minDuration),motionThreshold:Q.motionThreshold,protectAudio:Q.protectAudio}),F=_;if(Q.apply&&Q.handle!=="keep"){for(let Y of X.result.cuts)F=Q.handle==="cut"?_M(F,Y,$.io.now().toISOString()):tf(F,Y,Q.speedRate,$.io.now().toISOString());F=q2(F),await d1(G5(Z.directory.path,"edits")),await uj(Z.fileSystem,F,DJ)}let J={applied:Q.apply&&Q.handle!=="keep",candidateCount:X.result.candidateCount,cuts:X.result.cuts,evidencePath:"analysis/inactivity-v1.json",handle:Q.handle,planHash:HX(F),protectedInteractionCount:X.result.protectedInteractionCount,recordingId:Z.manifest.recordingId};l0($.io,Q.json,J,()=>`${J.cuts.length} inactivity range(s), ${J.applied?"applied":"dry-run"}; plan ${J.planHash}`)}async function H31($,Q){let Z=await i4($.paths.projectRoot,Q.recording);if(Q.apply&&Q.handle!=="keep")rV0(Z.project,"Automated project inactivity edits");let _=await TK($,["ffmpeg","ffprobe"]),X=E8(_,"ffmpeg"),F=E8(_,"ffprobe"),J=FY(_,"ffmpeg").version??"unknown",Y=await j40({artifactRoot:$.paths.artifactRoot,config:{...OJ,minimumCutUs:I4(Q.minDuration),motionThreshold:Q.motionThreshold,requireAudioSilence:Q.protectAudio},ffmpeg:X,ffmpegVersion:J,ffprobe:F,now:$.io.now(),project:Z,repositoryRoot:$.paths.repositoryRoot,runner:$.runner,toolVersion:$.version}),H=await s8(Z),K=Q.apply&&Q.handle!=="keep"&&Y.analysis.result.recommendedRanges.length>0;if(K){let V=$.io.now().toISOString(),G=e00({analysis:Y.analysis,decisionIds:Y.analysis.result.recommendedRanges.map(()=>`decision_${t3().replaceAll("-","")}`),operation:Q.handle==="cut"?"cut":"speed",plan:H,project:Y.project,speedRate:Q.speedRate,updatedAt:V});if(G.status==="rejected")throw new j("conflict",`Inactivity application was rejected: ${G.reason}`,G);H=q2(G.plan),await eQ(Z.fileSystem,H)}let W={analysisId:Y.analysis.analysisId,applied:K,candidateCount:Y.analysis.result.candidateCount,cuts:Y.analysis.result.recommendedRanges,evidencePath:Y.analysisPath,handle:Q.handle,planHash:m2(H),projectId:Y.project.projectId,protectedInteractionCount:Y.analysis.result.protectedInteractionCount,referenceRecording:Y.analysis.referenceRecording?.recordingId??null};l0($.io,Q.json,W,()=>`${W.cuts.length} project inactivity range(s), ${W.applied?"applied":"evidence only"}; analysis ${W.analysisId}; plan ${W.planHash}`)}async function K31($,Q){if(Q.recording.startsWith("project_")){await H31($,Q);return}await Y31($,Q)}async function W31($,Q){let Z=await q$($.paths.artifactRoot,Q.recording);if(Z.manifest.state!=="stopped")throw new j("conflict","Automatic zoom analysis requires a stopped recording with immutable events.");let _=await HO(Z);if(Q.plan!==void 0&&Q.plan!=="current"&&Q.plan!==_.planId)throw new j("not-found",`Only current (${_.planId}) is available; requested ${Q.plan}.`);let X=rC(await cE(Z),_.sourceDurationUs,{enterDurationUs:300000,exitDurationUs:300000,intentMergeGapUs:750000,maxDurationUs:8000000,maxScale:3,minDurationUs:1500000,postHandleUs:1e6,preHandleUs:500000,scale:2}),F=_;if(Q.apply)F=ZJ({..._,updatedAt:$.io.now().toISOString(),zooms:[..._.zooms.filter(({kind:Y})=>Y!=="automatic"),...X]}),F=q2(F),await d1(G5(Z.directory.path,"edits")),await uj(Z.fileSystem,F,DJ);let J={applied:Q.apply,planHash:HX(F),recordingId:Z.manifest.recordingId,suggestions:X.map((Y)=>({confidence:Y.confidence,range:Y.range,reason:Y.reason,scale:Y.scale,target:Y.target,zoomId:Y.zoomId}))};l0($.io,Q.json,J,()=>`${X.length} automatic zoom suggestion(s), ${Q.apply?"applied":"dry-run"}; plan ${J.planHash}`)}function V31($,Q){let Z=$.tracks.filter((X)=>X.enabled&&X.kind==="display-video"),_=Q==="primary"?Z.find((X)=>$.sources.displays.some((F)=>F.isPrimary&&F.displayId===X.source.displayId)):Z.find((X)=>X.source.displayId===Q||X.trackId===Q);if(_===void 0)throw new j("not-found",`No enabled display track matches ${Q}.`);return _}async function G31($,Q,Z,_,X){let F=Z;if(_){let W=await sV0($,Q,{minDurationUs:3000000,motionThreshold:0.003,protectAudio:!0});for(let V of W.result.cuts)F=_M(F,V,Z.updatedAt)}let J=V31(Q.manifest,X),Y=Q.manifest.sources.displays.find(({displayId:W})=>W===J.source.displayId),H=await cE(Q),K=Q.manifest.tracks.filter((W)=>W.enabled&&(W.kind==="system-audio"||W.kind==="microphone-audio")).map(({trackId:W})=>W);return{effectivePlan:F,renderPlan:T10(Q.manifest,F,H,{audioTrackIds:K,camera:{kind:"none"},displayTrackId:J.trackId,frameRate:Math.min(60,Y.refreshRateHz),pixelHeight:Y.pixelSize.height,pixelWidth:Y.pixelSize.width})}}async function N31($,Q){let Z=await q$($.paths.artifactRoot,Q.recording);if(Z.manifest.state!=="stopped")throw new j("conflict","Rendering requires a stopped recording with immutable media and events.");let _=await HO(Z),X=await G31($,Z,_,Q.autoInactivity,Q.display),F=H0(R(X.renderPlan)),J=`renders/resolved-${F}.json`,Y=`renders/${F}.mp4`;await d1(G5(Z.directory.path,"renders"));let H=Q.kind==="render-plan"&&Q.output!==void 0?await Q31(Z,Q.output,J):void 0;if(await Z.fileSystem.writeTextAtomic(J,`${R(X.renderPlan)}
5638
5638
  `),Q.kind==="render-plan"){if(H!==void 0&&H.relative!==J)await Z.fileSystem.writeTextAtomic(H.relative,`${R(X.renderPlan)}