From 0a7768e0b4de1952cb37c023f449edbd95d2637a Mon Sep 17 00:00:00 2001 From: 0thernet Date: Tue, 22 Sep 2026 23:56:03 -0400 Subject: [PATCH 01/12] fix(html-overlay): settle frame presentation before each screenshot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit renderFrame resolves when authored callbacks return, not when the new surface reaches the compositor. Under heavy GPU load a screenshot taken immediately can capture the previous presented frame — observed downstream as stills containing the prior seek pixels. Wait two animation frames between renderFrame and the screenshot so every capture reflects the frame it is named for. Also records a kb note collecting the deterministic scene-authoring pitfalls this class of bug belongs to (shader NaN domain guards, presentation ordering, additive-only glow layers, edge-on backdrops, seek-stability, disc orientation, uniform declaration). Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/desktop/cli/html-overlay-renderer.ts | 19 +++++++ .../deterministic-scene-authoring-pitfalls.md | 50 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 kb/notes/deterministic-scene-authoring-pitfalls.md diff --git a/apps/desktop/cli/html-overlay-renderer.ts b/apps/desktop/cli/html-overlay-renderer.ts index 247a25db..75e4685f 100644 --- a/apps/desktop/cli/html-overlay-renderer.ts +++ b/apps/desktop/cli/html-overlay-renderer.ts @@ -2332,6 +2332,25 @@ export class PlaywrightHtmlOverlayRenderer implements HtmlOverlayRenderer { ); } await inspectGpu(); + // Wait for the compositor to present the frame the callbacks + // just produced. renderFrame resolves when authored work returns, + // not when the new surface reaches the screen; under heavy GPU + // load a screenshot taken immediately can capture the previous + // presented frame. Two animation frames bound the wait: the draw + // is committed before the first callback fires and presented + // before the second. + await boundedBrowserStep( + async () => await host.evaluate( + async () => await new Promise((resolve) => { + requestAnimationFrame(() => { + requestAnimationFrame(() => resolve()); + }); + }), + ), + signal, + this.#browserStepTimeoutMs, + `frame ${String(frameIndex)} presentation settle`, + ); await boundedBrowserStep( async () => await page.screenshot({ omitBackground: HTML_OVERLAY_RENDERER_CONTRACT.screenshot.omitBackground, diff --git a/kb/notes/deterministic-scene-authoring-pitfalls.md b/kb/notes/deterministic-scene-authoring-pitfalls.md new file mode 100644 index 00000000..6b36dc66 --- /dev/null +++ b/kb/notes/deterministic-scene-authoring-pitfalls.md @@ -0,0 +1,50 @@ +--- +title: Deterministic scene-authoring pitfalls +type: concept +tags: + - agents + - html-overlay + - rendering + - threejs +repository_scopes: + - apps/desktop/html-overlay + - apps/desktop/cli +--- + +# Deterministic scene-authoring pitfalls + +Chaptered Three.js scenes rendered through the HTML overlay path fail in characteristic ways that are cheap to prevent once recognized. These lessons come from long deterministic scenes — hundreds of draw calls, custom `ShaderMaterial` layers, and a post chain — rendered frame by frame for video output. + +## Shader NaN poisons the post chain + +GLSL evaluates `pow(x, n)` as `exp2(n * log2(x))`. When `x` is a tiny negative value from floating-point error — `.5 + .5 * cos(...)` can produce `-1e-11` — the result is NaN, not a small dark value. A NaN fragment in a bright pass is then blurred by the bloom mip chain into dark square blotches that look like geometry bugs but are actually math errors. `atan(0, 0)` is undefined at the exact center of a polar shader for the same reason. + +Guard every domain edge: `pow(max(0., x), n)` or explicit `x * x`, `atan(y, x + 1e-4)`, `sqrt(max(0., x))`, and clamped inputs to `asin`/`acos`/`log`. When a frame develops unexplained dark tiles, suspect a NaN in an upstream additive or emissive pass before suspecting blending. + +## A resolved render is not a presented frame + +A frame callback that draws and returns does not guarantee the new surface reached the compositor. Screenshotting immediately after evaluation can capture the previous presented frame under GPU load — observed as a still that shows the prior seek's pixels while the scene state is correct. Waiting two `requestAnimationFrame` callbacks bounds the wait: the draw commits before the first callback and presents before the second. The overlay renderer applies this presentation settle before every frame screenshot so captures are deterministic, not probabilistic. + +## Backdrop panels are only honest in their authored view volume + +Canvas-painted sky backdrops and haze cards read correctly only from the camera region they were authored for. A camera that pulls back past them shows the panel edge-on as a dark slab floating in the world. Either fade such panels out as the camera leaves the authored range or gate the camera path so it never exposes the edge. + +## Additive layers cannot darken + +Glow discs, god rays, aurora curtains, and star fields belong on `AdditiveBlending` with `depthWrite:false`. Anything that must occlude — a galaxy's dust lanes, a planet silhouette — needs a separate opaque or normal-blended layer; an additive layer can only ever add light, so "darker than background" is impossible through it. + +## Seek-stability is the real deterministic contract + +Every animated value must be a pure function of the integer frame time: seeded hash functions for layout randomness, `update(t)` driven from the frame clock, and no `Math.random()`, wall clocks, or accumulated state that depends on evaluation order. The overlay runtime seeks document and tracked animations to the absolute frame time before callbacks, so a scene that also honors the clock produces identical pixels for identical timestamps regardless of render order. + +## Discs must face the capturing camera + +A procedural disc built in the world XZ plane collapses to a thin band for a camera looking along Z — the classic "the galaxy disappeared" bug. Orient far-space billboards in the view plane (XY facing ±Z for a pull-back camera) and tilt them with an explicit rotation rather than relying on perspective. + +## Declare every uniform used + +A vertex or fragment shader that reads a uniform it does not declare fails at compile with a terse link-stage error that names no variable. Keeping the `uniform` declarations and the JS `uniforms` object in one glance-adjacent block prevents the whole class of bug. + +## Related + +- [[notes/documentation-ownership|Documentation ownership]] — this note is pull-based rationale; the executable contracts live in the overlay runtime and renderer tests. From f634e6f484a1b195d99db6a5445a84cc9bd59e2b Mon Sep 17 00:00:00 2001 From: 0thernet Date: Wed, 23 Sep 2026 00:16:31 -0400 Subject: [PATCH 02/12] ci: retrigger pull_request checks From 9cf2ade1ace31e03517f1e6a707e16e687136d1e Mon Sep 17 00:00:00 2001 From: 0thernet Date: Wed, 23 Sep 2026 00:30:35 -0400 Subject: [PATCH 03/12] kb: refresh catalog for deterministic scene-authoring pitfalls note --- kb/index.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/kb/index.md b/kb/index.md index 61d32e25..e4abc18b 100644 --- a/kb/index.md +++ b/kb/index.md @@ -12,6 +12,7 @@ This vault keeps captured sources separate from maintained notes. Catalog links ### Notes - [[notes/agent-platform-onboarding|Agent platform onboarding]] — Cloud agent platforms (Muse connectors, Grok-style bots, Instinct-class clients) cannot run a local CLI, so a product that wants agent reach needs a hosted surface. The pattern… +- [[notes/deterministic-scene-authoring-pitfalls|Deterministic scene-authoring pitfalls]] — Chaptered Three.js scenes rendered through the HTML overlay path fail in characteristic ways that are cheap to prevent once recognized. These lessons come from long deterministic… - [[notes/documentation-ownership|Documentation ownership]] — Repository knowledge stays useful when each kind of truth has one primary home. The closest inherited owns mandatory edit-time rules. owns current multi-step procedures. Types,… - [[notes/repository-seams|Repository seams]] — Slopcamera is a standalone public SDK, CLI, desktop host, and static site. Its portable graph and scene contracts may be shared inside this repository, while media-host behavior,… @@ -30,7 +31,7 @@ This vault keeps captured sources separate from maintained notes. Catalog links - [[plans/hosted-agent-api|Hosted Slopcamera agent API]] — Status: completed. Status: completed. Decision record for the hosted tool surface that lets cloud agent platforms (Muse connectors, Grok, Instinct-class clients) use Slopcamera without a local shell. - [[plans/html-overlay-creative-toolkit|HTML overlay creative toolkit]] — Status: completed. Atet exposes a small, durable, mutually exclusive set of HTML-overlay authoring profiles, backed by exact executable locks and one deterministic render host. It also maintains a… - [[plans/rendered-review-galleries|Rendered review galleries — applied-material cells, seam checks, and scene-variant contact sheets]] — Status: completed. Upgrade the gallery review loop from flat generated pixels to rendered evidence — textures shown applied to probe geometry with a tiled seam check, skyboxes shown lighting a probe… -- [[plans/homepage-positioning-copy|Sharpen the homepage positioning copy]] — Status: in-progress. Rewrite the hero, trust, FAQ, and closing copy so the homepage states what Slopcamera is, why it beats prompting a bare coding agent, and stays factual inside the reviewed-island… +- [[plans/homepage-positioning-copy|Sharpen the homepage positioning copy]] — Status: completed. Rewrite the hero, trust, FAQ, and closing copy so the homepage states what Slopcamera is, why it beats prompting a bare coding agent, and stays factual inside the reviewed-island… ### Scopes From 561e0a2eadcf80b2ba005df6edec9d61c8255bd0 Mon Sep 17 00:00:00 2001 From: 0thernet Date: Wed, 23 Sep 2026 00:47:16 -0400 Subject: [PATCH 04/12] build: regenerate committed CLI bundle for overlay presentation settle --- apps/desktop/dist/cli/main.js | 116 +++++++++++++++++----------------- 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/apps/desktop/dist/cli/main.js b/apps/desktop/dist/cli/main.js index df384496..0e2f66d6 100755 --- a/apps/desktop/dist/cli/main.js +++ b/apps/desktop/dist/cli/main.js @@ -7,14 +7,14 @@ ${j} ${V??""}`).join(` `),Y=`alpha-${UZ(X).slice(0,16)}`,H=[``," ",` `,` `,..._.map(({d:K,fill:j,transform:V})=>` `)," "," ",` `,...$.map(({d:K,fill:j,rgb:V,transform:O})=>{let W=Z===void 0||J===void 0?j:gx(V,Z.model)?J[0]:J[1];return` `})," ","",""].join(` `);return vA(H),H}function J60($){return $.match(/{lV();k6();mu0=/^[MmZzLlHhVvCcSsQqTtAaEe0-9+,.\s-]+$/u,uu0=/^translate\(\s*[-+0-9.eE]+\s*(?:,\s*|\s+)[-+0-9.eE]+\s*\)$/u,lu0=/V===0))break;let Z=ox(Q.subarray(0,100)),J=ox(Q.subarray(345,500)),X=J===""?Z:`${J}/${Z}`,Y=ox(Q.subarray(124,136)).trim();if(!/^[0-7]+$/u.test(Y))throw new F0("tool_integrity","VTracer tar contains an invalid size.");let H=Number.parseInt(Y,8);if(!Number.isSafeInteger(H)||H<0||H>xA)throw new F0("tool_integrity","VTracer tar entry exceeds its size limit.");let K=F+512,j=K+H;if(j>$.length)throw new F0("tool_integrity","VTracer tar entry is truncated.");if(X===_||X.endsWith(`/${_}`))return Uint8Array.from($.subarray(K,j));F=K+Math.ceil(H/512)*512}throw new F0("tool_integrity",`VTracer archive omitted ${_}.`)}function su0($,_){let F=Buffer.from($),Q=0;while(Q+30<=F.length){if(F.readUInt32LE(Q)!==67324752)break;let J=F.readUInt16LE(Q+6),X=F.readUInt16LE(Q+8),Y=F.readUInt32LE(Q+18),H=F.readUInt32LE(Q+22),K=F.readUInt16LE(Q+26),j=F.readUInt16LE(Q+28);if((J&1)!==0||(J&8)!==0)throw new F0("tool_integrity","VTracer zip uses encryption or an unsupported data descriptor.");if(H>xA)throw new F0("tool_integrity","VTracer zip entry exceeds its size limit.");let V=Q+30,O=V+K+j,W=O+Y;if(W>F.length)throw new F0("tool_integrity","VTracer zip entry is truncated.");let G=F.subarray(V,V+K).toString("utf8");if(G===_||G.endsWith(`/${_}`)){let D=F.subarray(O,W),w=X===0?Buffer.from(D):X===8?cu0(D,{maxOutputLength:xA}):void 0;if(w===void 0)throw new F0("tool_integrity",`VTracer zip uses unsupported compression method ${X}.`);if(w.length!==H)throw new F0("tool_integrity","VTracer zip size does not match its header.");return Uint8Array.from(w)}Q=W}throw new F0("tool_integrity",`VTracer archive omitted ${_}.`)}function ox($){let _=$.indexOf(0);return Buffer.from(_===-1?$:$.subarray(0,_)).toString("ascii")}var xA=8388608;var H60=Y_(()=>{k6()});import{createHash as j60,randomUUID as V60}from"crypto";import{constants as hA}from"fs";import{chmod as W60,mkdir as N60,open as ax,realpath as O60,rename as nu0,rm as uA,writeFile as ru0}from"fs/promises";import{homedir as ix}from"os";import{dirname as ou0,join as dV,resolve as mA}from"path";function w60($){return process.env[$]}async function D60($,_,F){let Q=w60("SLOPCAMERA_VTRACER_PATH");if(Q!==void 0)return K60(mA(Q),mA(_),"override",$);let Z=`${process.platform}-${process.arch}`,J=iu0[Z];if(J===void 0)throw new F0("tool_platform",`VTracer is not pinned for ${process.platform}/${process.arch}.`,{arch:process.arch,platform:process.platform});let X=mA(F??tu0()),Y=process.platform==="win32"?".exe":"",H=dV(X,"tools",`vtracer-${MZ}-${process.platform}-${process.arch}${Y}`);if(await tx(H,$)!==J.binarySha256)await _l0(H),await eu0(H,J,$);return K60(H,mA(_),"official-release",$,J.binarySha256)}function tu0(){let $=w60("SLOPCAMERA_CACHE_DIR");if($!==void 0&&$.trim()!=="")return $;if(process.platform==="win32")return dV(process.env.LOCALAPPDATA??ix(),"slopcamera");if(process.platform==="darwin")return dV(ix(),"Library","Caches","slopcamera");return dV(process.env.XDG_CACHE_HOME??dV(ix(),".cache"),"slopcamera")}async function eu0($,_,F){F.assert("VTracer download");let Q=await Zl0(_.url,F,au0),Z=UZ(Q);if(Z!==_.archiveSha256)throw new F0("tool_integrity",`VTracer archive checksum mismatch: ${Z}`,{actual:Z,expected:_.archiveSha256});let J=Y60(Q,_.format);if(J.byteLength<1||J.byteLength>zX)throw new F0("tool_integrity","VTracer binary exceeds its verified installation limit.",{bytes:J.byteLength,maximumBytes:zX});let X=UZ(J);if(X!==_.binarySha256)throw new F0("tool_integrity",`VTracer binary checksum mismatch: ${X}`,{actual:X,expected:_.binarySha256});F.assert("VTracer installation"),await N60(ou0($),{recursive:!0});let Y=`${$}.${V60()}.tmp`;try{if(await ru0(Y,J,{flag:"wx",mode:448}),process.platform!=="win32")await W60(Y,320);F.assert("VTracer installation");try{await nu0(Y,$)}catch(K){if(await tx($,F)===_.binarySha256)await uA(Y,{force:!0});else throw K}}catch(K){if(await uA(Y,{force:!0}),K instanceof F0)throw K;throw new F0("tool_integrity","Could not publish the verified VTracer binary.",{},{cause:K})}let H=await tx($,F);if(H!==_.binarySha256)throw new F0("tool_integrity","Installed VTracer differs from the verified release binary.",{actual:H,expected:_.binarySha256})}async function K60($,_,F,Q,Z){Q.assert("VTracer private copy"),await N60(_,{mode:448,recursive:!0});let J=process.platform==="win32"?".exe":"",X=dV(_,`vtracer-${V60()}${J}`),Y=F==="official-release"?"tool_integrity":"tool_version",H,K,j;try{let V=await O60($);Q.assert("VTracer private copy"),H=await ax(V,L60());let O=await H.stat();Ql0(O,$),K=await ax(X,"wx",320),j=await Fl0(H,K,zX,Q),await K.sync(),Q.assert("VTracer private copy")}catch(V){if(V instanceof F0)throw V;throw new F0(Y,"VTracer could not be copied into the private conversion directory.",{},{cause:V})}finally{await Promise.allSettled([H?.close(),K?.close()])}try{if(j.length===0)throw new F0(Y,"VTracer executable is empty.");if(Z!==void 0&&j!==Z)throw new F0("tool_integrity","VTracer changed before it could be copied for conversion.",{actual:j,expected:Z});if(process.platform!=="win32")await W60(X,320);let V=await ex(X,zX,Q,Y);if(V!==j)throw new F0("tool_integrity","The private VTracer copy failed its integrity check.",{actual:V,expected:j});return $l0(X,F,Q,j,Z)}catch(V){throw await uA(X,{force:!0}),V}}async function $l0($,_,F,Q,Z){F.assert("VTracer inspection");let{stderr:J,stdout:X}=await gA([$,"--version"],F.remainingMs(),"tool_version");if(!new RegExp(`\\b${MZ.replaceAll(".","\\.")}\\b`,"u").test(`${X} -${J}`))throw new F0("tool_version",`Expected VTracer ${MZ}.`);let Y=await ex($,zX,F,"tool_integrity");if(Y!==Q||Z!==void 0&&Y!==Z)throw new F0("tool_integrity","The private VTracer executable changed during inspection.",{actual:Y,expected:Z??Q});return{path:$,sha256:Y,source:_,version:MZ}}async function tx($,_){try{return await ex($,zX,_,"tool_integrity")}catch(F){if(F instanceof F0&&F.code==="timeout")throw F;if(Jl0(F,"ENOENT"))return;return}}async function _l0($){try{await uA($,{force:!0})}catch(_){throw new F0("tool_integrity","Could not remove an invalid cached VTracer binary.",{},{cause:_})}}async function ex($,_,F,Q){let Z;try{F.assert("VTracer hash");let J=await O60($);F.assert("VTracer hash"),Z=await ax(J,L60());let X=await Z.stat();if(!X.isFile()||X.size<1||X.size>_)throw new F0(Q,"VTracer must be a non-empty regular file within its size limit.",{bytes:X.size,maximumBytes:_});let Y=j60("sha256"),H=Buffer.allocUnsafe(Math.min(G60,_+1)),K=0;while(!0){F.assert("VTracer hash");let j=Math.min(H.byteLength,_-K+1),{bytesRead:V}=await Z.read(H,0,j,null);if(V===0)break;if(K+=V,K>_)throw new F0(Q,"VTracer grew beyond its executable size limit while being hashed.",{bytes:K,maximumBytes:_});Y.update(H.subarray(0,V))}return F.assert("VTracer hash"),Y.digest("hex")}catch(J){if(J instanceof F0)throw J;throw new F0(Q,"VTracer executable could not be read safely.",{},{cause:J})}finally{await Z?.close().catch(()=>{return})}}async function Fl0($,_,F,Q){let Z=j60("sha256"),J=Buffer.allocUnsafe(Math.min(G60,F+1)),X=0;while(!0){Q.assert("VTracer private copy");let Y=Math.min(J.byteLength,F-X+1),{bytesRead:H}=await $.read(J,0,Y,null);if(H===0)break;if(X+=H,X>F)throw new F0("tool_integrity","VTracer grew beyond its executable size limit while being copied.",{bytes:X,maximumBytes:F});Z.update(J.subarray(0,H));let K=0;while(KzX)throw new F0("tool_version",`VTracer must be a non-empty regular file: ${_}`,{bytes:$.size,maximumBytes:zX})}async function Zl0($,_,F){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),_.remainingMs());try{let J=await fetch($,{headers:{"user-agent":"hraness-slopcamera-vectorizer"},redirect:"follow",signal:Q.signal});if(!J.ok||J.body===null)throw new F0("tool_download",`Could not download VTracer: ${J.status} ${J.statusText}`);let X=Number.parseInt(J.headers.get("content-length")??"",10);if(Number.isFinite(X)&&X>F)throw new F0("tool_download","VTracer archive exceeds its download limit.");let Y=[],H=J.body.getReader(),K=0;while(!0){_.assert("VTracer download");let{done:j,value:V}=await H.read();if(j)break;if(K+=V.byteLength,K>F)throw await H.cancel(),new F0("tool_download","VTracer archive exceeds its download limit.");Y.push(V)}return Uint8Array.from(Buffer.concat(Y,K))}catch(J){if(J instanceof F0)throw J;if(Q.signal.aborted)throw new F0("timeout","VTracer download exceeded the conversion time limit.");throw new F0("tool_download","Could not download VTracer.",{},{cause:J})}finally{clearTimeout(Z)}}function Jl0($,_){return $ instanceof Error&&"code"in $&&$.code===_}function L60(){if(process.platform==="win32")return hA.O_RDONLY;return hA.O_RDONLY|hA.O_NONBLOCK|hA.O_NOFOLLOW}var MZ="0.6.4",QD=($)=>Object.freeze($),iu0,au0=4194304,zX=16777216,G60=65536;var C60=Y_(()=>{H60();FD();lV();k6();iu0=Object.freeze({"darwin-arm64":QD({archiveSha256:"4a597fd2df8b961d60620df40a7436109427d86e5c028758e6e8796b02d3d996",binarySha256:"77e495bbe212448240387fba3b6d8bc62ba20ecfb6f3c22967e51600f1cc6e66",format:"tar.gz",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-aarch64-apple-darwin.tar.gz`}),"darwin-x64":QD({archiveSha256:"f0d755292c2602d772d63d658a3498b23eca8b5620d4b92a991bd035d5abed16",binarySha256:"0f9f88f989b757e27973a5c4b42665153070183d0787656ee8af2249ab326b78",format:"tar.gz",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-x86_64-apple-darwin.tar.gz`}),"linux-arm64":QD({archiveSha256:"cbd05ad4f491d12dd139ada61485ca1d24db9f981cbe1658632a083cd0ac1a71",binarySha256:"a4b33b6c4066a6b9187802c6efc8b89e211318e12a17164b9d1dd1f29ac5e502",format:"tar.gz",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-aarch64-unknown-linux-musl.tar.gz`}),"linux-x64":QD({archiveSha256:"9290ba0c90e224d6d212836dff5491407c1718bcb72f80b2b5a4a01816df5e40",binarySha256:"6f31499257076bd94de3e976844cf7ca5643f1e194a2bf0599b13f3719452aec",format:"tar.gz",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-x86_64-unknown-linux-musl.tar.gz`}),"win32-x64":QD({archiveSha256:"6b5bc17a6b017129ee40461df254f65d16f3b494c001a8541d41861066b716bf",binarySha256:"4ad8d35e566cd15caf582063b8349bd082b8fa2bd461e99d116fc63ad8fdeca0",format:"zip",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-x86_64-pc-windows-msvc.zip`})})});var UX=1,DK,ZD;var $h=Y_(()=>{uV();DK=Math.ceil(M6.maxInputBytes/3)*4+524288,ZD=M6.maxOutputBytes*2+524288});import{fileURLToPath as Xl0}from"url";import{mkdtemp as Yl0,rm as Hl0}from"fs/promises";import{tmpdir as Kl0}from"os";import{dirname as B60,join as _h}from"path";async function U60($,_){let F=performance.now(),Q=mV(_.limits);if(process.platform==="win32")throw new F0("tool_platform","Bounded VTracer streaming is unavailable on Windows.",{platform:process.platform});let Z=Nl0($,Q.maxInputBytes),J=await Yl0(_h(Kl0(),"slopcamera-vectorize-")),X;try{X=await Vl0(Z,_,Q,F,J)}finally{await Wl0(J)}if(performance.now()-F>=Q.maxDurationMs)throw new F0("timeout","Vectorization exceeded the conversion time limit during cleanup.");return X}async function Vl0($,_,F,Q,Z){let J=F.maxDurationMs-(performance.now()-Q);if(J<=lA+z60)throw new F0("timeout","Vectorization has no remaining budget for isolated worker execution.");let X=Math.floor(J-lA-z60),Y=wl0(_.inheritedFileDescriptors),H=Y.map((G,D)=>D+3),K={input:$,options:Gl0(_,X,H),protocol:UX,temporaryRoot:Z},j=Buffer.from(JSON.stringify(K));if(j.byteLength>DK)throw new F0("input_limit","The vectorization worker request exceeds its IPC limit.",{bytes:j.byteLength,maximumBytes:DK});let V=F.maxDurationMs-(performance.now()-Q);if(V<=lA)throw new F0("timeout","Vectorization has no remaining budget for isolated worker startup and cleanup.");let{stdout:O}=await gA([process.execPath,Dl0()],Math.floor(V-lA),"trace_failed",{...Y.length===0?{}:{inheritedFileDescriptors:Y},maxStdoutBytes:ZD,stdin:j});if(performance.now()-Q>=F.maxDurationMs)throw new F0("timeout","Vectorization exceeded the conversion time limit.");let W=Ll0(O);if(!W.ok)throw new F0(W.error.code,W.error.message,W.error.details);if(Cl0(W.result,F.maxOutputBytes),performance.now()-Q>=F.maxDurationMs)throw new F0("timeout","Vectorization exceeded the conversion time limit.");return W.result}async function Wl0($){try{await Hl0($,{force:!0,recursive:!0})}catch(_){throw new F0("trace_failed","The isolated vectorization directory could not be removed.",{temporaryRoot:$},{cause:_})}}function Nl0($,_){return typeof $==="string"?{kind:"path",value:$}:Ol0($,_)}function Ol0($,_){let F=$ instanceof ArrayBuffer?new Uint8Array($):$;if(F.byteLength<1)throw new F0("invalid_input","Raster input is empty.");if(F.byteLength>_)throw new F0("input_limit",`Raster input exceeds the ${_}-byte limit.`,{bytes:F.byteLength,maximumBytes:_});return{kind:"bytes",value:Buffer.from(F.buffer,F.byteOffset,F.byteLength).toString("base64")}}function Gl0($,_,F){return{...$.alphaCutoff===void 0?{}:{alphaCutoff:$.alphaCutoff},...$.cacheDirectory===void 0?{}:{cacheDirectory:$.cacheDirectory},...$.duotone===void 0?{}:{duotone:[$.duotone[0],$.duotone[1]]},...F.length===0?{}:{inheritedFileDescriptors:F},limits:{...$.limits,maxDurationMs:_},...$.outputPath===void 0?{}:{outputPath:$.outputPath}}}function wl0($){let _=$??[];if(_.length>16||_.some((F,Q)=>!Number.isSafeInteger(F)||F<0||F>2147483647||_.indexOf(F)!==Q))throw new F0("invalid_input","Inherited vectorizer descriptors must be unique bounded integers.");return Object.freeze([..._])}function Dl0(){let $=Xl0(import.meta.url);return $.endsWith(".ts")?_h(B60($),"worker.ts"):_h(B60($),"vectorize","worker.js")}function Ll0($){let _;try{_=JSON.parse($)}catch(F){throw new F0("trace_failed","The vectorization worker returned malformed output.",{},{cause:F})}if(!JD(_)||_.protocol!==UX)throw new F0("trace_failed","The vectorization worker returned an incompatible response.");if(_.ok===!0&&Bl0(_.result))return _;if(_.ok===!1&&JD(_.error)&&typeof _.error.code==="string"&&jl0.has(_.error.code)&&typeof _.error.message==="string"&&JD(_.error.details))return _;throw new F0("trace_failed","The vectorization worker returned an invalid response.")}function Cl0($,_){let F=Buffer.byteLength($.svg);if(F<1||F>_||$.receipt.bytes!==F||$.receipt.svgSha256.length!==64)throw new F0("trace_failed","The vectorization worker response violates its output contract.",{bytes:F,maximumOutputBytes:_})}function Bl0($){if(!JD($)||$.outputPath!==null&&typeof $.outputPath!=="string"||typeof $.svg!=="string"||!JD($.receipt))return!1;let _=$.receipt.profile;return typeof $.receipt.bytes==="number"&&typeof $.receipt.svgSha256==="string"&&typeof _==="string"&&Sx.includes(_)}function JD($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var jl0,lA=250,z60=100;var k60=Y_(()=>{FD();uV();$h();k6();jl0=new Set(["input_limit","invalid_input","output_limit","quality_limit","timeout","tool_download","tool_integrity","tool_platform","tool_version","trace_failed","unsafe_svg"])});import{randomUUID as zl0}from"crypto";import{mkdir as Ul0,rename as kl0,rm as Ml0,writeFile as Jh}from"fs/promises";import{dirname as Al0,join as M60,resolve as Rl0}from"path";function EF($,_={}){return U60($,_)}async function A60($,_={},F){let Q=mV(_.limits),Z=new tw(Q.maxDurationMs),J=_.alphaCutoff??Tl0;if(!Number.isInteger(J)||J<1||J>64)throw new F0("invalid_input","alphaCutoff must be an integer from 1 through 64.");let X=_.duotone===void 0?void 0:[R_(_.duotone[0]),R_(_.duotone[1])],Y=await IA($,Q,Z);if(process.platform==="win32")throw new F0("tool_platform","Bounded VTracer streaming is unavailable on Windows.",{platform:process.platform});let H=await D60(Z,F,_.cacheDirectory),K=[],j=[],V=Pl0(Y.pixels,J);for(let U of V){Z.assert(`${U.name} trace`);let k=M60(F,`${U.name}.png`);await Jh(k,await $D(U.pixels,Y.width,Y.height));let A=await Qh(Y,U,Fh[0],k,H,F,Q,Z,K);if(A!==void 0)j.push(A);if(A!==void 0&&Sl0(A.quality))continue;let q=await Qh(Y,U,Fh[1],k,H,F,Q,Z,K);if(q!==void 0)j.push(q);if([A,q].some((M)=>M!==void 0&&Zh(M.quality)))continue;let E=await Qh(Y,U,Fh[2],k,H,F,Q,Z,K);if(E!==void 0)j.push(E)}let O=[...j].sort(fl0)[0];if(O!==void 0&&I_0(Y.pixels)&&O.quality.alphaRmse>0.06){let U=await bl0(Y,O,H,F,Q,Z,K);if(U!==void 0)j.push(U)}let W=j.filter((U)=>U.bytes<=Q.maxOutputBytes&&U.pathCount<=Q.maxPaths&&Zh(U.quality));if(W.length===0)throw new F0("quality_limit","No adaptive vector candidate passed the fidelity and output gates.",{candidates:j.map(gl0),errors:K});let G=yl0(W),D=X===void 0?void 0:{model:v_0(Y.pixels),palette:X},w=G.maskPaths===void 0?nx(G.artworkPaths,Y.width,Y.height,D):rx(G.artworkPaths,G.maskPaths,Y.width,Y.height,D);vA(w);let L=Buffer.byteLength(w),C=J60(w);if(L>Q.maxOutputBytes||C>Q.maxPaths)throw new F0("output_limit",`Canonical SVG exceeds ${Q.maxOutputBytes} bytes or ${Q.maxPaths} paths.`,{bytes:L,pathCount:C});Z.assert("output publication");let B=_.outputPath===void 0?null:await vl0(_.outputPath,w),z=l_0();return{outputPath:B,receipt:{alphaCutoff:G.alphaCutoff,bytes:L,candidatesEvaluated:j.length,format:Y.format,height:Y.height,inputBytes:Y.inputBytes,outputMode:D===void 0?"color":"duotone",pathCount:C,profile:G.profile,provenance:{arch:process.arch,platform:process.platform,sharp:z.sharp,sharpVersions:z.sharpVersions,vips:z.vips,vtracerSha256:H.sha256,vtracerSource:H.source,vtracerVersion:H.version},quality:q60(G.quality),receiptVersion:1,representation:G.representation,sourceSha256:Y.sourceSha256,svgSha256:UZ(w),width:Y.width},svg:w}}function Pl0($,_){let F=fx($,_),Q=[];if(Il0(F))Q.push({alphaCutoff:_,name:`alpha-${_}`,pixels:F});if(_>1&&(Q.length===0||P_0($,_)>=ql0))Q.push({alphaCutoff:1,name:"alpha-1",pixels:fx($,1)});if(Q.length===0)throw new F0("invalid_input","Alpha sanitation removed every visible pixel.");return Q}function Il0($){for(let _=3;_<$.length;_+=4)if($[_]>0)return!0;return!1}async function Qh($,_,F,Q,Z,J,X,Y,H){try{let K=await T60(Z,Q,F.args,J,X.maxOutputBytes,Y);Y.assert(`${F.name} trace`);let j=sx(K,$.width,$.height,X.maxPaths),V=Buffer.byteLength(j.svg),O=j.paths.length;if(V>X.maxOutputBytes||O>X.maxPaths)throw new F0("output_limit",`${F.name} exceeds vector output limits.`);let W=await R60(j.svg,$,X.maxDecodedPixels,Y);return{alphaCutoff:_.alphaCutoff,artworkPaths:j.paths,bytes:V,pathCount:O,profile:F.name,quality:W,representation:"color-paths",svg:j.svg}}catch(K){if(K instanceof F0&&K.code==="timeout")throw K;H.push(`${_.name}/${F.name}: ${K instanceof Error?K.message:String(K)}`);return}}async function bl0($,_,F,Q,Z,J,X){try{let Y=E_0($.pixels),H=M60(Q,"alpha-plane.png");await Jh(H,await $D(Y,$.width,$.height));let K=await T60(F,H,El0,Q,Z.maxOutputBytes,J),j=sx(K,$.width,$.height,Z.maxPaths),V=_.artworkPaths.length+j.paths.length;if(V>Z.maxPaths)throw new F0("output_limit","Alpha-masked output exceeds the path limit.");let O=rx(_.artworkPaths,j.paths,$.width,$.height),W=Buffer.byteLength(O);if(W>Z.maxOutputBytes)throw new F0("output_limit","Alpha-masked output exceeds the byte limit.");let G=await R60(O,$,Z.maxDecodedPixels,J);return{alphaCutoff:_.alphaCutoff,artworkPaths:_.artworkPaths,bytes:W,maskPaths:j.paths,pathCount:V,profile:_.profile,quality:G,representation:"alpha-mask",svg:O}}catch(Y){if(Y instanceof F0&&Y.code==="timeout")throw Y;X.push(`alpha-mask: ${Y instanceof Error?Y.message:String(Y)}`);return}}async function R60($,_,F,Q){let Z=await u_0($,_.scoreWidth,_.scoreHeight,F);Q.assert("quality measurement");let J=y_0(_.scorePixels,Z,_.scoreWidth,_.scoreHeight,1);return{alphaRmse:S_0(_.scorePixels,Z),colorRmse:b_0(_.scorePixels,Z),outsideAlphaRatio:J.outsideAlphaRatio,sampleHeight:_.scoreHeight,sampleWidth:_.scoreWidth,supportRecall:J.supportRecall}}async function T60($,_,F,Q,Z,J){let{output:X}=await _60((Y)=>[$.path,"--input",_,"--output",Y,...F],J.remainingMs(),"trace_failed",{maxOutputBytes:Z,temporaryRoot:Q});if(X.length===0)throw new F0("trace_failed","VTracer did not emit an SVG.");return X}function Sl0($){return Zh($)&&$.colorRmse<=0.12&&$.alphaRmse<=0.18&&$.outsideAlphaRatio<=0.02&&$.supportRecall>=0.97}function Zh($){return $.colorRmse<=0.3&&$.alphaRmse<=0.3&&$.outsideAlphaRatio<=0.15&&$.supportRecall>=0.8}function fl0($,_){return $.quality.colorRmse-_.quality.colorRmse||$.quality.alphaRmse-_.quality.alphaRmse||$.bytes-_.bytes||$.pathCount-_.pathCount||$.profile.localeCompare(_.profile)}function yl0($){let _=Math.min(...$.map(({quality:Q})=>Q.colorRmse));return[...$.filter(({quality:Q})=>Q.colorRmse<=_+0.005)].sort((Q,Z)=>Q.bytes-Z.bytes||Q.pathCount-Z.pathCount||Q.quality.alphaRmse-Z.quality.alphaRmse||Q.profile.localeCompare(Z.profile)||Q.representation.localeCompare(Z.representation))[0]}function q60($){let _=(F)=>Number(F.toFixed(8));return{alphaRmse:_($.alphaRmse),colorRmse:_($.colorRmse),outsideAlphaRatio:_($.outsideAlphaRatio),sampleHeight:$.sampleHeight,sampleWidth:$.sampleWidth,supportRecall:_($.supportRecall)}}function gl0($){return{alphaCutoff:$.alphaCutoff,bytes:$.bytes,pathCount:$.pathCount,profile:$.profile,quality:q60($.quality),representation:$.representation}}async function vl0($,_){let F=Rl0($);await Ul0(Al0(F),{recursive:!0});let Q=`${F}.${zl0()}.tmp`;try{await Jh(Q,_,{flag:"wx"}),await kl0(Q,F)}catch(Z){throw await Ml0(Q,{force:!0}),new F0("output_limit",`Could not atomically write ${F}.`,{},{cause:Z})}return F}var Tl0=8,ql0=0.002,Fh,El0;var XD=Y_(()=>{FD();uV();lV();bA();X60();C60();k60();k6();Fh=[{args:["--colormode","color","--hierarchical","stacked","--mode","spline","--filter_speckle","0","--color_precision","8","--gradient_step","4","--segment_length","4.5","--path_precision","4"],name:"balanced"},{args:["--colormode","color","--hierarchical","stacked","--mode","spline","--filter_speckle","0","--color_precision","8","--gradient_step","2","--segment_length","3.5","--path_precision","5"],name:"detailed"},{args:["--preset","photo","--hierarchical","stacked","--filter_speckle","0"],name:"photo"}],El0=["--colormode","color","--hierarchical","cutout","--mode","spline","--filter_speckle","0","--color_precision","8","--gradient_step","2","--segment_length","3.5","--path_precision","5","--corner_threshold","30","--splice_threshold","20"]});var N91={};import{lstat as F91,realpath as J70}from"fs/promises";import{tmpdir as Q91}from"os";import{basename as Z91,dirname as J91}from"path";async function Y91(){let $;try{m_0();let F=await H91(),Q=K91(F),Z=j91(Q.input),J=await V91(Q.temporaryRoot),X=await e_0(Q.options.inheritedFileDescriptors,async()=>await A60(Z,Q.options,J));$={ok:!0,protocol:UX,result:X}}catch(F){$={error:W91(F),ok:!1,protocol:UX}}let _=JSON.stringify($);if(Buffer.byteLength(_)>ZD)_=JSON.stringify({error:{code:"output_limit",details:{maximumBytes:ZD},message:"The vectorization worker response exceeds its IPC limit."},ok:!1,protocol:UX});await Bun.write(Bun.stdout,_)}async function H91(){let $=Bun.stdin.stream().getReader(),_=[],F=0;try{while(!0){let{done:Q,value:Z}=await $.read();if(Q)break;if(F+=Z.byteLength,F>DK)throw await $.cancel(),new F0("input_limit","The vectorization worker request exceeds its IPC limit.",{bytes:F,maximumBytes:DK});_.push(Z)}}finally{$.releaseLock()}return Buffer.concat(_,F).toString("utf8")}function K91($){let _;try{_=JSON.parse($)}catch(F){throw new F0("invalid_input","The vectorization worker request is malformed.",{},{cause:F})}if(!od(_)||_.protocol!==UX||!od(_.input)||!od(_.options)||typeof _.temporaryRoot!=="string"||_.temporaryRoot.length===0||typeof _.input.kind!=="string"||typeof _.input.value!=="string"||!["bytes","path"].includes(_.input.kind))throw new F0("invalid_input","The vectorization worker request is invalid.");return _}function j91($){if($.kind==="path")return $.value;if($.value.length>Math.ceil(DK/3)*4||$.value.length%4!==0)throw new F0("input_limit","Encoded raster input exceeds its IPC limit.");let _=Buffer.from($.value,"base64");if(_.toString("base64")!==$.value)throw new F0("invalid_input","Encoded raster input is not canonical base64.");return _}async function V91($){let _,F;try{let Q=await Promise.all([J70($),J70(Q91())]);_=Q[0],F=Q[1];let Z=await F91($);if(!Z.isDirectory()||Z.isSymbolicLink()||J91(_)!==F||!/^slopcamera-vectorize-[A-Za-z0-9_-]{6,}$/u.test(Z91(_)))throw new F0("invalid_input","The supervisor temporary directory is invalid.")}catch(Q){if(Q instanceof F0)throw Q;throw new F0("invalid_input","The supervisor temporary directory could not be verified.",{},{cause:Q})}return _}function W91($){let _=$ instanceof F0&&X91.has($.code)?$.code:"trace_failed",F=$ instanceof Error?$.message:"The vectorization worker failed.",Q=$ instanceof F0&&Buffer.byteLength(JSON.stringify($.details))<=65536?$.details:{};return{code:_,details:Q,message:F}}function od($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var X91;var X70=Y_(async()=>{$h();k6();FD();XD();bA();X91=new Set(["input_limit","invalid_input","output_limit","quality_limit","timeout","tool_download","tool_integrity","tool_platform","tool_version","trace_failed","unsafe_svg"]);$60();await Y91()});import{maybeShowSupportInvitation as N70,runSupportCommand as O70}from"@hraness/support-foundation/node";var $c={id:"slopcamera",name:"Slopcamera",valueProposition:"Support ongoing development of local visual tools for agents.",updates:!1};function _c(){let $={...process.env};return process.env.HRANESS_SUPPORT_AUDIENCE="off",process.env.HRANESS_SUPPORT_EMAIL="off",$}async function Fc($,_={}){let F=await O70($c,$,{command:["slopcamera"],..._,gitEmail:!1});if(F.stdout!=="")process.stdout.write(F.stdout);if(F.stderr!=="")process.stderr.write(F.stderr);return F.exitCode}async function Qc($={}){try{await N70($c,{usefulResult:!0,command:["slopcamera"],...$,gitEmail:!1})}catch{}}class l0 extends Error{code;details;constructor($,_,F){super(_);this.name="SlopcameraCodeError",this.code=$,this.details=F===void 0?void 0:Object.freeze({...F})}}function YE($){return $ instanceof Error?$.message:String($)}function Zc($){if($ instanceof l0)return $;return new l0("internal",YE($))}function HE($,_=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(_)||_<0)return;let F=2;if(F>_)return;for(let Q=0;Q<$.length;Q+=1){let Z=$.charCodeAt(Q),J;if(Z===34||Z===92||Z===8||Z===9||Z===10||Z===12||Z===13)J=2;else if(Z<32)J=6;else if(Z<128)J=1;else if(Z<2048)J=2;else if(Z>=55296&&Z<=56319){let X=$.charCodeAt(Q+1);if(X>=56320&&X<=57343)J=4,Q+=1;else J=6}else if(Z>=56320&&Z<=57343)J=6;else J=3;if(J>_-F)return;F+=J}return F}function Jc($,_=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(_)||_<0)return;let F=0;for(let Q=0;Q<$.length;Q+=1){let Z=$.charCodeAt(Q),J;if(Z<128)J=1;else if(Z<2048)J=2;else if(Z>=55296&&Z<=56319){let X=$.charCodeAt(Q+1);if(X>=56320&&X<=57343)J=4,Q+=1;else J=3}else J=3;if(J>_-F)return;F+=J}return F}import{sha256 as G70}from"@noble/hashes/sha2.js";import{bytesToHex as w70}from"@noble/hashes/utils.js";var D70=new TextEncoder;function M8(){if(typeof Bun<"u"){let _=new Bun.CryptoHasher("sha256");return{digestHex:()=>_.digest("hex"),update:(F)=>{_.update(F)}}}let $=G70.create();return{digestHex:()=>w70($.digest()),update:(_)=>{$.update(typeof _==="string"?D70.encode(_):_)}}}function X0($){let _=M8();return _.update($),_.digestHex()}var L70=128,C70=1e6,B70=65536;function o2($,_){throw new l0("invalid-data",$,_)}function KE($,_){if(!Number.isSafeInteger($)||$<1)return o2(`${_} must be a positive safe integer.`);return $}function _C($){return Object.getOwnPropertySymbols($).some((_)=>Reflect.get($,_)?.enumerable===!0)}function jE($,_,F){if($===void 0){F(_);return}if(Array.isArray($.target))$.target[$.key]=_;else Object.defineProperty($.target,$.key,{configurable:!0,enumerable:!0,value:_,writable:!0})}function VE($){if(typeof $==="number"){if(!Number.isFinite($))return o2("JSON snapshots do not support non-finite numbers.");return JSON.stringify(Object.is($,-0)?0:$)}return JSON.stringify($)}function FC($,_,F,Q={},Z){let J=KE(_,"JSON snapshot byte limit"),X=KE(Q.maximumDepth??L70,"JSON snapshot depth limit"),Y=KE(Q.maximumValues??C70,"JSON snapshot value limit"),H=new WeakSet,K=Z.hash?M8():void 0,j=Z.hashPrefix??"",V=()=>{if(K===void 0||j.length===0)return;K.update(j),j=""},O=Z.captureText,W=[],G="",D=[{depth:0,kind:"visit",value:$}],w=0,L=1,C,B=(k,A=k.length)=>{if(A>J-w)return o2(`${F} contains more than ${String(J)} bytes.`,{actualLowerBound:w+A,maximumBytes:J});if(K!==void 0){if(j+=k,j.length>=B70)V()}if(O){if(G+=k,G.length>=65536)W.push(G),G=""}w+=A},z=(k)=>{if(k>Y-L)return o2(`${F} contains more than ${String(Y)} JSON values.`,{actualLowerBound:L+k,maximumValues:Y});L+=k},U=(k)=>{C=k};try{while(D.length>0){let k=D.pop();if(k===void 0)break;if(k.kind==="array"){if(k.index===k.values){if(B("]"),H.delete(k.source),k.clone!==void 0)Object.freeze(k.clone);continue}if(k.index>0)B(",");let I=k.descriptors[String(k.index)];if(I===void 0||I.get!==void 0||I.set!==void 0)return o2(`${F} arrays must contain plain data elements.`);D.push({...k,index:k.index+1}),D.push({...k.clone===void 0?{}:{assignment:{key:k.index,target:k.clone}},depth:k.depth+1,kind:"visit",value:I.value});continue}if(k.kind==="object"){if(k.index===k.keys.length){if(B("}"),H.delete(k.source),k.clone!==void 0)Object.freeze(k.clone);continue}let I=k.keys[k.index];if(I===void 0)return o2(`${F} lost an object key during traversal.`);if(k.index>0)B(",");let g=HE(I,J-w);if(g===void 0)return o2(`${F} contains more than ${String(J)} bytes.`,{actualLowerBound:J+1,maximumBytes:J});B(VE(I),g),B(":");let b=k.descriptors[I];if(b===void 0||b.get!==void 0||b.set!==void 0)return o2(`${F} properties must be plain data properties.`);D.push({...k,index:k.index+1}),D.push({...k.clone===void 0?{}:{assignment:{key:I,target:k.clone}},depth:k.depth+1,kind:"visit",value:b.value});continue}if(k.depth>X)return o2(`${F} nesting exceeds ${String(X)} levels.`,{actual:k.depth,maximumDepth:X});let A=k.value;if(A===null||typeof A==="boolean"||typeof A==="number"||typeof A==="string"){let I=typeof A==="number"&&Object.is(A,-0)?0:A;if(typeof A==="string"){let g=HE(A,J-w);if(g===void 0)return o2(`${F} contains more than ${String(J)} bytes.`,{actualLowerBound:J+1,maximumBytes:J});B(VE(A),g)}else B(VE(A));if(Z.captureValue)jE(k.assignment,I,U);continue}if(typeof A!=="object")return o2(`${F} does not support ${typeof A} values.`);if(H.has(A))return o2(`${F} does not support cyclic values.`);let q=Array.isArray(A)?A.length:void 0;if(q!==void 0&&q>Y-L)return o2(`${F} contains more than ${String(Y)} JSON values.`,{actualLowerBound:L+q,maximumValues:Y});if(q!==void 0){let I=2+Math.max(0,q-1);if(I>J-w)return o2(`${F} contains more than ${String(J)} bytes.`,{actualLowerBound:w+I,maximumBytes:J})}if(H.add(A),Array.isArray(A)){let I=q;if(I===void 0)return o2(`${F} lost an array length during traversal.`);L+=I;let g=Object.getOwnPropertyDescriptors(A);if(!Z.ignoreNonIndexArrayProperties){if(_C(g))return o2(`${F} cannot contain enumerable symbol properties.`);let y=Object.keys(g).filter((r)=>g[r]?.enumerable===!0);if(y.length!==I||y.some((r,h)=>r!==String(h)))return o2(`${F} arrays must be dense and cannot have named properties.`)}let b=Z.captureValue?[]:void 0;if(b!==void 0)jE(k.assignment,b,U);B("["),D.push({clone:b,depth:k.depth,descriptors:g,index:0,kind:"array",source:A,values:I});continue}let E=Object.getPrototypeOf(A);if(E!==Object.prototype&&E!==null)return o2(`${F} accepts only arrays and plain objects.`);let M=Object.getOwnPropertyDescriptors(A);if(_C(M))return o2(`${F} cannot contain enumerable symbol properties.`);let T=Object.keys(M).filter((I)=>M[I]?.enumerable===!0).sort();z(T.length);let P=Z.captureValue?{}:void 0;if(P!==void 0)jE(k.assignment,P,U);B("{"),D.push({clone:P,depth:k.depth,descriptors:M,index:0,keys:T,kind:"object",source:A})}}catch(k){if(k instanceof l0)throw k;throw new l0("invalid-data",`${F} could not be safely inspected.`,{cause:k instanceof Error?k.message:String(k)})}if(Z.captureValue&&C===void 0)return o2(`${F} did not contain a JSON value.`);if(O&&G.length>0)W.push(G);return V(),Object.freeze({bytes:w,...O?{canonicalText:W.join("")}:{},...K===void 0?{}:{sha256:K.digestHex()},...Z.captureValue?{value:C}:{},values:L})}function a0($,_,F,Q={}){let Z=FC($,_,F,Q,{captureText:!1,captureValue:!0,hash:!1,ignoreNonIndexArrayProperties:!1});if(Z.value===void 0)return o2(`${F} did not produce a complete JSON value snapshot.`);return Z}function t4($,_,F,Q={}){let Z=FC($,_,F,Q,{captureText:Q.captureCanonicalText===!0,captureValue:!0,hash:!0,ignoreNonIndexArrayProperties:!1});if(Z.sha256===void 0||Z.value===void 0)return o2(`${F} did not produce a complete JSON snapshot.`);return Z}function Xc($,_,F,Q={}){let Z=FC($,_,F,Q,{captureText:!0,captureValue:!1,hash:!1,ignoreNonIndexArrayProperties:!0});if(Z.canonicalText===void 0)return o2(`${F} did not produce canonical JSON text.`);return Z.canonicalText}function WE($,_,F,Q={},Z){let J=FC($,_,F,Q,{captureText:!1,captureValue:!1,hash:!0,ignoreNonIndexArrayProperties:!0,...Z===void 0?{}:{hashPrefix:Z}});if(J.sha256===void 0)return o2(`${F} did not produce a canonical JSON identity.`);return Object.freeze({bytes:J.bytes,sha256:J.sha256})}function Yc($,_,F,Q={},Z){return WE($,_,F,Q,Z).sha256}function $0($){let _=new WeakSet,F=new WeakSet,Q=[{exiting:!1,value:$}];try{while(Q.length>0){let Z=Q.pop();if(Z===void 0)break;let J=Z.value;if(J===null||typeof J==="boolean"||typeof J==="string")continue;if(typeof J==="number"){if(!Number.isFinite(J))return o2("JSON snapshots do not support non-finite numbers.");continue}if(typeof J!=="object")return o2(`JSON snapshots do not support ${typeof J} values.`);if(Z.exiting){_.delete(J),F.add(J),Object.freeze(J);continue}if(F.has(J))continue;if(_.has(J))return o2("JSON snapshots do not support cycles.");if(_.add(J),Q.push({exiting:!0,value:J}),Array.isArray(J)){let K=J.length,j=Object.getOwnPropertyDescriptors(J);if(_C(j))return o2("JSON snapshots cannot contain enumerable symbol properties.");let V=Object.keys(j).filter((O)=>j[O]?.enumerable===!0);if(V.length!==K||V.some((O,W)=>O!==String(W)))return o2("JSON snapshot arrays must be dense and cannot have named properties.");for(let O=K-1;O>=0;O-=1){let W=j[String(O)];if(W===void 0||W.get!==void 0||W.set!==void 0)return o2("JSON snapshot arrays must contain plain data elements.");Q.push({exiting:!1,value:W.value})}continue}let X=Object.getPrototypeOf(J);if(X!==Object.prototype&&X!==null)return o2("JSON snapshots accept only arrays and plain objects.");let Y=Object.getOwnPropertyDescriptors(J);if(_C(Y))return o2("JSON snapshots cannot contain enumerable symbol properties.");let H=Object.keys(Y).filter((K)=>Y[K]?.enumerable===!0);for(let K=H.length-1;K>=0;K-=1){let j=H[K];if(j===void 0)continue;let V=Y[j];if(V===void 0||V.get!==void 0||V.set!==void 0)return o2("JSON snapshot properties must be plain data properties.");if(V.value===void 0)return o2(`JSON snapshot property ${j} is undefined.`);Q.push({exiting:!1,value:V.value})}}}catch(Z){if(Z instanceof l0)throw Z;throw new l0("invalid-data","JSON snapshot could not be safely inspected.",{cause:Z instanceof Error?Z.message:String(Z)})}return $}var{MAX_SAFE_INTEGER:QC,MAX_SAFE_INTEGER:z70,MAX_SAFE_INTEGER:U70}=Number;function NE($,_){return $<_?-1:$>_?1:0}function OE($){return{maximumDepth:$?.maximumDepth??z70,maximumValues:$?.maximumValues??U70}}function Hc($,_){return Xc($,_.maximumBytes,_.name??"Canonical JSON",OE(_))}function $9($,_,F){return Yc($,_.maximumBytes,_.name??"Canonical JSON",OE(_),F)}function ZC($,_,F){return WE($,_.maximumBytes,_.name??"Canonical JSON",OE(_),F)}function R($){return Hc($,{maximumBytes:QC})}function m($){return $9($,{maximumBytes:QC})}function zN($,_){return $9(_,{maximumBytes:QC},$)}function J3($,_){return ZC($,{maximumBytes:QC},_)}import{z as EE}from"zod";import{z as M0}from"zod";var kN="slopcamera-workflow-graph-v2",MN="slopcamera-workflow-ref-v1",DY="slopcamera-workflow-graph-abi-v2",AN="slopcamera-requirement-envelope-v2",GE=1,HC="slopcamera-workflow-compilation-v1",k70="studio-workflow-graph-v2",M70="studio-workflow-ref-v1",Kc="studio-workflow-graph-abi-v2",A70="studio-requirement-envelope-v2",A8=4096,UN=4096,lZ=32,LY=4096,jc=2097152,Vc=2097152,Wc=300000,R70=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u,T70=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/u,q70=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\/[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)*$/u,Nc=/^[A-Za-z0-9][A-Za-z0-9._:/@-]*$/u,E70=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/u,P70=/^[a-f0-9]{64}$/u,wE=M0.string().min(1).max(128).regex(R70),KC=M0.string().min(1).max(64).regex(T70),m4=M0.string().min(1).max(255).regex(q70),I6=M0.string().min(1).max(192).regex(Nc),jC=M0.string().min(1).max(192).regex(Nc),DE=M0.string().min(3).max(192).regex(E70),W2=M0.string().regex(P70),H$=M0.number().int().positive().max(Number.MAX_SAFE_INTEGER),r5=M0.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),I70=M0.union([M0.string().min(1).max(128),r5]),LE=M0.string().refine(($)=>$!=="__proto__","JSON object keys must not use the reserved __proto__ name."),b70=Symbol("reserved-json-object");function CE($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.hasOwn($,"__proto__")?b70:$}var L1=M0.lazy(()=>M0.preprocess(CE,M0.union([M0.null(),M0.boolean(),M0.number().finite(),M0.string(),M0.array(L1),M0.record(LE,L1)]))),VC=M0.strictObject({$ref:M0.strictObject({nodeKey:m4,path:M0.array(I70).max(lZ).optional(),schemaId:I6}),version:M0.union([M0.literal(MN),M0.literal(M70)])}),S70=M0.lazy(()=>M0.record(LE,BE).superRefine(($,_)=>{if(Object.hasOwn($,"$ref"))_.addIssue({code:"custom",message:"The reserved $ref field must contain a complete versioned workflow reference."})})),BE=M0.lazy(()=>M0.preprocess(CE,M0.union([VC,M0.null(),M0.boolean(),M0.number().finite(),M0.string(),M0.array(BE),S70]))),f70=M0.lazy(()=>M0.record(LE,zE).superRefine(($,_)=>{if(Object.hasOwn($,"$ref"))_.addIssue({code:"custom",message:"The reserved $ref field must contain a complete versioned workflow reference."})})),zE=M0.lazy(()=>M0.preprocess(CE,M0.union([VC,M0.array(zE),f70]))),UE=M0.strictObject({kind:DE,version:H$}),RN=M0.strictObject({bounds:M0.strictObject({maxDurationMs:H$.max(Wc),maxInputBytes:H$.max(jc),maxOutputBytes:H$.max(Vc)}),key:jC,version:M0.literal(GE)}),TN=M0.discriminatedUnion("kind",[M0.strictObject({kind:M0.literal("operation"),operation:UE}),M0.strictObject({compute:RN,kind:M0.literal("compute")})]),WC=M0.strictObject({controlDependencies:M0.array(m4).max(UN).optional(),dependencies:M0.array(m4).max(UN),executor:TN,input:BE,inputSchemaId:I6,key:m4,label:M0.string().min(1).max(160).optional(),outputSchemaId:I6});function M4($){return $.executor.kind==="operation"}function F8($){return $.executor.kind==="compute"}var qN=M0.strictObject({id:wE,inputSchemaId:I6,version:H$}),u_=M0.strictObject({nodes:M0.array(WC).min(1).max(A8),outputs:zE,version:M0.union([M0.literal(kN),M0.literal(k70)]),workflow:qN}),Oc=Object.freeze(["pure","local-read","local-derived-write","project-mutation","paid-cloud","live-control"]),JC=Object.freeze([...Oc,"trusted-code"]),Gc=Object.freeze(["deterministic","verified-receipt","recoverable-transaction","ambiguous-after-dispatch","non-resumable-live"]),XC=Object.freeze([...Gc,"explicit-code-replay"]),X3=Object.freeze(["project-state","recording-metadata","screen-capture","camera","microphone","system-audio","typed-text","window-metadata","local-media","provider-options"]),y70=Object.freeze(["pure","local-artifact","project-transaction","paid-dispatch","live-control"]),dZ=Object.freeze(["cpu","local-io","ffmpeg","vision","whisper","network","paid-call","project-render","project-publication","output-publication","capture-device","browser"]),wc=M0.strictObject({amount:H$,resource:M0.enum(dZ)}),Kj=M0.strictObject({cache:M0.enum(["none","exact-run","content-addressed"]),cancellable:M0.boolean(),effect:M0.enum(Oc),maxDurationMs:H$,maxFanOut:r5,maxInputBytes:r5,maxOutputBytes:r5,preparation:M0.array(M0.enum(X3)).max(X3.length),resources:M0.array(wc).max(dZ.length),resume:M0.enum(Gc)}),Dc=M0.strictObject({cache:M0.literal("exact-run"),cancellable:M0.literal(!0),effect:M0.literal("trusted-code"),maxDurationMs:H$.max(Wc),maxFanOut:M0.literal(0),maxInputBytes:H$.max(jc),maxOutputBytes:H$.max(Vc),preparation:M0.tuple([]),resources:M0.tuple([M0.strictObject({amount:M0.literal(1),resource:M0.literal("cpu")})]),resume:M0.literal("explicit-code-replay")}),jj=M0.union([Kj,Dc]);function Vj($){return Dc.parse({cache:"exact-run",cancellable:!0,effect:"trusted-code",maxDurationMs:$.bounds.maxDurationMs,maxFanOut:0,maxInputBytes:$.bounds.maxInputBytes,maxOutputBytes:$.bounds.maxOutputBytes,preparation:[],resources:[{amount:1,resource:"cpu"}],resume:"explicit-code-replay"})}var Y3=M0.strictObject({inputSchemaId:I6,kind:DE,lifecycle:M0.enum(y70),outputSchemaId:I6,policy:Kj,version:H$}),NC=M0.strictObject({discovery:M0.array(Y3).max(LY),id:I6,projectionSha256:W2,trustedCompute:M0.boolean()}),Wj=M0.strictObject({maxDepth:H$,maxEdges:r5,maxFanOut:r5,maxNodes:H$.max(A8),maxTotalOperationFanOut:r5}),YC=Object.freeze(["dependency-outputs","exact-media-hashes","exact-sensitive-metadata-hashes","prices","project-generations","render-plans"]),g70=M0.strictObject({depth:r5,edges:r5,localMediaUploadNodes:r5,maxDurationMs:r5,maxInputBytes:r5,maxOutputBytes:r5,nodes:r5,paidCallClaims:r5,structuralFanOut:r5,totalOperationFanOut:r5}),EN=M0.strictObject({bounds:g70,computeKeys:M0.array(jC).max(A8),effects:M0.array(M0.enum(JC)).max(JC.length),operationFamilies:M0.array(KC).max(A8),operationKinds:M0.array(DE).max(A8),preparation:M0.array(M0.enum(X3)).max(X3.length),resources:M0.array(wc).max(dZ.length),resumeClasses:M0.array(M0.enum(XC)).max(XC.length),unresolved:M0.array(M0.enum(YC)).max(YC.length),version:M0.union([M0.literal(AN),M0.literal(A70)])}),Lc=M0.strictObject({compilationSha256:W2,envelope:EN,graph:u_,graphSha256:W2,limits:Wj,projection:NC,topologicalWaves:M0.array(M0.array(m4).min(1)).max(A8),version:M0.literal(HC)}),kE=Symbol.for("slopcamera.trusted-compute-definition"),Cc=Symbol.for("studio.trusted-compute-definition"),OC=Symbol.for("slopcamera.workflow-ref");function W5($,_,F){let Q=$.safeParse(_);if(!Q.success)throw new l0("invalid-data",`Invalid ${F}.`,{issues:Q.error.issues.map((Z)=>({code:Z.code,message:Z.message,path:Z.path.map(String)}))});return Q.data}import{z as u1}from"zod";var v70=4096,Bc=32768,Uc=67108864,kc=16777216,Mc=2000000,x70=67108864,E9=u1.string().min(1).max(v70).refine(($)=>!$.includes("\x00"),"Paths must not contain NUL bytes."),wC=u1.string().regex(/^[a-f0-9]{64}$/u),Nj=u1.string().min(1).max(256),zc=u1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),CY=u1.number().int().positive().max(Number.MAX_SAFE_INTEGER);function ME($){return $}var Ac=u1.string().min(3).max(256).regex(/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/iu),h70=u1.strictObject({path:E9}),m70=ME(u1.strictObject({outDirectory:E9.optional(),path:E9,scale:u1.number().finite().positive().max(4).optional()})),u70=ME(u1.strictObject({alphaCutoff:u1.number().int().min(1).max(64).optional(),duotone:u1.tuple([u1.string().regex(/^#[a-f0-9]{3}(?:[a-f0-9]{3})?$/iu),u1.string().regex(/^#[a-f0-9]{3}(?:[a-f0-9]{3})?$/iu)]).optional(),inputPath:E9,outputPath:E9.refine(($)=>$.toLowerCase().endsWith(".svg"),"Vector output paths must end in .svg."),timeoutMs:u1.number().int().min(1).max(300000).optional()})),l70=u1.string().superRefine(($,_)=>{if(Jc($,Bc)===void 0){_.addIssue({code:"custom",message:`Prompts must contain at most ${String(Bc)} UTF-8 bytes.`});return}if($.trim().length===0){_.addIssue({code:"custom",message:"Prompts must not be blank."});return}if(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test($))_.addIssue({code:"custom",message:"Prompts must not contain control characters."})}),d70=ME(u1.strictObject({model:Ac,outputPath:E9.refine(($)=>/\.(?:jpe?g|png|webp)$/iu.test($),"Generated image output paths must end in .png, .jpg, .jpeg, or .webp."),prompt:l70})),Rc=u1.strictObject({code:u1.string().min(1).max(160),message:u1.string().min(1).max(4096),shapeIds:u1.array(u1.string().min(1).max(256)).max(4096)}),c70=u1.strictObject({configPath:u1.null(),findings:u1.array(Rc).max(4096)}),p70=u1.strictObject({darkPng:E9,darkSvg:E9,lightPng:E9,lightSvg:E9,spec:E9,tldr:E9}),s70=u1.strictObject({artifacts:p70,configPath:u1.null(),findings:u1.array(Rc).max(4096)}),n70=u1.strictObject({alphaRmse:u1.number().finite().nonnegative(),colorRmse:u1.number().finite().nonnegative(),outsideAlphaRatio:u1.number().finite().min(0).max(1),sampleHeight:CY,sampleWidth:CY,supportRecall:u1.number().finite().min(0).max(1)}),r70=u1.strictObject({arch:Nj,platform:Nj,sharp:Nj,sharpVersions:u1.record(u1.string().min(1).max(128),Nj),vips:Nj,vtracerSha256:wC,vtracerSource:u1.enum(["official-release","override"]),vtracerVersion:Nj}),o70=u1.strictObject({alphaCutoff:u1.number().int().min(1).max(64),bytes:zc.max(Mc),candidatesEvaluated:CY,format:u1.string().min(1).max(80),height:CY.max(4096),inputBytes:CY.max(kc),outputMode:u1.enum(["color","duotone"]),pathCount:zc.max(12000),profile:u1.enum(["balanced","detailed","photo"]),provenance:r70,quality:n70,receiptVersion:u1.literal(1),representation:u1.enum(["color-paths","alpha-mask"]),sourceSha256:wC,svgSha256:wC,width:CY.max(4096)}),i70=u1.strictObject({outputPath:E9,receipt:o70}),a70=u1.strictObject({bytes:CY.max(Uc),mediaType:u1.enum(["image/jpeg","image/png","image/webp"]),model:Ac,outputPath:E9,provider:u1.literal("vercel-ai-gateway"),requestId:u1.string().min(1).max(256).refine(($)=>!/[\u0000-\u001f\u007f]/u.test($),"Request ids must not contain control characters."),sha256:wC,warnings:u1.array(u1.string().min(1).max(256)).max(100)}),Oj=Object.freeze(["slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.generate","slopcamera.image.vectorize"]);function t70($){let _=Object.freeze([...$.preparation]),F=Object.freeze($.resources.map((Q)=>Object.freeze({...Q})));return Object.freeze({...$,preparation:_,resources:F})}function GC($){return Object.freeze({...$,policy:t70($.policy)})}var cZ=Object.freeze({"slopcamera.diagram.check":GC({inputSchema:h70,inputSchemaId:"slopcamera.operation.diagram.check.input/v2",kind:"slopcamera.diagram.check",lifecycle:"pure",outputSchema:c70,outputSchemaId:"slopcamera.operation.diagram.check.output/v2",policy:{cache:"content-addressed",cancellable:!1,effect:"local-read",maxDurationMs:30000,maxFanOut:0,maxInputBytes:4096,maxOutputBytes:262144,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"}],resume:"deterministic"},version:2}),"slopcamera.diagram.render":GC({inputSchema:m70,inputSchemaId:"slopcamera.operation.diagram.render.input/v2",kind:"slopcamera.diagram.render",lifecycle:"local-artifact",outputSchema:s70,outputSchemaId:"slopcamera.operation.diagram.render.output/v2",policy:{cache:"none",cancellable:!1,effect:"local-derived-write",maxDurationMs:120000,maxFanOut:5,maxInputBytes:8192,maxOutputBytes:5*x70,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"}],resume:"ambiguous-after-dispatch"},version:2}),"slopcamera.image.generate":GC({inputSchema:d70,inputSchemaId:"slopcamera.operation.image.generate.input/v2",kind:"slopcamera.image.generate",lifecycle:"paid-dispatch",outputSchema:a70,outputSchemaId:"slopcamera.operation.image.generate.output/v2",policy:{cache:"exact-run",cancellable:!1,effect:"paid-cloud",maxDurationMs:120000,maxFanOut:1,maxInputBytes:16384,maxOutputBytes:Uc,preparation:["provider-options"],resources:[{amount:1,resource:"local-io"},{amount:1,resource:"network"},{amount:1,resource:"paid-call"}],resume:"ambiguous-after-dispatch"},version:2}),"slopcamera.image.vectorize":GC({inputSchema:u70,inputSchemaId:"slopcamera.operation.image.vectorize.input/v2",kind:"slopcamera.image.vectorize",lifecycle:"local-artifact",outputSchema:i70,outputSchemaId:"slopcamera.operation.image.vectorize.output/v2",policy:{cache:"none",cancellable:!1,effect:"local-derived-write",maxDurationMs:300000,maxFanOut:1,maxInputBytes:kc,maxOutputBytes:Mc,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"}],resume:"ambiguous-after-dispatch"},version:2})});var e70="slopcamera.workflow.registry-projection/v1",$V0="slopcamera.workflow.registry.public/v1",Tc=new WeakSet,qc=17+X3.length+3*dZ.length,RE=1+LY*qc,TE=33554432,Ec=8,_V0=TE+4096,FV0=Ec+1,QV0=RE+5;function ZV0($){return Array.isArray($)?$:$.list()}function qE($,_="operation discovery list"){if(!Array.isArray($))throw new l0("invalid-data",`${_} must be an array.`);let F=$.length;if(F>LY)throw new l0("invalid-data",`${_} cannot exceed ${String(LY)} entries.`);let Q=Object.getOwnPropertyDescriptors($);if(Object.getOwnPropertySymbols(Q).some((K)=>Reflect.get(Q,K)?.enumerable===!0))throw new l0("invalid-data",`${_} cannot contain enumerable symbol properties.`);let Z=Object.keys(Q).filter((K)=>Q[K]?.enumerable===!0);if(Z.length!==F||Z.some((K,j)=>K!==String(j)))throw new l0("invalid-data",`${_} must be dense and cannot have named properties.`);let X=2+Math.max(0,F-1),Y=1,H=[];for(let K=0;KRE)throw new l0("invalid-data",`${_} contains more than ${String(RE)} JSON values.`);H.push(O.value)}return Object.freeze(H)}function AE($,_){return`${$}@${String(_)}`}function JV0($){return[...new Set($)].sort((_,F)=>_.localeCompare(F))}function DC($){if($==="studio")return"slopcamera";return $.replace(/^studio\./u,"slopcamera.")}function Pc($){let _=qE($).map((Q)=>{let Z=W5(Y3,Q,"operation discovery entry"),J=JV0(Z.policy.preparation);if(J.length!==Z.policy.preparation.length)throw new l0("invalid-data",`Duplicate preparation requirement for ${AE(Z.kind,Z.version)}.`,{kind:Z.kind,version:Z.version});let X=[...Z.policy.resources].sort((Y,H)=>Y.resource.localeCompare(H.resource));if(new Set(X.map((Y)=>Y.resource)).size!==X.length)throw new l0("invalid-data",`Duplicate resource claim for ${AE(Z.kind,Z.version)}.`,{kind:Z.kind,version:Z.version});return W5(Y3,{...Z,policy:{...Z.policy,preparation:J,resources:X}},"normalized operation discovery entry")}).sort((Q,Z)=>Q.kind.localeCompare(Z.kind)||Q.version-Z.version),F=new Set;for(let Q of _){let Z=AE(Q.kind,Q.version);if(F.has(Z))throw new l0("conflict",`Duplicate operation discovery entry: ${Z}`,{kind:Q.kind,version:Q.version});F.add(Z)}return _}function XV0($){return Pc($).map((_)=>W5(Y3,{..._,inputSchemaId:DC(_.inputSchemaId),kind:DC(_.kind),outputSchemaId:DC(_.outputSchemaId)},"canonical operation discovery entry"))}function YV0($){return Object.freeze($.map((_)=>Object.freeze({..._,policy:Object.freeze({..._.policy,preparation:Object.freeze([..._.policy.preparation]),resources:Object.freeze(_.policy.resources.map((F)=>Object.freeze({...F})))})})))}function Ic($,_=e70){return zN(`${_}\x00`,{discovery:$.discovery,id:$.id,trustedCompute:$.trustedCompute})}function LC($,_,F={}){let Q=DC(W5(I6,$,"registry projection id")),Z=XV0(ZV0(_)),J=F.trustedCompute??!1,X=W5(NC,{discovery:Z,id:Q,projectionSha256:Ic({discovery:Z,id:Q,trustedCompute:J}),trustedCompute:J},"workflow registry projection"),Y=Object.freeze({...X,discovery:YV0(X.discovery)});return Tc.add(Y),Y}function bc($){if(typeof $==="object"&&$!==null&&Tc.has($))return $;let _=a0($,_V0,"workflow registry projection",{maximumDepth:FV0,maximumValues:QV0}).value,F=W5(NC,_,"workflow registry projection"),Q=Pc(F.discovery),Z={discovery:Q,id:F.id,trustedCompute:F.trustedCompute},J=Ic(Z);if(F.projectionSha256!==J)throw new l0("invalid-data","Workflow registry projection hash does not match its contents.",{actualProjectionSha256:F.projectionSha256,expectedProjectionSha256:J,projectionId:F.id});if(m(F.discovery)!==m(Q))throw new l0("invalid-data","Workflow registry projection discovery is not normalized.",{projectionId:F.id});return LC(F.id,Q,{trustedCompute:F.trustedCompute})}function HV0(){return Oj.map(($)=>{let _=cZ[$];return{inputSchemaId:_.inputSchemaId,kind:_.kind,lifecycle:_.lifecycle,outputSchemaId:_.outputSchemaId,policy:_.policy,version:_.version}})}function KV0(){return LC($V0,HV0(),{trustedCompute:!1})}var BY=KV0();var jV0="slopcamera.workflow.graph/v1",VV0="slopcamera.workflow.compilation/v1",PE=Object.freeze({maxDepth:64,maxEdges:2048,maxFanOut:64,maxNodes:256,maxTotalOperationFanOut:4096}),WV0=67108864,NV0=160,gc=1100000,OV0=1024,GV0=2,wV0=16;var DV0=17+X3.length+3*dZ.length,LV0=5+LY*DV0,CV0=21+3*A8+JC.length+X3.length+3*dZ.length+XC.length+YC.length,BV0=1+2*A8,zV0=6,t91=gc+LV0+CV0+BV0+zV0+4;function Q8($,_){throw new l0("invalid-data",$,_)}function vc($){if(typeof $!=="object"||$===null||Object.isFrozen($))return $;for(let _ of Object.values($))vc(_);return Object.freeze($)}function CC($,_){return`${$}@${String(_)}`}function H3($){return[...new Set($)].sort((_,F)=>_.localeCompare(F))}function zY($){if($==="studio")return"slopcamera";return $.replace(/^studio\./u,"slopcamera.")}function pZ($,_,F){let Q=$+_;if(!Number.isSafeInteger(Q))return Q8(`${F} exceeds the safe integer range.`,{left:$,right:_});return Q}function UV0($){if($===void 0)return PE;let _=a0($,OV0,"graph compiler limits",{maximumDepth:GV0,maximumValues:wV0}).value;if(typeof _!=="object"||_===null||Array.isArray(_))return W5(Wj,_,"graph compiler limits");return W5(Wj,{...PE,..._},"graph compiler limits")}function kV0($,_){if(typeof $!=="object"||$===null||Array.isArray($))return;let F=Object.getOwnPropertyDescriptor($,"nodes")?.value;if(Array.isArray(F)&&F.length>_)return Q8(`Workflow has ${String(F.length)} nodes; the limit is ${String(_)}.`,{actual:F.length,limit:_})}function MV0($,_=A8){kV0($,_);let F=a0($,WV0,"Authored workflow graph",{maximumDepth:NV0,maximumValues:gc}).value,Q=W5(u_,F,"authored workflow graph");if(Q.nodes.length>_)return Q8(`Workflow has ${String(Q.nodes.length)} nodes; the limit is ${String(_)}.`,{actual:Q.nodes.length,limit:_});let Z={...Q,nodes:[...Q.nodes].sort((J,X)=>J.key.localeCompare(X.key))};return $0(Z)}function BC($){if(xc($))return{$ref:{...$.$ref,schemaId:zY($.$ref.schemaId)},version:MN};if(Array.isArray($))return $.map(BC);if(typeof $==="object"&&$!==null)return Object.fromEntries(Object.entries($).map(([_,F])=>[_,BC(F)]));return $}function AV0($){return $0(W5(u_,{...$,nodes:$.nodes.map((_)=>({..._,executor:_.executor.kind==="operation"?{kind:"operation",operation:{..._.executor.operation,kind:zY(_.executor.operation.kind)}}:{compute:{..._.executor.compute,key:zY(_.executor.compute.key)},kind:"compute"},input:BC(_.input),inputSchemaId:zY(_.inputSchemaId),outputSchemaId:zY(_.outputSchemaId)})),outputs:BC($.outputs),version:kN,workflow:{...$.workflow,id:zY($.workflow.id),inputSchemaId:zY($.workflow.inputSchemaId)}},"canonical authored workflow graph"))}function Gj($,_=A8){return AV0(MV0($,_))}function RV0($){return zN(`${jV0}\x00`,$)}function xc($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.hasOwn($,"$ref")}function TV0($){return Array.isArray($)}function Sc($){let _=[],F=[$];while(F.length>0){let Q=F.pop();if(Q===void 0)continue;if(xc(Q)){_.push(Q);continue}if(TV0(Q)){for(let Z of Q)F.push(Z);continue}if(typeof Q==="object"&&Q!==null)for(let Z of Object.values(Q))F.push(Z)}return _}function fc($,_){return $.length===_.length&&$.every((F,Q)=>F===_[Q])}function yc($,_,F){let Q=_.get($.$ref.nodeKey);if(Q===void 0)return Q8(`${F} contains a dangling reference to ${$.$ref.nodeKey}.`,{nodeKey:$.$ref.nodeKey,owner:F});if(Q.outputSchemaId!==$.$ref.schemaId)return Q8(`${F} expects schema ${$.$ref.schemaId} from ${Q.key}, but the producer declares ${Q.outputSchemaId}.`,{actualSchemaId:Q.outputSchemaId,expectedSchemaId:$.$ref.schemaId,nodeKey:Q.key,owner:F})}function qV0($,_){let F=new Map,Q=new Map,Z=0;for(let j of $){let V=new Set(j.dependencies);F.set(j.key,V),Z=pZ(Z,V.size,"Workflow edge count");for(let O of V){let W=Q.get(O)??new Set;W.add(j.key),Q.set(O,W)}}if(Z>_.maxEdges)return Q8(`Workflow has ${String(Z)} edges; the limit is ${String(_.maxEdges)}.`,{actual:Z,limit:_.maxEdges});let J=Math.max(0,...[...Q.values()].map((j)=>j.size));if(J>_.maxFanOut)return Q8(`Workflow fan-out is ${String(J)}; the limit is ${String(_.maxFanOut)}.`,{actual:J,limit:_.maxFanOut});let X=$.filter((j)=>(F.get(j.key)?.size??0)===0).map((j)=>j.key).sort((j,V)=>j.localeCompare(V)),Y=new Map($.map((j)=>[j.key,F.get(j.key)?.size??0])),H=[],K=0;while(X.length>0){let j=X;H.push(j),K+=j.length;let V=new Set;for(let O of j)for(let W of Q.get(O)??[]){let G=(Y.get(W)??0)-1;if(Y.set(W,G),G===0)V.add(W)}X=[...V].sort((O,W)=>O.localeCompare(W))}if(K!==$.length)return Q8("Workflow graph contains a dependency cycle.");if(H.length>_.maxDepth)return Q8(`Workflow depth is ${String(H.length)}; the limit is ${String(_.maxDepth)}.`,{actual:H.length,limit:_.maxDepth});return{depth:H.length,edges:Z,structuralFanOut:J,waves:H}}function EV0($,_,F){let Q=Gj($,F.maxNodes);if(Q.nodes.length>F.maxNodes)return Q8(`Workflow has ${String(Q.nodes.length)} nodes; the limit is ${String(F.maxNodes)}.`,{actual:Q.nodes.length,limit:F.maxNodes});let Z=new Map;for(let H of Q.nodes){if(Z.has(H.key))return Q8(`Duplicate workflow node key: ${H.key}`,{nodeKey:H.key});Z.set(H.key,H)}let J=new Map(_.discovery.map((H)=>[CC(H.kind,H.version),H])),X=new Map,Y=0;for(let H of Q.nodes){let K;if(M4(H)){let G=H.executor.operation,D=J.get(CC(G.kind,G.version));if(D===void 0)throw new l0("unsupported-plan",`Unsupported operation: ${CC(G.kind,G.version)}`,{kind:G.kind,nodeKey:H.key,projectionId:_.id,version:G.version});if(H.inputSchemaId!==D.inputSchemaId||H.outputSchemaId!==D.outputSchemaId)return Q8(`Operation schema identity mismatch for ${CC(G.kind,G.version)} at node ${H.key}.`,{actualInputSchemaId:H.inputSchemaId,actualOutputSchemaId:H.outputSchemaId,expectedInputSchemaId:D.inputSchemaId,expectedOutputSchemaId:D.outputSchemaId,kind:G.kind,nodeKey:H.key,version:G.version});K=D.policy}else if(F8(H)){if(!_.trustedCompute)throw new l0("unsupported-plan",`Trusted compute is unsupported at node ${H.key}.`,{executorKind:"compute",nodeKey:H.key,projectionId:_.id});K=Vj(H.executor.compute)}else throw new l0("internal",`Unknown node executor for ${H.key}.`);X.set(H.key,K),Y=pZ(Y,K.maxFanOut,"Total operation fan-out");let j=Sc(H.input);for(let G of j)yc(G,Z,`Node ${H.key}`);let V=H.controlDependencies??[],O=H3(V);if(!fc(V,O))return Q8(`Node ${H.key} control dependencies must be unique and sorted.`,{nodeKey:H.key});for(let G of V){if(!Z.has(G))return Q8(`Node ${H.key} contains a dangling control dependency to ${G}.`,{dependency:G,nodeKey:H.key});if(G===H.key)return Q8(`Node ${H.key} cannot depend on itself.`,{nodeKey:H.key})}let W=H3([...j.map((G)=>G.$ref.nodeKey),...V]);if(!fc(H.dependencies,W))return Q8(`Node ${H.key} dependencies do not match its embedded references and explicit control dependencies. Expected [${W.join(", ")}].`,{expectedDependencies:W,nodeKey:H.key})}if(Y>F.maxTotalOperationFanOut)return Q8(`Workflow operation fan-out bound is ${String(Y)}; the limit is ${String(F.maxTotalOperationFanOut)}.`,{actual:Y,limit:F.maxTotalOperationFanOut});for(let H of Sc(Q.outputs))yc(H,Z,"Workflow outputs");return{graph:Q,policiesByNode:X,topology:qV0(Q.nodes,F)}}function PV0($){let _=$.indexOf(".");if(_<1)throw new l0("internal",`Operation ${$} has no namespace family.`,{kind:$});return $.slice(0,_)}function IV0($,_,F){$.set(_,pZ($.get(_)??0,F,`Resource ${_} claim`))}function bV0($){let _=new Set,F=new Set,Q=new Set,Z=new Set,J=new Set,X=new Map,Y=new Set,H=0,K=0,j=0,V=0,O=0;for(let G of $.graph.nodes){let D=$.policiesByNode.get(G.key);if(D===void 0)throw new l0("internal",`Node ${G.key} lost its execution policy.`);if(F.add(D.effect),Y.add(D.resume),M4(G))Q.add(PV0(G.executor.operation.kind)),Z.add(G.executor.operation.kind);else if(F8(G))Q.add("compute"),_.add(G.executor.compute.key);for(let w of D.preparation)J.add(w);for(let w of D.resources)IV0(X,w.resource,w.amount);if(D.effect==="paid-cloud"&&D.preparation.includes("local-media"))H=pZ(H,1,"Local media upload node count");K=pZ(K,D.maxDurationMs,"Workflow duration bound"),j=pZ(j,D.maxInputBytes,"Workflow input byte bound"),V=pZ(V,D.maxOutputBytes,"Workflow output byte bound"),O=pZ(O,D.maxFanOut,"Workflow operation fan-out bound")}let W=new Set;if($.topology.edges>0)W.add("dependency-outputs");if(J.has("local-media")||J.has("project-state")||J.has("recording-metadata"))W.add("exact-media-hashes");if(J.has("recording-metadata")||J.has("typed-text")||J.has("window-metadata"))W.add("exact-sensitive-metadata-hashes");if(F.has("paid-cloud")||X.has("paid-call"))W.add("prices");if(F.has("project-mutation")||Z.has("render.project")||Z.has("render.project-plan"))W.add("project-generations");if(Q.has("render"))W.add("render-plans");return W5(EN,{bounds:{depth:$.topology.depth,edges:$.topology.edges,localMediaUploadNodes:H,maxDurationMs:K,maxInputBytes:j,maxOutputBytes:V,nodes:$.graph.nodes.length,paidCallClaims:X.get("paid-call")??0,structuralFanOut:$.topology.structuralFanOut,totalOperationFanOut:O},computeKeys:H3(_),effects:H3(F),operationFamilies:H3(Q),operationKinds:H3(Z),preparation:H3(J),resources:[...X].map(([G,D])=>({amount:D,resource:G})).sort((G,D)=>G.resource.localeCompare(D.resource)),resumeClasses:H3(Y),unresolved:H3(W),version:AN},"workflow requirement envelope")}function SV0($){if($.projection!==void 0){if($.registry!==void 0||$.projectionId!==void 0||$.trustedCompute!==void 0)throw new l0("invalid-data","Compile with either a projection or a registry projection source, not both.");return bc($.projection)}if($.registry!==void 0){if($.projectionId===void 0)throw new l0("invalid-data","A registry projection source requires an explicit projection id.");return LC($.projectionId,$.registry,{trustedCompute:$.trustedCompute??!1})}if($.projectionId!==void 0||$.trustedCompute!==void 0)throw new l0("invalid-data","A projection id or trusted-compute authority requires a registry projection source.");return BY}var PN=EE.unknown().refine(($)=>$!==void 0,"Required"),e91=EE.strictObject({compilationSha256:W2,envelope:PN,graph:PN,graphSha256:W2,limits:PN,projection:PN,topologicalWaves:PN,version:EE.literal(HC)});function fV0($){return zN(`${VV0}\x00`,$)}function hc($){let _=UV0($.limits),F=SV0($),Q=EV0($.graph,F,_),Z=RV0(Q.graph),J={envelope:bV0(Q),graph:Q.graph,graphSha256:Z,limits:_,projection:F,topologicalWaves:Q.topology.waves,version:HC};return vc(W5(Lc,{...J,compilationSha256:fV0(J)},"compiled workflow graph"))}var zC=128,IN=1e6,mc=new WeakMap;function pc($){if($.consumed>=$.maximum)throw new l0("invalid-data",`Workflow authoring values exceed the ${String(IN)} value limit.`);$.consumed+=1}function sc($,_){bN($,_),$.consumed+=_}function bN($,_){if(_>$.maximum-$.consumed)throw new l0("invalid-data",`Workflow authoring values exceed the ${String(IN)} value limit.`)}function nc($){return{consumed:0,maximum:IN-$.authoredValues}}function uc($,_){if(_>IN-$.authoredValues)throw new l0("invalid-data",`Workflow authoring values exceed the ${String(IN)} value limit.`)}function yV0($){if($[kE]===!0)return $;if(Reflect.get($,Cc)!==!0)return;let _=mc.get($);if(_!==void 0)return _;let F=Object.freeze({[kE]:!0,bounds:$.bounds,inputSchema:$.inputSchema,inputSchemaId:$.inputSchemaId,key:$.key,outputSchema:$.outputSchema,outputSchemaId:$.outputSchemaId,run:$.run});return mc.set($,F),F}function IE($,_){return`${$}@${String(_)}`}function gV0($){let _=$,F=typeof _.list==="function"?_.list():$.discovery;return qE(F)}function rc($){let _=Object.getPrototypeOf($);return _===Object.prototype||_===null}function SN($,_){if(Object.getOwnPropertySymbols($).some((F)=>Reflect.get($,F)?.enumerable===!0))throw new l0("invalid-data",`${_} cannot contain enumerable symbol properties.`)}function fE($){return $0(W5(VC,$.serialized,"workflow reference"))}function oc($){let _=$.$ref.path;return _===void 0?5:6+_.length}function yE($,_){return typeof $==="object"&&$!==null&&OC in $&&_.references.has($)}function bE($,_,F,Q,Z,J){if(Z>zC)throw new l0("invalid-data",`Workflow input nesting exceeds ${String(zC)} levels.`);if(yE($,_)){let X=fE($);return sc(J,oc(X)),F.add(X.$ref.nodeKey),X}if(pc(J),typeof $==="object"&&$!==null&&OC in $)throw new l0("invalid-data","Use a typed Ref value created by this workflow graph builder.");if($===null||typeof $==="boolean"||typeof $==="string")return $;if(typeof $==="number"){if(!Number.isFinite($))throw new l0("invalid-data","Workflow node input numbers must be finite.");return Object.is($,-0)?0:$}if(typeof $!=="object")throw new l0("invalid-data",`Workflow node input cannot contain ${typeof $} values.`);if(Q.has($))throw new l0("invalid-data","Workflow node input cannot contain cycles.");Q.add($);try{if(Array.isArray($)){let K=$.length;bN(J,K);let j=Object.getOwnPropertyDescriptors($);SN(j,"Workflow node input arrays");let V=Object.keys(j).filter((W)=>j[W]?.enumerable===!0);if(V.length!==K||V.some((W,G)=>W!==String(G)))throw new l0("invalid-data","Workflow node input arrays must be dense and cannot have named properties.");let O=[];for(let W=0;WX[K]?.enumerable===!0).sort();bN(J,Y.length);let H={};for(let K of Y){if(K==="__proto__")throw new l0("invalid-data","Workflow inputs cannot contain the reserved __proto__ object key.");let j=X[K];if(j===void 0||j.get!==void 0||j.set!==void 0)throw new l0("invalid-data","Workflow node input properties must be plain data properties.");H[K]=bE(j.value,_,F,Q,Z+1,J)}return H}finally{Q.delete($)}}function lc($,_){let F=new Set,Q=nc(_),Z=bE($,_,F,new Set,0,Q);return{dependencies:[...F].sort((J,X)=>J.localeCompare(X)),value:Z,values:Q.consumed}}function dc($,_){if($===void 0)return[];let F=new Set,Q=(Y)=>{if(!yE(Y,_))throw new l0("invalid-data","Operation control dependencies must be typed Ref values created by this workflow graph builder.");F.add(fE(Y).$ref.nodeKey)};if(!Array.isArray($))return Q($),[...F];let Z=$.length;if(Z>UN)throw new l0("invalid-data",`Operation control dependencies cannot exceed ${String(UN)} entries.`);let J=Object.getOwnPropertyDescriptors($);SN(J,"Operation control dependencies");let X=Object.keys(J).filter((Y)=>J[Y]?.enumerable===!0);if(X.length!==Z||X.some((Y,H)=>Y!==String(H)))throw new l0("invalid-data","Operation control dependencies must be a dense array without named properties.");for(let Y=0;YY.localeCompare(H))}function cc($,_){return[...new Set([...$,..._])].sort((F,Q)=>F.localeCompare(Q))}function SE($,_,F,Q,Z){if(Q>zC)throw new l0("invalid-data",`Workflow output nesting exceeds ${String(zC)} levels.`);if(yE($,_)){let J=fE($);return sc(Z,oc(J)),J}if(pc(Z),typeof $!=="object"||$===null)throw new l0("invalid-data","Workflow outputs must contain only typed references, arrays, and named objects.");if(F.has($))throw new l0("invalid-data","Workflow outputs cannot contain cycles.");F.add($);try{if(Array.isArray($)){let H=$.length;bN(Z,H);let K=Object.getOwnPropertyDescriptors($);SN(K,"Workflow output arrays");let j=Object.keys(K).filter((O)=>K[O]?.enumerable===!0);if(j.length!==H||j.some((O,W)=>O!==String(W)))throw new l0("invalid-data","Workflow output arrays must be dense and cannot have named properties.");let V=[];for(let O=0;OJ[H]?.enumerable===!0).sort();bN(Z,X.length);let Y={};for(let H of X){if(H==="__proto__")throw new l0("invalid-data","Workflow outputs cannot contain the reserved __proto__ object key.");let K=J[H];if(K===void 0||K.get!==void 0||K.set!==void 0)throw new l0("invalid-data","Workflow output properties must be plain data properties.");Y[H]=SE(K.value,_,F,Q+1,Z)}return Y}finally{F.delete($)}}function UC($,_,F,Q=[]){if(Q.length>lZ)throw new l0("invalid-data",`Workflow reference paths cannot exceed ${String(lZ)} segments.`);let Z=$0({$ref:{nodeKey:$,...Q.length===0?{}:{path:[...Q]},schemaId:_},version:MN}),J=Object.freeze({[OC]:()=>{throw new l0("internal","A workflow reference type marker is not executable.")},at:(X)=>{if(!Number.isSafeInteger(X)||X<0)throw new l0("invalid-data","Workflow reference array indexes must be nonnegative safe integers.");if(Q.length>=lZ)throw new l0("invalid-data",`Workflow reference paths cannot exceed ${String(lZ)} segments.`);return UC($,_,F,[...Q,X])},select:(X)=>{if(typeof X!=="string"||X.length<1||X.length>128)throw new l0("invalid-data","Workflow reference field names must contain 1\u2013128 characters.");if(Q.length>=lZ)throw new l0("invalid-data",`Workflow reference paths cannot exceed ${String(lZ)} segments.`);return UC($,_,F,[...Q,X])},serialized:Z});return F.references.add(J),J}function vV0($){let _=new Map;for(let F of gV0($)){let Q=W5(Y3,F,"operation discovery entry"),Z=IE(Q.kind,Q.version);if(_.has(Z))throw new l0("conflict",`Duplicate operation discovery entry: ${Z}`,{kind:Q.kind,version:Q.version});_.set(Z,Q)}return{authoredValues:7,computes:new Map,discovery:_,nodes:new Map,references:new WeakSet}}class wj{#$;#_;constructor($,_){this.#$=_,this.#_=$}static create($){return new wj(vV0($),[])}namespace($){let _=W5(KC,$,"workflow namespace segment");return new wj(this.#_,[...this.#$,_])}fragment($,_,F){return _.build(this.namespace($),F)}operation($,_,F,Q={}){return this.#J($,{input:F,inputSchemaId:_.inputSchemaId,kind:_.kind,outputSchemaId:_.outputSchemaId,version:_.version},Q)}operationByKind($,_,F={}){let Q=this.#_.discovery.get(IE(_.kind,_.version));if(Q===void 0)throw new l0("unsupported-plan",`Unsupported operation: ${_.kind}@${String(_.version)}`,{kind:_.kind,version:_.version});return this.#J($,{input:_.input,inputSchemaId:Q.inputSchemaId,kind:_.kind,outputSchemaId:Q.outputSchemaId,version:_.version},F)}compute($,_,F,Q={}){if(typeof _!=="object"||_===null)throw new l0("invalid-data","Compute nodes require a definition created by defineCompute().");let Z=yV0(_);if(Z===void 0)throw new l0("invalid-data","Compute nodes require a definition created by defineCompute().");let J=W5(RN,{bounds:Z.bounds,key:Z.key,version:GE},"trusted compute identity"),X=this.#_.computes.get(J.key);if(X!==void 0&&X!==Z)throw new l0("conflict",`Duplicate trusted compute key: ${J.key}`,{key:J.key});let Y=this.#Q($),H=lc(F,this.#_),K=dc(Q.after,this.#_),j=cc(H.dependencies,K),V=H.values+15+K.length+j.length+(Q.label===void 0?0:1);uc(this.#_,V);let O=W5(WC,{controlDependencies:K,dependencies:j,executor:{compute:J,kind:"compute"},input:H.value,inputSchemaId:Z.inputSchemaId,key:Y,...Q.label===void 0?{}:{label:Q.label},outputSchemaId:Z.outputSchemaId},"authored compute node");return this.#_.computes.set(J.key,Z),this.#_.nodes.set(Y,O),this.#_.authoredValues+=V,UC(Y,Z.outputSchemaId,this.#_)}computeDefinitions(){return Object.freeze([...this.#_.computes.values()].sort(($,_)=>$.key.localeCompare(_.key)))}build($,_){let F=W5(qN,$,"workflow identity"),Q=nc(this.#_),Z=SE(_,this.#_,new Set,0,Q);return $0(W5(u_,{nodes:[...this.#_.nodes.values()].sort((J,X)=>J.key.localeCompare(X.key)),outputs:Z,version:kN,workflow:F},"authored workflow graph"))}#Q($){let _=W5(KC,$,"workflow node key segment"),F=[...this.#$,_].join("/");if(this.#_.nodes.has(F))throw new l0("conflict",`Duplicate workflow node key: ${F}`,{nodeKey:F});if(this.#_.nodes.size>=A8)throw new l0("invalid-data",`Workflow nodes cannot exceed ${String(A8)} entries.`);return F}#J($,_,F){let Q=this.#Q($),Z=this.#_.discovery.get(IE(_.kind,_.version));if(Z===void 0)throw new l0("unsupported-plan",`Unsupported operation: ${_.kind}@${String(_.version)}`,{kind:_.kind,version:_.version});if(_.inputSchemaId!==Z.inputSchemaId||_.outputSchemaId!==Z.outputSchemaId)throw new l0("invalid-data",`Operation contract schema mismatch for ${_.kind}@${String(_.version)}.`,{actualInputSchemaId:_.inputSchemaId,actualOutputSchemaId:_.outputSchemaId,expectedInputSchemaId:Z.inputSchemaId,expectedOutputSchemaId:Z.outputSchemaId,kind:_.kind,version:_.version});let J=lc(_.input,this.#_),X=dc(F.after,this.#_),Y=cc(J.dependencies,X),H=J.values+11+X.length+Y.length+(F.label===void 0?0:1);uc(this.#_,H);let K=W5(WC,{controlDependencies:X,dependencies:Y,executor:{kind:"operation",operation:{kind:Z.kind,version:Z.version}},input:J.value,inputSchemaId:Z.inputSchemaId,key:Q,...F.label===void 0?{}:{label:F.label},outputSchemaId:Z.outputSchemaId},"authored operation node");return this.#_.nodes.set(Q,K),this.#_.authoredValues+=H,UC(Q,Z.outputSchemaId,this.#_)}}var N=l0,uF=YE;function UY($){return Zc($)}var kC={usage:2,"not-found":3,conflict:4,unavailable:5,"unsafe-path":6,"invalid-data":7,subprocess:8,"unsupported-plan":9,"authorization-required":10,cancelled:11,ambiguous:12,incompatible:13,internal:1};function kY($){if($ instanceof N)return $;return new N("internal",uF($))}var Dj=1e4;var gE=["blender-product","blender-character","blender-shaded-street","blender-cloth","blender-fluid","cadquery-bracket","manim-lesson"];import{createHash as AC,randomUUID as KW0}from"crypto";import{link as jW0,mkdir as Jp,rm as VW0,writeFile as WW0}from"fs/promises";import{dirname as NW0,join as RC,resolve as OW0}from"path";import MY from"sharp";class h1 extends Error{code;constructor($,_,F){super(`[${$}] ${_}`,F);this.name="SlopcameraCloudError",this.code=$}}import{createHash as xE,randomUUID as tc}from"crypto";import{link as xV0,rm as hV0,writeFile as mV0}from"fs/promises";import{dirname as uV0,extname as lV0,resolve as ic}from"path";var fN="https://ai-gateway.vercel.sh/v4/ai",ec=Object.freeze(["openai/gpt-image-1.5","recraft/recraft-v4.1-utility"]),dV0=Object.freeze(["image/png","image/jpeg","image/webp"]),nZ=32768,cV0=67108864,pV0=300000,ac=1800000,sV0=100663296;function Lj($){throw new h1("INVALID_ARGUMENT",$)}function MC($){if($.length<16||$.length>16384||$.trim()!==$||/[^\x21-\x7e]/u.test($))throw new h1("AUTHENTICATION_REQUIRED","The selected Vercel AI Gateway credential is invalid.");return $}function $p($){return $??process.env}function hE($){let _=$p($);if(_.AI_GATEWAY_API_KEY!==void 0)return{source:"AI_GATEWAY_API_KEY",token:MC(_.AI_GATEWAY_API_KEY)};if(_.VERCEL_OIDC_TOKEN!==void 0)return{source:"VERCEL_OIDC_TOKEN",token:MC(_.VERCEL_OIDC_TOKEN)};throw new h1("AUTHENTICATION_REQUIRED","Set AI_GATEWAY_API_KEY or run Slopcamera through `vercel env run -- \u2026` with VERCEL_OIDC_TOKEN available.")}function _p($){let _=$p($);if(_.AI_GATEWAY_API_KEY!==void 0)return MC(_.AI_GATEWAY_API_KEY),{available:!0,source:"AI_GATEWAY_API_KEY"};if(_.VERCEL_OIDC_TOKEN!==void 0)return MC(_.VERCEL_OIDC_TOKEN),{available:!0,source:"VERCEL_OIDC_TOKEN"};return{available:!1,source:null}}function nV0($){if(typeof $!=="string"||$.length<3||$.length>256||!/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/iu.test($))Lj("Model must be a bounded Vercel AI Gateway provider/model id.");return $}function rV0($){if(typeof $!=="string"||$.trim().length===0||/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test($)||Buffer.byteLength($,"utf8")>nZ)Lj(`Prompt must be non-empty and no more than ${nZ} UTF-8 bytes.`);return $}function oV0($){let _=$??pV0;if(!Number.isSafeInteger(_)||_<1000||_>ac)Lj(`timeoutMs must be an integer from 1000 through ${ac}.`);return _}function sZ($){return typeof $==="object"&&$!==null||typeof $==="function"}function iV0($){if(typeof $!=="function")throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.");return $}function aV0(){globalThis.AI_SDK_LOG_WARNINGS=!1}function vE($){if($.aborted)throw new h1("GENERATION_FAILED","Vercel AI Gateway image generation was cancelled or exceeded its deadline.")}async function tV0(){let $,_;try{[$,_]=await Promise.all([import("ai-v7"),import("@ai-sdk/gateway-v4")])}catch{throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.")}if(!sZ($)||!sZ(_))throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.");let F=iV0($.generateImage);if(typeof _.createGateway!=="function")throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.");let Q=_.createGateway;return{createGateway:(Z)=>{let J=Q(Z);if(!sZ(J)||typeof J.imageModel!=="function")throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.");let X=J.imageModel;return{imageModel:(Y)=>X.call(J,Y)}},generateImage:F}}function eV0($){try{if($ instanceof Request)return new URL($.url);if($ instanceof URL)return new URL($.href);return new URL($,fN)}catch{throw new h1("GENERATION_FAILED","The Vercel AI Gateway request was rejected.")}}function $W0($,_){if(!($ instanceof Request))return _;let F=new Request($),Q=F.method==="GET"||F.method==="HEAD"?void 0:F.body??void 0,Z={headers:F.headers,method:F.method,signal:F.signal,...Q===void 0?{}:{body:Q,duplex:"half"}};return new Request(_.href,Z)}function _W0($,_){let F=$.headers.get("content-length");if(F!==null){let X=Number(F);if(!Number.isSafeInteger(X)||X<0||X>_)throw $.body?.cancel().catch(()=>{return}),new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded response.")}if($.body===null)return $;let Q=$.body.getReader(),Z=0,J=new ReadableStream({cancel:async(X)=>await Q.cancel(X),pull:async(X)=>{try{let Y=await Q.read();if(Y.done){Q.releaseLock(),X.close();return}if(Z+=Y.value.byteLength,Z>_){await Q.cancel().catch(()=>{return}),X.error(new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded response."));return}X.enqueue(Y.value)}catch{X.error(new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded response."))}}});return new Response(J,{headers:$.headers,status:$.status,statusText:$.statusText})}function mE($={}){let _=$.fetch??globalThis.fetch,F=$.maximumResponseBytes??sV0;if(!Number.isSafeInteger(F)||F<1||F>1073741824)Lj("maximumResponseBytes is outside the supported range.");let Q=new URL(fN);return async(Z,J)=>{let X=eV0(Z);if(X.origin!==Q.origin||X.pathname!==Q.pathname&&!X.pathname.startsWith(`${Q.pathname}/`)||X.username!==""||X.password!=="")throw new h1("GENERATION_FAILED","The Vercel AI Gateway request was rejected.");let Y=$W0(Z,X),H;try{H=await _(Y,{...J,redirect:"error"})}catch(K){if(K instanceof h1)throw K;throw new h1("GENERATION_FAILED","Vercel AI Gateway image generation failed; the request was not retried.")}if(H.redirected||H.status>=300&&H.status<400)throw await H.body?.cancel().catch(()=>{return}),new h1("GENERATION_FAILED","The Vercel AI Gateway request was rejected.");return _W0(H,F)}}function FW0($,_){let F=new AbortController,Q=()=>F.abort($?.reason),Z,J=new Promise((H,K)=>{Z=K}),X=()=>{Z?.(new h1("GENERATION_FAILED","Vercel AI Gateway image generation was cancelled or exceeded its deadline."))};if(F.signal.addEventListener("abort",X,{once:!0}),$?.aborted===!0)Q();$?.addEventListener("abort",Q,{once:!0});let Y=setTimeout(()=>F.abort(),_);return{dispose:()=>{clearTimeout(Y),$?.removeEventListener("abort",Q),F.signal.removeEventListener("abort",X),Z=void 0},interruption:J,signal:F.signal}}function QW0($){if(typeof $!=="string"||!dV0.includes($))throw new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an unsupported image type.");return $}function ZW0($,_){if($.byteLength<12||$.byteLength>cV0)return!1;if(_==="image/png")return Buffer.from($.subarray(0,8)).equals(Buffer.from([137,80,78,71,13,10,26,10]));if(_==="image/jpeg")return $[0]===255&&$[1]===216&&$.at(-2)===255&&$.at(-1)===217;return $.byteLength>=16&&Buffer.from($.subarray(0,4)).toString("ascii")==="RIFF"&&Buffer.from($).readUInt32LE(4)===$.byteLength-8&&Buffer.from($.subarray(8,12)).toString("ascii")==="WEBP"&&["VP8 ","VP8L","VP8X"].includes(Buffer.from($.subarray(12,16)).toString("ascii"))}function JW0($){let _="provider-warning",F="Provider warning";if(typeof $==="string")F=$;else if(sZ($)){if(typeof $.type==="string"&&$.type.length<=64)_=$.type.replace(/[^a-z0-9._-]/giu,"-")||_;if(typeof $.message==="string")F=$.message;else if(typeof $.details==="string")F=$.details}return`${_} sha256:${xE("sha256").update(F).digest("hex")}`}function XW0($,_){if(!sZ($)||!Array.isArray($.images)||$.images.length!==1)throw new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway did not return exactly one image.");let F=$.images[0];if(!sZ(F)||!(F.uint8Array instanceof Uint8Array))throw new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded image.");let Q=QW0(F.mediaType);if(!ZW0(F.uint8Array,Q))throw new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded image.");let Z=sZ($.providerMetadata)&&sZ($.providerMetadata.gateway)?$.providerMetadata.gateway:void 0,J=Z!==void 0&&typeof Z.generationId==="string"&&Z.generationId.length>0&&Z.generationId.length<=256&&!/[\u0000-\u001f\u007f]/u.test(Z.generationId)?Z.generationId:tc(),X=`sha256:${xE("sha256").update("slopcamera.gateway-generation-id/v1\x00").update(J).digest("hex")}`,Y=Array.isArray($.warnings)?$.warnings.slice(0,100).map(JW0):[];return{bytes:F.uint8Array,response:{image:{base64:Buffer.from(F.uint8Array).toString("base64"),mediaType:Q},model:_,provider:"vercel-ai-gateway",requestId:X,warnings:Y}}}async function Fp($,_){let F=nV0($.model),Q=rV0($.prompt),Z=hE(_.environment),J=FW0($.signal,oV0($.timeoutMs));try{let X=(async()=>{vE(J.signal),aV0();let Y=await(_.loadRuntime??tV0)();vE(J.signal);let H=Y.createGateway({apiKey:Z.token,baseURL:fN,fetch:mE({..._.fetch===void 0?{}:{fetch:_.fetch},..._.maximumResponseBytes===void 0?{}:{maximumResponseBytes:_.maximumResponseBytes}})});vE(J.signal);let K=await Y.generateImage({abortSignal:J.signal,maxRetries:0,model:H.imageModel(F),n:1,prompt:Q});return XW0(K,F)})();return await Promise.race([X,J.interruption])}catch(X){if(X instanceof h1)throw X;throw new h1("GENERATION_FAILED","Vercel AI Gateway image generation failed; the request was not retried.")}finally{J.dispose()}}async function Cj($,_={}){return(await Fp($,_)).response}function YW0($){let _=lV0($).toLocaleLowerCase("en-US");if(_===".png")return"image/png";if(_===".jpg"||_===".jpeg")return"image/jpeg";if(_===".webp")return"image/webp";Lj("Output path must end in .png, .jpg, .jpeg, or .webp.")}async function HW0($,_){let F=ic($),Q=ic(uV0(F),`.${tc()}.slopcamera-generate.tmp`);try{return await mV0(Q,_,{flag:"wx"}),await xV0(Q,F),F}catch{throw new h1("OUTPUT_WRITE_FAILED","Slopcamera could not atomically write the generated image.")}finally{await hV0(Q,{force:!0}).catch(()=>{return})}}async function Bj($,_={}){if(typeof $.outputPath!=="string"||$.outputPath.length<1||$.outputPath.length>4096||$.outputPath.includes("\x00"))Lj("Output path must be a non-empty local path.");let F=YW0($.outputPath),Q=await Fp($,_);if(Q.response.image.mediaType!==F)throw new h1("GENERATION_INVALID_RESPONSE",`Generated ${Q.response.image.mediaType} does not match the requested ${F} output path.`);let Z=await HW0($.outputPath,Q.bytes);return{bytes:Q.bytes.byteLength,mediaType:Q.response.image.mediaType,model:Q.response.model,outputPath:Z,provider:Q.response.provider,requestId:Q.response.requestId,sha256:xE("sha256").update(Q.bytes).digest("hex"),warnings:Q.response.warnings}}var K3=Object.freeze(["image","texture","skybox","backdrop","sprite"]),H_=Object.freeze(["style","palette","material","lighting","mood","detail"]),w1=Object.freeze({candidates:16,concurrency:4,subjectBytes:2048,candidatePromptBytes:nZ,variantBytes:1024,idLength:64,cellEdgeMin:64,cellEdgeMax:1024,cellEdgeDefault:512,labelHeight:28,cellGap:8,galleryPixels:33554432,candidatePixels:33554432,candidateEdge:8192}),Xp={image:{aspect:[1,1],frame:($)=>$,rules:"Clean readable composition; no text, captions, borders, or watermark."},texture:{aspect:[1,1],frame:($)=>`Seamless tileable texture of ${$}.`,rules:"Flat orthographic top-down material surface, uniform diffuse lighting, edge-to-edge surface detail that tiles in both directions; no shadows, no specular highlights, no vignette, no borders, no objects, no text."},skybox:{aspect:[2,1],frame:($)=>`Seamless equirectangular 360-degree panorama of ${$}.`,rules:"Full spherical environment in 2:1 equirectangular projection, continuous horizon exactly at the vertical center, left and right edges wrapping seamlessly; no seams, no text, no watermark, no foreground frame."},backdrop:{aspect:[16,9],frame:($)=>`Flat scenic backdrop plate of ${$}.`,rules:"Edge-to-edge environment plate for compositing behind foreground subjects, consistent perspective and lighting across the frame; no borders, no text, no watermark."},sprite:{aspect:[1,1],frame:($)=>`A single ${$} on a plain solid neutral background.`,rules:"One centered subject, fully visible with a clean silhouette, flat even lighting; no shadows, no extra objects, no text, no watermark."}},Qp={style:["photorealistic","stylized painterly","flat minimal","hand-drawn"],palette:["warm earthy palette","cool desaturated palette","neutral grayscale palette","vivid saturated palette"],material:["rough weathered surface","smooth polished surface","organic natural surface","synthetic industrial surface"],lighting:["soft diffuse lighting","dramatic directional lighting","flat ambient lighting","golden-hour lighting"],mood:["serene calm mood","dramatic mood","playful mood","mysterious mood"],detail:["minimal sparse detail","balanced detail","intricate dense detail"]},GW0={material:["clear air","light haze","thin clouds","dense dramatic clouds"],lighting:["golden hour","overcast midday","clear night sky","midday sun"]};function wW0($,_){return $==="skybox"?GW0[_]??Qp[_]:Qp[_]}function d2($){throw new h1("INVALID_ARGUMENT",$)}function gN($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function yN($,_,F){if(typeof $!=="string"||$.trim().length===0||/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test($)||Buffer.byteLength($,"utf8")>F)d2(`${_} must be non-empty text no more than ${F} UTF-8 bytes.`);return $.trim()}function DW0($){let _=yN($,"Candidate id",w1.idLength);if(!/^[a-z0-9][a-z0-9._-]*$/iu.test(_))d2("Candidate id must start with an alphanumeric and contain only alphanumerics, '.', '_', or '-'.");return _}function Yp($){let _=$.toLowerCase().split(/[^a-z0-9]+/u).filter((F)=>F.length>0).join("-").slice(0,w1.idLength);return _.length===0?"candidate":_}function LW0($){let _=$??"image";if(typeof _!=="string"||!K3.includes(_))d2(`kind must be one of: ${K3.join(", ")}.`);return _}function uE($,_,F){let Q=Xp[_],Z=[Q.frame($),`Rules: ${Q.rules}`],J=F?.trim();if(J!==void 0&&J.length>0)Z.push(`Variation direction: ${J}.`);return Z.join(` +${J}`))throw new F0("tool_version",`Expected VTracer ${MZ}.`);let Y=await ex($,zX,F,"tool_integrity");if(Y!==Q||Z!==void 0&&Y!==Z)throw new F0("tool_integrity","The private VTracer executable changed during inspection.",{actual:Y,expected:Z??Q});return{path:$,sha256:Y,source:_,version:MZ}}async function tx($,_){try{return await ex($,zX,_,"tool_integrity")}catch(F){if(F instanceof F0&&F.code==="timeout")throw F;if(Jl0(F,"ENOENT"))return;return}}async function _l0($){try{await uA($,{force:!0})}catch(_){throw new F0("tool_integrity","Could not remove an invalid cached VTracer binary.",{},{cause:_})}}async function ex($,_,F,Q){let Z;try{F.assert("VTracer hash");let J=await O60($);F.assert("VTracer hash"),Z=await ax(J,L60());let X=await Z.stat();if(!X.isFile()||X.size<1||X.size>_)throw new F0(Q,"VTracer must be a non-empty regular file within its size limit.",{bytes:X.size,maximumBytes:_});let Y=j60("sha256"),H=Buffer.allocUnsafe(Math.min(G60,_+1)),K=0;while(!0){F.assert("VTracer hash");let j=Math.min(H.byteLength,_-K+1),{bytesRead:V}=await Z.read(H,0,j,null);if(V===0)break;if(K+=V,K>_)throw new F0(Q,"VTracer grew beyond its executable size limit while being hashed.",{bytes:K,maximumBytes:_});Y.update(H.subarray(0,V))}return F.assert("VTracer hash"),Y.digest("hex")}catch(J){if(J instanceof F0)throw J;throw new F0(Q,"VTracer executable could not be read safely.",{},{cause:J})}finally{await Z?.close().catch(()=>{return})}}async function Fl0($,_,F,Q){let Z=j60("sha256"),J=Buffer.allocUnsafe(Math.min(G60,F+1)),X=0;while(!0){Q.assert("VTracer private copy");let Y=Math.min(J.byteLength,F-X+1),{bytesRead:H}=await $.read(J,0,Y,null);if(H===0)break;if(X+=H,X>F)throw new F0("tool_integrity","VTracer grew beyond its executable size limit while being copied.",{bytes:X,maximumBytes:F});Z.update(J.subarray(0,H));let K=0;while(KzX)throw new F0("tool_version",`VTracer must be a non-empty regular file: ${_}`,{bytes:$.size,maximumBytes:zX})}async function Zl0($,_,F){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),_.remainingMs());try{let J=await fetch($,{headers:{"user-agent":"hraness-slopcamera-vectorizer"},redirect:"follow",signal:Q.signal});if(!J.ok||J.body===null)throw new F0("tool_download",`Could not download VTracer: ${J.status} ${J.statusText}`);let X=Number.parseInt(J.headers.get("content-length")??"",10);if(Number.isFinite(X)&&X>F)throw new F0("tool_download","VTracer archive exceeds its download limit.");let Y=[],H=J.body.getReader(),K=0;while(!0){_.assert("VTracer download");let{done:j,value:V}=await H.read();if(j)break;if(K+=V.byteLength,K>F)throw await H.cancel(),new F0("tool_download","VTracer archive exceeds its download limit.");Y.push(V)}return Uint8Array.from(Buffer.concat(Y,K))}catch(J){if(J instanceof F0)throw J;if(Q.signal.aborted)throw new F0("timeout","VTracer download exceeded the conversion time limit.");throw new F0("tool_download","Could not download VTracer.",{},{cause:J})}finally{clearTimeout(Z)}}function Jl0($,_){return $ instanceof Error&&"code"in $&&$.code===_}function L60(){if(process.platform==="win32")return hA.O_RDONLY;return hA.O_RDONLY|hA.O_NONBLOCK|hA.O_NOFOLLOW}var MZ="0.6.4",QD=($)=>Object.freeze($),iu0,au0=4194304,zX=16777216,G60=65536;var C60=Y_(()=>{H60();FD();lV();k6();iu0=Object.freeze({"darwin-arm64":QD({archiveSha256:"4a597fd2df8b961d60620df40a7436109427d86e5c028758e6e8796b02d3d996",binarySha256:"77e495bbe212448240387fba3b6d8bc62ba20ecfb6f3c22967e51600f1cc6e66",format:"tar.gz",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-aarch64-apple-darwin.tar.gz`}),"darwin-x64":QD({archiveSha256:"f0d755292c2602d772d63d658a3498b23eca8b5620d4b92a991bd035d5abed16",binarySha256:"0f9f88f989b757e27973a5c4b42665153070183d0787656ee8af2249ab326b78",format:"tar.gz",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-x86_64-apple-darwin.tar.gz`}),"linux-arm64":QD({archiveSha256:"cbd05ad4f491d12dd139ada61485ca1d24db9f981cbe1658632a083cd0ac1a71",binarySha256:"a4b33b6c4066a6b9187802c6efc8b89e211318e12a17164b9d1dd1f29ac5e502",format:"tar.gz",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-aarch64-unknown-linux-musl.tar.gz`}),"linux-x64":QD({archiveSha256:"9290ba0c90e224d6d212836dff5491407c1718bcb72f80b2b5a4a01816df5e40",binarySha256:"6f31499257076bd94de3e976844cf7ca5643f1e194a2bf0599b13f3719452aec",format:"tar.gz",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-x86_64-unknown-linux-musl.tar.gz`}),"win32-x64":QD({archiveSha256:"6b5bc17a6b017129ee40461df254f65d16f3b494c001a8541d41861066b716bf",binarySha256:"4ad8d35e566cd15caf582063b8349bd082b8fa2bd461e99d116fc63ad8fdeca0",format:"zip",url:`https://github.com/visioncortex/vtracer/releases/download/${MZ}/vtracer-x86_64-pc-windows-msvc.zip`})})});var UX=1,DK,ZD;var $h=Y_(()=>{uV();DK=Math.ceil(M6.maxInputBytes/3)*4+524288,ZD=M6.maxOutputBytes*2+524288});import{fileURLToPath as Xl0}from"url";import{mkdtemp as Yl0,rm as Hl0}from"fs/promises";import{tmpdir as Kl0}from"os";import{dirname as B60,join as _h}from"path";async function U60($,_){let F=performance.now(),Q=mV(_.limits);if(process.platform==="win32")throw new F0("tool_platform","Bounded VTracer streaming is unavailable on Windows.",{platform:process.platform});let Z=Nl0($,Q.maxInputBytes),J=await Yl0(_h(Kl0(),"slopcamera-vectorize-")),X;try{X=await Vl0(Z,_,Q,F,J)}finally{await Wl0(J)}if(performance.now()-F>=Q.maxDurationMs)throw new F0("timeout","Vectorization exceeded the conversion time limit during cleanup.");return X}async function Vl0($,_,F,Q,Z){let J=F.maxDurationMs-(performance.now()-Q);if(J<=lA+z60)throw new F0("timeout","Vectorization has no remaining budget for isolated worker execution.");let X=Math.floor(J-lA-z60),Y=wl0(_.inheritedFileDescriptors),H=Y.map((G,D)=>D+3),K={input:$,options:Gl0(_,X,H),protocol:UX,temporaryRoot:Z},j=Buffer.from(JSON.stringify(K));if(j.byteLength>DK)throw new F0("input_limit","The vectorization worker request exceeds its IPC limit.",{bytes:j.byteLength,maximumBytes:DK});let V=F.maxDurationMs-(performance.now()-Q);if(V<=lA)throw new F0("timeout","Vectorization has no remaining budget for isolated worker startup and cleanup.");let{stdout:O}=await gA([process.execPath,Dl0()],Math.floor(V-lA),"trace_failed",{...Y.length===0?{}:{inheritedFileDescriptors:Y},maxStdoutBytes:ZD,stdin:j});if(performance.now()-Q>=F.maxDurationMs)throw new F0("timeout","Vectorization exceeded the conversion time limit.");let W=Ll0(O);if(!W.ok)throw new F0(W.error.code,W.error.message,W.error.details);if(Cl0(W.result,F.maxOutputBytes),performance.now()-Q>=F.maxDurationMs)throw new F0("timeout","Vectorization exceeded the conversion time limit.");return W.result}async function Wl0($){try{await Hl0($,{force:!0,recursive:!0})}catch(_){throw new F0("trace_failed","The isolated vectorization directory could not be removed.",{temporaryRoot:$},{cause:_})}}function Nl0($,_){return typeof $==="string"?{kind:"path",value:$}:Ol0($,_)}function Ol0($,_){let F=$ instanceof ArrayBuffer?new Uint8Array($):$;if(F.byteLength<1)throw new F0("invalid_input","Raster input is empty.");if(F.byteLength>_)throw new F0("input_limit",`Raster input exceeds the ${_}-byte limit.`,{bytes:F.byteLength,maximumBytes:_});return{kind:"bytes",value:Buffer.from(F.buffer,F.byteOffset,F.byteLength).toString("base64")}}function Gl0($,_,F){return{...$.alphaCutoff===void 0?{}:{alphaCutoff:$.alphaCutoff},...$.cacheDirectory===void 0?{}:{cacheDirectory:$.cacheDirectory},...$.duotone===void 0?{}:{duotone:[$.duotone[0],$.duotone[1]]},...F.length===0?{}:{inheritedFileDescriptors:F},limits:{...$.limits,maxDurationMs:_},...$.outputPath===void 0?{}:{outputPath:$.outputPath}}}function wl0($){let _=$??[];if(_.length>16||_.some((F,Q)=>!Number.isSafeInteger(F)||F<0||F>2147483647||_.indexOf(F)!==Q))throw new F0("invalid_input","Inherited vectorizer descriptors must be unique bounded integers.");return Object.freeze([..._])}function Dl0(){let $=Xl0(import.meta.url);return $.endsWith(".ts")?_h(B60($),"worker.ts"):_h(B60($),"vectorize","worker.js")}function Ll0($){let _;try{_=JSON.parse($)}catch(F){throw new F0("trace_failed","The vectorization worker returned malformed output.",{},{cause:F})}if(!JD(_)||_.protocol!==UX)throw new F0("trace_failed","The vectorization worker returned an incompatible response.");if(_.ok===!0&&Bl0(_.result))return _;if(_.ok===!1&&JD(_.error)&&typeof _.error.code==="string"&&jl0.has(_.error.code)&&typeof _.error.message==="string"&&JD(_.error.details))return _;throw new F0("trace_failed","The vectorization worker returned an invalid response.")}function Cl0($,_){let F=Buffer.byteLength($.svg);if(F<1||F>_||$.receipt.bytes!==F||$.receipt.svgSha256.length!==64)throw new F0("trace_failed","The vectorization worker response violates its output contract.",{bytes:F,maximumOutputBytes:_})}function Bl0($){if(!JD($)||$.outputPath!==null&&typeof $.outputPath!=="string"||typeof $.svg!=="string"||!JD($.receipt))return!1;let _=$.receipt.profile;return typeof $.receipt.bytes==="number"&&typeof $.receipt.svgSha256==="string"&&typeof _==="string"&&Sx.includes(_)}function JD($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var jl0,lA=250,z60=100;var k60=Y_(()=>{FD();uV();$h();k6();jl0=new Set(["input_limit","invalid_input","output_limit","quality_limit","timeout","tool_download","tool_integrity","tool_platform","tool_version","trace_failed","unsafe_svg"])});import{randomUUID as zl0}from"crypto";import{mkdir as Ul0,rename as kl0,rm as Ml0,writeFile as Jh}from"fs/promises";import{dirname as Al0,join as M60,resolve as Rl0}from"path";function EF($,_={}){return U60($,_)}async function A60($,_={},F){let Q=mV(_.limits),Z=new tw(Q.maxDurationMs),J=_.alphaCutoff??Tl0;if(!Number.isInteger(J)||J<1||J>64)throw new F0("invalid_input","alphaCutoff must be an integer from 1 through 64.");let X=_.duotone===void 0?void 0:[R_(_.duotone[0]),R_(_.duotone[1])],Y=await IA($,Q,Z);if(process.platform==="win32")throw new F0("tool_platform","Bounded VTracer streaming is unavailable on Windows.",{platform:process.platform});let H=await D60(Z,F,_.cacheDirectory),K=[],j=[],V=Pl0(Y.pixels,J);for(let U of V){Z.assert(`${U.name} trace`);let k=M60(F,`${U.name}.png`);await Jh(k,await $D(U.pixels,Y.width,Y.height));let A=await Qh(Y,U,Fh[0],k,H,F,Q,Z,K);if(A!==void 0)j.push(A);if(A!==void 0&&Sl0(A.quality))continue;let q=await Qh(Y,U,Fh[1],k,H,F,Q,Z,K);if(q!==void 0)j.push(q);if([A,q].some((M)=>M!==void 0&&Zh(M.quality)))continue;let E=await Qh(Y,U,Fh[2],k,H,F,Q,Z,K);if(E!==void 0)j.push(E)}let O=[...j].sort(fl0)[0];if(O!==void 0&&I_0(Y.pixels)&&O.quality.alphaRmse>0.06){let U=await bl0(Y,O,H,F,Q,Z,K);if(U!==void 0)j.push(U)}let W=j.filter((U)=>U.bytes<=Q.maxOutputBytes&&U.pathCount<=Q.maxPaths&&Zh(U.quality));if(W.length===0)throw new F0("quality_limit","No adaptive vector candidate passed the fidelity and output gates.",{candidates:j.map(gl0),errors:K});let G=yl0(W),D=X===void 0?void 0:{model:v_0(Y.pixels),palette:X},w=G.maskPaths===void 0?nx(G.artworkPaths,Y.width,Y.height,D):rx(G.artworkPaths,G.maskPaths,Y.width,Y.height,D);vA(w);let L=Buffer.byteLength(w),C=J60(w);if(L>Q.maxOutputBytes||C>Q.maxPaths)throw new F0("output_limit",`Canonical SVG exceeds ${Q.maxOutputBytes} bytes or ${Q.maxPaths} paths.`,{bytes:L,pathCount:C});Z.assert("output publication");let B=_.outputPath===void 0?null:await vl0(_.outputPath,w),z=l_0();return{outputPath:B,receipt:{alphaCutoff:G.alphaCutoff,bytes:L,candidatesEvaluated:j.length,format:Y.format,height:Y.height,inputBytes:Y.inputBytes,outputMode:D===void 0?"color":"duotone",pathCount:C,profile:G.profile,provenance:{arch:process.arch,platform:process.platform,sharp:z.sharp,sharpVersions:z.sharpVersions,vips:z.vips,vtracerSha256:H.sha256,vtracerSource:H.source,vtracerVersion:H.version},quality:q60(G.quality),receiptVersion:1,representation:G.representation,sourceSha256:Y.sourceSha256,svgSha256:UZ(w),width:Y.width},svg:w}}function Pl0($,_){let F=fx($,_),Q=[];if(Il0(F))Q.push({alphaCutoff:_,name:`alpha-${_}`,pixels:F});if(_>1&&(Q.length===0||P_0($,_)>=ql0))Q.push({alphaCutoff:1,name:"alpha-1",pixels:fx($,1)});if(Q.length===0)throw new F0("invalid_input","Alpha sanitation removed every visible pixel.");return Q}function Il0($){for(let _=3;_<$.length;_+=4)if($[_]>0)return!0;return!1}async function Qh($,_,F,Q,Z,J,X,Y,H){try{let K=await T60(Z,Q,F.args,J,X.maxOutputBytes,Y);Y.assert(`${F.name} trace`);let j=sx(K,$.width,$.height,X.maxPaths),V=Buffer.byteLength(j.svg),O=j.paths.length;if(V>X.maxOutputBytes||O>X.maxPaths)throw new F0("output_limit",`${F.name} exceeds vector output limits.`);let W=await R60(j.svg,$,X.maxDecodedPixels,Y);return{alphaCutoff:_.alphaCutoff,artworkPaths:j.paths,bytes:V,pathCount:O,profile:F.name,quality:W,representation:"color-paths",svg:j.svg}}catch(K){if(K instanceof F0&&K.code==="timeout")throw K;H.push(`${_.name}/${F.name}: ${K instanceof Error?K.message:String(K)}`);return}}async function bl0($,_,F,Q,Z,J,X){try{let Y=E_0($.pixels),H=M60(Q,"alpha-plane.png");await Jh(H,await $D(Y,$.width,$.height));let K=await T60(F,H,El0,Q,Z.maxOutputBytes,J),j=sx(K,$.width,$.height,Z.maxPaths),V=_.artworkPaths.length+j.paths.length;if(V>Z.maxPaths)throw new F0("output_limit","Alpha-masked output exceeds the path limit.");let O=rx(_.artworkPaths,j.paths,$.width,$.height),W=Buffer.byteLength(O);if(W>Z.maxOutputBytes)throw new F0("output_limit","Alpha-masked output exceeds the byte limit.");let G=await R60(O,$,Z.maxDecodedPixels,J);return{alphaCutoff:_.alphaCutoff,artworkPaths:_.artworkPaths,bytes:W,maskPaths:j.paths,pathCount:V,profile:_.profile,quality:G,representation:"alpha-mask",svg:O}}catch(Y){if(Y instanceof F0&&Y.code==="timeout")throw Y;X.push(`alpha-mask: ${Y instanceof Error?Y.message:String(Y)}`);return}}async function R60($,_,F,Q){let Z=await u_0($,_.scoreWidth,_.scoreHeight,F);Q.assert("quality measurement");let J=y_0(_.scorePixels,Z,_.scoreWidth,_.scoreHeight,1);return{alphaRmse:S_0(_.scorePixels,Z),colorRmse:b_0(_.scorePixels,Z),outsideAlphaRatio:J.outsideAlphaRatio,sampleHeight:_.scoreHeight,sampleWidth:_.scoreWidth,supportRecall:J.supportRecall}}async function T60($,_,F,Q,Z,J){let{output:X}=await _60((Y)=>[$.path,"--input",_,"--output",Y,...F],J.remainingMs(),"trace_failed",{maxOutputBytes:Z,temporaryRoot:Q});if(X.length===0)throw new F0("trace_failed","VTracer did not emit an SVG.");return X}function Sl0($){return Zh($)&&$.colorRmse<=0.12&&$.alphaRmse<=0.18&&$.outsideAlphaRatio<=0.02&&$.supportRecall>=0.97}function Zh($){return $.colorRmse<=0.3&&$.alphaRmse<=0.3&&$.outsideAlphaRatio<=0.15&&$.supportRecall>=0.8}function fl0($,_){return $.quality.colorRmse-_.quality.colorRmse||$.quality.alphaRmse-_.quality.alphaRmse||$.bytes-_.bytes||$.pathCount-_.pathCount||$.profile.localeCompare(_.profile)}function yl0($){let _=Math.min(...$.map(({quality:Q})=>Q.colorRmse));return[...$.filter(({quality:Q})=>Q.colorRmse<=_+0.005)].sort((Q,Z)=>Q.bytes-Z.bytes||Q.pathCount-Z.pathCount||Q.quality.alphaRmse-Z.quality.alphaRmse||Q.profile.localeCompare(Z.profile)||Q.representation.localeCompare(Z.representation))[0]}function q60($){let _=(F)=>Number(F.toFixed(8));return{alphaRmse:_($.alphaRmse),colorRmse:_($.colorRmse),outsideAlphaRatio:_($.outsideAlphaRatio),sampleHeight:$.sampleHeight,sampleWidth:$.sampleWidth,supportRecall:_($.supportRecall)}}function gl0($){return{alphaCutoff:$.alphaCutoff,bytes:$.bytes,pathCount:$.pathCount,profile:$.profile,quality:q60($.quality),representation:$.representation}}async function vl0($,_){let F=Rl0($);await Ul0(Al0(F),{recursive:!0});let Q=`${F}.${zl0()}.tmp`;try{await Jh(Q,_,{flag:"wx"}),await kl0(Q,F)}catch(Z){throw await Ml0(Q,{force:!0}),new F0("output_limit",`Could not atomically write ${F}.`,{},{cause:Z})}return F}var Tl0=8,ql0=0.002,Fh,El0;var XD=Y_(()=>{FD();uV();lV();bA();X60();C60();k60();k6();Fh=[{args:["--colormode","color","--hierarchical","stacked","--mode","spline","--filter_speckle","0","--color_precision","8","--gradient_step","4","--segment_length","4.5","--path_precision","4"],name:"balanced"},{args:["--colormode","color","--hierarchical","stacked","--mode","spline","--filter_speckle","0","--color_precision","8","--gradient_step","2","--segment_length","3.5","--path_precision","5"],name:"detailed"},{args:["--preset","photo","--hierarchical","stacked","--filter_speckle","0"],name:"photo"}],El0=["--colormode","color","--hierarchical","cutout","--mode","spline","--filter_speckle","0","--color_precision","8","--gradient_step","2","--segment_length","3.5","--path_precision","5","--corner_threshold","30","--splice_threshold","20"]});var N91={};import{lstat as F91,realpath as J70}from"fs/promises";import{tmpdir as Q91}from"os";import{basename as Z91,dirname as J91}from"path";async function Y91(){let $;try{m_0();let F=await H91(),Q=K91(F),Z=j91(Q.input),J=await V91(Q.temporaryRoot),X=await e_0(Q.options.inheritedFileDescriptors,async()=>await A60(Z,Q.options,J));$={ok:!0,protocol:UX,result:X}}catch(F){$={error:W91(F),ok:!1,protocol:UX}}let _=JSON.stringify($);if(Buffer.byteLength(_)>ZD)_=JSON.stringify({error:{code:"output_limit",details:{maximumBytes:ZD},message:"The vectorization worker response exceeds its IPC limit."},ok:!1,protocol:UX});await Bun.write(Bun.stdout,_)}async function H91(){let $=Bun.stdin.stream().getReader(),_=[],F=0;try{while(!0){let{done:Q,value:Z}=await $.read();if(Q)break;if(F+=Z.byteLength,F>DK)throw await $.cancel(),new F0("input_limit","The vectorization worker request exceeds its IPC limit.",{bytes:F,maximumBytes:DK});_.push(Z)}}finally{$.releaseLock()}return Buffer.concat(_,F).toString("utf8")}function K91($){let _;try{_=JSON.parse($)}catch(F){throw new F0("invalid_input","The vectorization worker request is malformed.",{},{cause:F})}if(!od(_)||_.protocol!==UX||!od(_.input)||!od(_.options)||typeof _.temporaryRoot!=="string"||_.temporaryRoot.length===0||typeof _.input.kind!=="string"||typeof _.input.value!=="string"||!["bytes","path"].includes(_.input.kind))throw new F0("invalid_input","The vectorization worker request is invalid.");return _}function j91($){if($.kind==="path")return $.value;if($.value.length>Math.ceil(DK/3)*4||$.value.length%4!==0)throw new F0("input_limit","Encoded raster input exceeds its IPC limit.");let _=Buffer.from($.value,"base64");if(_.toString("base64")!==$.value)throw new F0("invalid_input","Encoded raster input is not canonical base64.");return _}async function V91($){let _,F;try{let Q=await Promise.all([J70($),J70(Q91())]);_=Q[0],F=Q[1];let Z=await F91($);if(!Z.isDirectory()||Z.isSymbolicLink()||J91(_)!==F||!/^slopcamera-vectorize-[A-Za-z0-9_-]{6,}$/u.test(Z91(_)))throw new F0("invalid_input","The supervisor temporary directory is invalid.")}catch(Q){if(Q instanceof F0)throw Q;throw new F0("invalid_input","The supervisor temporary directory could not be verified.",{},{cause:Q})}return _}function W91($){let _=$ instanceof F0&&X91.has($.code)?$.code:"trace_failed",F=$ instanceof Error?$.message:"The vectorization worker failed.",Q=$ instanceof F0&&Buffer.byteLength(JSON.stringify($.details))<=65536?$.details:{};return{code:_,details:Q,message:F}}function od($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var X91;var X70=Y_(async()=>{$h();k6();FD();XD();bA();X91=new Set(["input_limit","invalid_input","output_limit","quality_limit","timeout","tool_download","tool_integrity","tool_platform","tool_version","trace_failed","unsafe_svg"]);$60();await Y91()});import{maybeShowSupportInvitation as N70,runSupportCommand as O70}from"@hraness/support-foundation/node";var $c={id:"slopcamera",name:"Slopcamera",valueProposition:"Support ongoing development of local visual tools for agents.",updates:!1};function _c(){let $={...process.env};return process.env.HRANESS_SUPPORT_AUDIENCE="off",process.env.HRANESS_SUPPORT_EMAIL="off",$}async function Fc($,_={}){let F=await O70($c,$,{command:["slopcamera"],..._,gitEmail:!1});if(F.stdout!=="")process.stdout.write(F.stdout);if(F.stderr!=="")process.stderr.write(F.stderr);return F.exitCode}async function Qc($={}){try{await N70($c,{usefulResult:!0,command:["slopcamera"],...$,gitEmail:!1})}catch{}}class l0 extends Error{code;details;constructor($,_,F){super(_);this.name="SlopcameraCodeError",this.code=$,this.details=F===void 0?void 0:Object.freeze({...F})}}function YE($){return $ instanceof Error?$.message:String($)}function Zc($){if($ instanceof l0)return $;return new l0("internal",YE($))}function HE($,_=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(_)||_<0)return;let F=2;if(F>_)return;for(let Q=0;Q<$.length;Q+=1){let Z=$.charCodeAt(Q),J;if(Z===34||Z===92||Z===8||Z===9||Z===10||Z===12||Z===13)J=2;else if(Z<32)J=6;else if(Z<128)J=1;else if(Z<2048)J=2;else if(Z>=55296&&Z<=56319){let X=$.charCodeAt(Q+1);if(X>=56320&&X<=57343)J=4,Q+=1;else J=6}else if(Z>=56320&&Z<=57343)J=6;else J=3;if(J>_-F)return;F+=J}return F}function Jc($,_=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(_)||_<0)return;let F=0;for(let Q=0;Q<$.length;Q+=1){let Z=$.charCodeAt(Q),J;if(Z<128)J=1;else if(Z<2048)J=2;else if(Z>=55296&&Z<=56319){let X=$.charCodeAt(Q+1);if(X>=56320&&X<=57343)J=4,Q+=1;else J=3}else J=3;if(J>_-F)return;F+=J}return F}import{sha256 as G70}from"@noble/hashes/sha2.js";import{bytesToHex as w70}from"@noble/hashes/utils.js";var D70=new TextEncoder;function M8(){if(typeof Bun<"u"){let _=new Bun.CryptoHasher("sha256");return{digestHex:()=>_.digest("hex"),update:(F)=>{_.update(F)}}}let $=G70.create();return{digestHex:()=>w70($.digest()),update:(_)=>{$.update(typeof _==="string"?D70.encode(_):_)}}}function X0($){let _=M8();return _.update($),_.digestHex()}var L70=128,C70=1e6,B70=65536;function o2($,_){throw new l0("invalid-data",$,_)}function KE($,_){if(!Number.isSafeInteger($)||$<1)return o2(`${_} must be a positive safe integer.`);return $}function _C($){return Object.getOwnPropertySymbols($).some((_)=>Reflect.get($,_)?.enumerable===!0)}function jE($,_,F){if($===void 0){F(_);return}if(Array.isArray($.target))$.target[$.key]=_;else Object.defineProperty($.target,$.key,{configurable:!0,enumerable:!0,value:_,writable:!0})}function VE($){if(typeof $==="number"){if(!Number.isFinite($))return o2("JSON snapshots do not support non-finite numbers.");return JSON.stringify(Object.is($,-0)?0:$)}return JSON.stringify($)}function FC($,_,F,Q={},Z){let J=KE(_,"JSON snapshot byte limit"),X=KE(Q.maximumDepth??L70,"JSON snapshot depth limit"),Y=KE(Q.maximumValues??C70,"JSON snapshot value limit"),H=new WeakSet,K=Z.hash?M8():void 0,j=Z.hashPrefix??"",V=()=>{if(K===void 0||j.length===0)return;K.update(j),j=""},O=Z.captureText,W=[],G="",D=[{depth:0,kind:"visit",value:$}],w=0,L=1,C,B=(k,A=k.length)=>{if(A>J-w)return o2(`${F} contains more than ${String(J)} bytes.`,{actualLowerBound:w+A,maximumBytes:J});if(K!==void 0){if(j+=k,j.length>=B70)V()}if(O){if(G+=k,G.length>=65536)W.push(G),G=""}w+=A},z=(k)=>{if(k>Y-L)return o2(`${F} contains more than ${String(Y)} JSON values.`,{actualLowerBound:L+k,maximumValues:Y});L+=k},U=(k)=>{C=k};try{while(D.length>0){let k=D.pop();if(k===void 0)break;if(k.kind==="array"){if(k.index===k.values){if(B("]"),H.delete(k.source),k.clone!==void 0)Object.freeze(k.clone);continue}if(k.index>0)B(",");let I=k.descriptors[String(k.index)];if(I===void 0||I.get!==void 0||I.set!==void 0)return o2(`${F} arrays must contain plain data elements.`);D.push({...k,index:k.index+1}),D.push({...k.clone===void 0?{}:{assignment:{key:k.index,target:k.clone}},depth:k.depth+1,kind:"visit",value:I.value});continue}if(k.kind==="object"){if(k.index===k.keys.length){if(B("}"),H.delete(k.source),k.clone!==void 0)Object.freeze(k.clone);continue}let I=k.keys[k.index];if(I===void 0)return o2(`${F} lost an object key during traversal.`);if(k.index>0)B(",");let g=HE(I,J-w);if(g===void 0)return o2(`${F} contains more than ${String(J)} bytes.`,{actualLowerBound:J+1,maximumBytes:J});B(VE(I),g),B(":");let b=k.descriptors[I];if(b===void 0||b.get!==void 0||b.set!==void 0)return o2(`${F} properties must be plain data properties.`);D.push({...k,index:k.index+1}),D.push({...k.clone===void 0?{}:{assignment:{key:I,target:k.clone}},depth:k.depth+1,kind:"visit",value:b.value});continue}if(k.depth>X)return o2(`${F} nesting exceeds ${String(X)} levels.`,{actual:k.depth,maximumDepth:X});let A=k.value;if(A===null||typeof A==="boolean"||typeof A==="number"||typeof A==="string"){let I=typeof A==="number"&&Object.is(A,-0)?0:A;if(typeof A==="string"){let g=HE(A,J-w);if(g===void 0)return o2(`${F} contains more than ${String(J)} bytes.`,{actualLowerBound:J+1,maximumBytes:J});B(VE(A),g)}else B(VE(A));if(Z.captureValue)jE(k.assignment,I,U);continue}if(typeof A!=="object")return o2(`${F} does not support ${typeof A} values.`);if(H.has(A))return o2(`${F} does not support cyclic values.`);let q=Array.isArray(A)?A.length:void 0;if(q!==void 0&&q>Y-L)return o2(`${F} contains more than ${String(Y)} JSON values.`,{actualLowerBound:L+q,maximumValues:Y});if(q!==void 0){let I=2+Math.max(0,q-1);if(I>J-w)return o2(`${F} contains more than ${String(J)} bytes.`,{actualLowerBound:w+I,maximumBytes:J})}if(H.add(A),Array.isArray(A)){let I=q;if(I===void 0)return o2(`${F} lost an array length during traversal.`);L+=I;let g=Object.getOwnPropertyDescriptors(A);if(!Z.ignoreNonIndexArrayProperties){if(_C(g))return o2(`${F} cannot contain enumerable symbol properties.`);let y=Object.keys(g).filter((r)=>g[r]?.enumerable===!0);if(y.length!==I||y.some((r,h)=>r!==String(h)))return o2(`${F} arrays must be dense and cannot have named properties.`)}let b=Z.captureValue?[]:void 0;if(b!==void 0)jE(k.assignment,b,U);B("["),D.push({clone:b,depth:k.depth,descriptors:g,index:0,kind:"array",source:A,values:I});continue}let E=Object.getPrototypeOf(A);if(E!==Object.prototype&&E!==null)return o2(`${F} accepts only arrays and plain objects.`);let M=Object.getOwnPropertyDescriptors(A);if(_C(M))return o2(`${F} cannot contain enumerable symbol properties.`);let T=Object.keys(M).filter((I)=>M[I]?.enumerable===!0).sort();z(T.length);let P=Z.captureValue?{}:void 0;if(P!==void 0)jE(k.assignment,P,U);B("{"),D.push({clone:P,depth:k.depth,descriptors:M,index:0,keys:T,kind:"object",source:A})}}catch(k){if(k instanceof l0)throw k;throw new l0("invalid-data",`${F} could not be safely inspected.`,{cause:k instanceof Error?k.message:String(k)})}if(Z.captureValue&&C===void 0)return o2(`${F} did not contain a JSON value.`);if(O&&G.length>0)W.push(G);return V(),Object.freeze({bytes:w,...O?{canonicalText:W.join("")}:{},...K===void 0?{}:{sha256:K.digestHex()},...Z.captureValue?{value:C}:{},values:L})}function a0($,_,F,Q={}){let Z=FC($,_,F,Q,{captureText:!1,captureValue:!0,hash:!1,ignoreNonIndexArrayProperties:!1});if(Z.value===void 0)return o2(`${F} did not produce a complete JSON value snapshot.`);return Z}function t4($,_,F,Q={}){let Z=FC($,_,F,Q,{captureText:Q.captureCanonicalText===!0,captureValue:!0,hash:!0,ignoreNonIndexArrayProperties:!1});if(Z.sha256===void 0||Z.value===void 0)return o2(`${F} did not produce a complete JSON snapshot.`);return Z}function Xc($,_,F,Q={}){let Z=FC($,_,F,Q,{captureText:!0,captureValue:!1,hash:!1,ignoreNonIndexArrayProperties:!0});if(Z.canonicalText===void 0)return o2(`${F} did not produce canonical JSON text.`);return Z.canonicalText}function WE($,_,F,Q={},Z){let J=FC($,_,F,Q,{captureText:!1,captureValue:!1,hash:!0,ignoreNonIndexArrayProperties:!0,...Z===void 0?{}:{hashPrefix:Z}});if(J.sha256===void 0)return o2(`${F} did not produce a canonical JSON identity.`);return Object.freeze({bytes:J.bytes,sha256:J.sha256})}function Yc($,_,F,Q={},Z){return WE($,_,F,Q,Z).sha256}function $0($){let _=new WeakSet,F=new WeakSet,Q=[{exiting:!1,value:$}];try{while(Q.length>0){let Z=Q.pop();if(Z===void 0)break;let J=Z.value;if(J===null||typeof J==="boolean"||typeof J==="string")continue;if(typeof J==="number"){if(!Number.isFinite(J))return o2("JSON snapshots do not support non-finite numbers.");continue}if(typeof J!=="object")return o2(`JSON snapshots do not support ${typeof J} values.`);if(Z.exiting){_.delete(J),F.add(J),Object.freeze(J);continue}if(F.has(J))continue;if(_.has(J))return o2("JSON snapshots do not support cycles.");if(_.add(J),Q.push({exiting:!0,value:J}),Array.isArray(J)){let K=J.length,j=Object.getOwnPropertyDescriptors(J);if(_C(j))return o2("JSON snapshots cannot contain enumerable symbol properties.");let V=Object.keys(j).filter((O)=>j[O]?.enumerable===!0);if(V.length!==K||V.some((O,W)=>O!==String(W)))return o2("JSON snapshot arrays must be dense and cannot have named properties.");for(let O=K-1;O>=0;O-=1){let W=j[String(O)];if(W===void 0||W.get!==void 0||W.set!==void 0)return o2("JSON snapshot arrays must contain plain data elements.");Q.push({exiting:!1,value:W.value})}continue}let X=Object.getPrototypeOf(J);if(X!==Object.prototype&&X!==null)return o2("JSON snapshots accept only arrays and plain objects.");let Y=Object.getOwnPropertyDescriptors(J);if(_C(Y))return o2("JSON snapshots cannot contain enumerable symbol properties.");let H=Object.keys(Y).filter((K)=>Y[K]?.enumerable===!0);for(let K=H.length-1;K>=0;K-=1){let j=H[K];if(j===void 0)continue;let V=Y[j];if(V===void 0||V.get!==void 0||V.set!==void 0)return o2("JSON snapshot properties must be plain data properties.");if(V.value===void 0)return o2(`JSON snapshot property ${j} is undefined.`);Q.push({exiting:!1,value:V.value})}}}catch(Z){if(Z instanceof l0)throw Z;throw new l0("invalid-data","JSON snapshot could not be safely inspected.",{cause:Z instanceof Error?Z.message:String(Z)})}return $}var{MAX_SAFE_INTEGER:QC,MAX_SAFE_INTEGER:z70,MAX_SAFE_INTEGER:U70}=Number;function NE($,_){return $<_?-1:$>_?1:0}function OE($){return{maximumDepth:$?.maximumDepth??z70,maximumValues:$?.maximumValues??U70}}function Hc($,_){return Xc($,_.maximumBytes,_.name??"Canonical JSON",OE(_))}function $9($,_,F){return Yc($,_.maximumBytes,_.name??"Canonical JSON",OE(_),F)}function ZC($,_,F){return WE($,_.maximumBytes,_.name??"Canonical JSON",OE(_),F)}function R($){return Hc($,{maximumBytes:QC})}function m($){return $9($,{maximumBytes:QC})}function zN($,_){return $9(_,{maximumBytes:QC},$)}function J3($,_){return ZC($,{maximumBytes:QC},_)}import{z as EE}from"zod";import{z as M0}from"zod";var kN="slopcamera-workflow-graph-v2",MN="slopcamera-workflow-ref-v1",DY="slopcamera-workflow-graph-abi-v2",AN="slopcamera-requirement-envelope-v2",GE=1,HC="slopcamera-workflow-compilation-v1",k70="studio-workflow-graph-v2",M70="studio-workflow-ref-v1",Kc="studio-workflow-graph-abi-v2",A70="studio-requirement-envelope-v2",A8=4096,UN=4096,lZ=32,LY=4096,jc=2097152,Vc=2097152,Wc=300000,R70=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u,T70=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/u,q70=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\/[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)*$/u,Nc=/^[A-Za-z0-9][A-Za-z0-9._:/@-]*$/u,E70=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/u,P70=/^[a-f0-9]{64}$/u,wE=M0.string().min(1).max(128).regex(R70),KC=M0.string().min(1).max(64).regex(T70),m4=M0.string().min(1).max(255).regex(q70),I6=M0.string().min(1).max(192).regex(Nc),jC=M0.string().min(1).max(192).regex(Nc),DE=M0.string().min(3).max(192).regex(E70),W2=M0.string().regex(P70),K$=M0.number().int().positive().max(Number.MAX_SAFE_INTEGER),r5=M0.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),I70=M0.union([M0.string().min(1).max(128),r5]),LE=M0.string().refine(($)=>$!=="__proto__","JSON object keys must not use the reserved __proto__ name."),b70=Symbol("reserved-json-object");function CE($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.hasOwn($,"__proto__")?b70:$}var L1=M0.lazy(()=>M0.preprocess(CE,M0.union([M0.null(),M0.boolean(),M0.number().finite(),M0.string(),M0.array(L1),M0.record(LE,L1)]))),VC=M0.strictObject({$ref:M0.strictObject({nodeKey:m4,path:M0.array(I70).max(lZ).optional(),schemaId:I6}),version:M0.union([M0.literal(MN),M0.literal(M70)])}),S70=M0.lazy(()=>M0.record(LE,BE).superRefine(($,_)=>{if(Object.hasOwn($,"$ref"))_.addIssue({code:"custom",message:"The reserved $ref field must contain a complete versioned workflow reference."})})),BE=M0.lazy(()=>M0.preprocess(CE,M0.union([VC,M0.null(),M0.boolean(),M0.number().finite(),M0.string(),M0.array(BE),S70]))),f70=M0.lazy(()=>M0.record(LE,zE).superRefine(($,_)=>{if(Object.hasOwn($,"$ref"))_.addIssue({code:"custom",message:"The reserved $ref field must contain a complete versioned workflow reference."})})),zE=M0.lazy(()=>M0.preprocess(CE,M0.union([VC,M0.array(zE),f70]))),UE=M0.strictObject({kind:DE,version:K$}),RN=M0.strictObject({bounds:M0.strictObject({maxDurationMs:K$.max(Wc),maxInputBytes:K$.max(jc),maxOutputBytes:K$.max(Vc)}),key:jC,version:M0.literal(GE)}),TN=M0.discriminatedUnion("kind",[M0.strictObject({kind:M0.literal("operation"),operation:UE}),M0.strictObject({compute:RN,kind:M0.literal("compute")})]),WC=M0.strictObject({controlDependencies:M0.array(m4).max(UN).optional(),dependencies:M0.array(m4).max(UN),executor:TN,input:BE,inputSchemaId:I6,key:m4,label:M0.string().min(1).max(160).optional(),outputSchemaId:I6});function M4($){return $.executor.kind==="operation"}function F8($){return $.executor.kind==="compute"}var qN=M0.strictObject({id:wE,inputSchemaId:I6,version:K$}),u_=M0.strictObject({nodes:M0.array(WC).min(1).max(A8),outputs:zE,version:M0.union([M0.literal(kN),M0.literal(k70)]),workflow:qN}),Oc=Object.freeze(["pure","local-read","local-derived-write","project-mutation","paid-cloud","live-control"]),JC=Object.freeze([...Oc,"trusted-code"]),Gc=Object.freeze(["deterministic","verified-receipt","recoverable-transaction","ambiguous-after-dispatch","non-resumable-live"]),XC=Object.freeze([...Gc,"explicit-code-replay"]),X3=Object.freeze(["project-state","recording-metadata","screen-capture","camera","microphone","system-audio","typed-text","window-metadata","local-media","provider-options"]),y70=Object.freeze(["pure","local-artifact","project-transaction","paid-dispatch","live-control"]),dZ=Object.freeze(["cpu","local-io","ffmpeg","vision","whisper","network","paid-call","project-render","project-publication","output-publication","capture-device","browser"]),wc=M0.strictObject({amount:K$,resource:M0.enum(dZ)}),Kj=M0.strictObject({cache:M0.enum(["none","exact-run","content-addressed"]),cancellable:M0.boolean(),effect:M0.enum(Oc),maxDurationMs:K$,maxFanOut:r5,maxInputBytes:r5,maxOutputBytes:r5,preparation:M0.array(M0.enum(X3)).max(X3.length),resources:M0.array(wc).max(dZ.length),resume:M0.enum(Gc)}),Dc=M0.strictObject({cache:M0.literal("exact-run"),cancellable:M0.literal(!0),effect:M0.literal("trusted-code"),maxDurationMs:K$.max(Wc),maxFanOut:M0.literal(0),maxInputBytes:K$.max(jc),maxOutputBytes:K$.max(Vc),preparation:M0.tuple([]),resources:M0.tuple([M0.strictObject({amount:M0.literal(1),resource:M0.literal("cpu")})]),resume:M0.literal("explicit-code-replay")}),jj=M0.union([Kj,Dc]);function Vj($){return Dc.parse({cache:"exact-run",cancellable:!0,effect:"trusted-code",maxDurationMs:$.bounds.maxDurationMs,maxFanOut:0,maxInputBytes:$.bounds.maxInputBytes,maxOutputBytes:$.bounds.maxOutputBytes,preparation:[],resources:[{amount:1,resource:"cpu"}],resume:"explicit-code-replay"})}var Y3=M0.strictObject({inputSchemaId:I6,kind:DE,lifecycle:M0.enum(y70),outputSchemaId:I6,policy:Kj,version:K$}),NC=M0.strictObject({discovery:M0.array(Y3).max(LY),id:I6,projectionSha256:W2,trustedCompute:M0.boolean()}),Wj=M0.strictObject({maxDepth:K$,maxEdges:r5,maxFanOut:r5,maxNodes:K$.max(A8),maxTotalOperationFanOut:r5}),YC=Object.freeze(["dependency-outputs","exact-media-hashes","exact-sensitive-metadata-hashes","prices","project-generations","render-plans"]),g70=M0.strictObject({depth:r5,edges:r5,localMediaUploadNodes:r5,maxDurationMs:r5,maxInputBytes:r5,maxOutputBytes:r5,nodes:r5,paidCallClaims:r5,structuralFanOut:r5,totalOperationFanOut:r5}),EN=M0.strictObject({bounds:g70,computeKeys:M0.array(jC).max(A8),effects:M0.array(M0.enum(JC)).max(JC.length),operationFamilies:M0.array(KC).max(A8),operationKinds:M0.array(DE).max(A8),preparation:M0.array(M0.enum(X3)).max(X3.length),resources:M0.array(wc).max(dZ.length),resumeClasses:M0.array(M0.enum(XC)).max(XC.length),unresolved:M0.array(M0.enum(YC)).max(YC.length),version:M0.union([M0.literal(AN),M0.literal(A70)])}),Lc=M0.strictObject({compilationSha256:W2,envelope:EN,graph:u_,graphSha256:W2,limits:Wj,projection:NC,topologicalWaves:M0.array(M0.array(m4).min(1)).max(A8),version:M0.literal(HC)}),kE=Symbol.for("slopcamera.trusted-compute-definition"),Cc=Symbol.for("studio.trusted-compute-definition"),OC=Symbol.for("slopcamera.workflow-ref");function W5($,_,F){let Q=$.safeParse(_);if(!Q.success)throw new l0("invalid-data",`Invalid ${F}.`,{issues:Q.error.issues.map((Z)=>({code:Z.code,message:Z.message,path:Z.path.map(String)}))});return Q.data}import{z as u1}from"zod";var v70=4096,Bc=32768,Uc=67108864,kc=16777216,Mc=2000000,x70=67108864,E9=u1.string().min(1).max(v70).refine(($)=>!$.includes("\x00"),"Paths must not contain NUL bytes."),wC=u1.string().regex(/^[a-f0-9]{64}$/u),Nj=u1.string().min(1).max(256),zc=u1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),CY=u1.number().int().positive().max(Number.MAX_SAFE_INTEGER);function ME($){return $}var Ac=u1.string().min(3).max(256).regex(/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/iu),h70=u1.strictObject({path:E9}),m70=ME(u1.strictObject({outDirectory:E9.optional(),path:E9,scale:u1.number().finite().positive().max(4).optional()})),u70=ME(u1.strictObject({alphaCutoff:u1.number().int().min(1).max(64).optional(),duotone:u1.tuple([u1.string().regex(/^#[a-f0-9]{3}(?:[a-f0-9]{3})?$/iu),u1.string().regex(/^#[a-f0-9]{3}(?:[a-f0-9]{3})?$/iu)]).optional(),inputPath:E9,outputPath:E9.refine(($)=>$.toLowerCase().endsWith(".svg"),"Vector output paths must end in .svg."),timeoutMs:u1.number().int().min(1).max(300000).optional()})),l70=u1.string().superRefine(($,_)=>{if(Jc($,Bc)===void 0){_.addIssue({code:"custom",message:`Prompts must contain at most ${String(Bc)} UTF-8 bytes.`});return}if($.trim().length===0){_.addIssue({code:"custom",message:"Prompts must not be blank."});return}if(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test($))_.addIssue({code:"custom",message:"Prompts must not contain control characters."})}),d70=ME(u1.strictObject({model:Ac,outputPath:E9.refine(($)=>/\.(?:jpe?g|png|webp)$/iu.test($),"Generated image output paths must end in .png, .jpg, .jpeg, or .webp."),prompt:l70})),Rc=u1.strictObject({code:u1.string().min(1).max(160),message:u1.string().min(1).max(4096),shapeIds:u1.array(u1.string().min(1).max(256)).max(4096)}),c70=u1.strictObject({configPath:u1.null(),findings:u1.array(Rc).max(4096)}),p70=u1.strictObject({darkPng:E9,darkSvg:E9,lightPng:E9,lightSvg:E9,spec:E9,tldr:E9}),s70=u1.strictObject({artifacts:p70,configPath:u1.null(),findings:u1.array(Rc).max(4096)}),n70=u1.strictObject({alphaRmse:u1.number().finite().nonnegative(),colorRmse:u1.number().finite().nonnegative(),outsideAlphaRatio:u1.number().finite().min(0).max(1),sampleHeight:CY,sampleWidth:CY,supportRecall:u1.number().finite().min(0).max(1)}),r70=u1.strictObject({arch:Nj,platform:Nj,sharp:Nj,sharpVersions:u1.record(u1.string().min(1).max(128),Nj),vips:Nj,vtracerSha256:wC,vtracerSource:u1.enum(["official-release","override"]),vtracerVersion:Nj}),o70=u1.strictObject({alphaCutoff:u1.number().int().min(1).max(64),bytes:zc.max(Mc),candidatesEvaluated:CY,format:u1.string().min(1).max(80),height:CY.max(4096),inputBytes:CY.max(kc),outputMode:u1.enum(["color","duotone"]),pathCount:zc.max(12000),profile:u1.enum(["balanced","detailed","photo"]),provenance:r70,quality:n70,receiptVersion:u1.literal(1),representation:u1.enum(["color-paths","alpha-mask"]),sourceSha256:wC,svgSha256:wC,width:CY.max(4096)}),i70=u1.strictObject({outputPath:E9,receipt:o70}),a70=u1.strictObject({bytes:CY.max(Uc),mediaType:u1.enum(["image/jpeg","image/png","image/webp"]),model:Ac,outputPath:E9,provider:u1.literal("vercel-ai-gateway"),requestId:u1.string().min(1).max(256).refine(($)=>!/[\u0000-\u001f\u007f]/u.test($),"Request ids must not contain control characters."),sha256:wC,warnings:u1.array(u1.string().min(1).max(256)).max(100)}),Oj=Object.freeze(["slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.generate","slopcamera.image.vectorize"]);function t70($){let _=Object.freeze([...$.preparation]),F=Object.freeze($.resources.map((Q)=>Object.freeze({...Q})));return Object.freeze({...$,preparation:_,resources:F})}function GC($){return Object.freeze({...$,policy:t70($.policy)})}var cZ=Object.freeze({"slopcamera.diagram.check":GC({inputSchema:h70,inputSchemaId:"slopcamera.operation.diagram.check.input/v2",kind:"slopcamera.diagram.check",lifecycle:"pure",outputSchema:c70,outputSchemaId:"slopcamera.operation.diagram.check.output/v2",policy:{cache:"content-addressed",cancellable:!1,effect:"local-read",maxDurationMs:30000,maxFanOut:0,maxInputBytes:4096,maxOutputBytes:262144,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"}],resume:"deterministic"},version:2}),"slopcamera.diagram.render":GC({inputSchema:m70,inputSchemaId:"slopcamera.operation.diagram.render.input/v2",kind:"slopcamera.diagram.render",lifecycle:"local-artifact",outputSchema:s70,outputSchemaId:"slopcamera.operation.diagram.render.output/v2",policy:{cache:"none",cancellable:!1,effect:"local-derived-write",maxDurationMs:120000,maxFanOut:5,maxInputBytes:8192,maxOutputBytes:5*x70,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"}],resume:"ambiguous-after-dispatch"},version:2}),"slopcamera.image.generate":GC({inputSchema:d70,inputSchemaId:"slopcamera.operation.image.generate.input/v2",kind:"slopcamera.image.generate",lifecycle:"paid-dispatch",outputSchema:a70,outputSchemaId:"slopcamera.operation.image.generate.output/v2",policy:{cache:"exact-run",cancellable:!1,effect:"paid-cloud",maxDurationMs:120000,maxFanOut:1,maxInputBytes:16384,maxOutputBytes:Uc,preparation:["provider-options"],resources:[{amount:1,resource:"local-io"},{amount:1,resource:"network"},{amount:1,resource:"paid-call"}],resume:"ambiguous-after-dispatch"},version:2}),"slopcamera.image.vectorize":GC({inputSchema:u70,inputSchemaId:"slopcamera.operation.image.vectorize.input/v2",kind:"slopcamera.image.vectorize",lifecycle:"local-artifact",outputSchema:i70,outputSchemaId:"slopcamera.operation.image.vectorize.output/v2",policy:{cache:"none",cancellable:!1,effect:"local-derived-write",maxDurationMs:300000,maxFanOut:1,maxInputBytes:kc,maxOutputBytes:Mc,preparation:["local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"}],resume:"ambiguous-after-dispatch"},version:2})});var e70="slopcamera.workflow.registry-projection/v1",$V0="slopcamera.workflow.registry.public/v1",Tc=new WeakSet,qc=17+X3.length+3*dZ.length,RE=1+LY*qc,TE=33554432,Ec=8,_V0=TE+4096,FV0=Ec+1,QV0=RE+5;function ZV0($){return Array.isArray($)?$:$.list()}function qE($,_="operation discovery list"){if(!Array.isArray($))throw new l0("invalid-data",`${_} must be an array.`);let F=$.length;if(F>LY)throw new l0("invalid-data",`${_} cannot exceed ${String(LY)} entries.`);let Q=Object.getOwnPropertyDescriptors($);if(Object.getOwnPropertySymbols(Q).some((K)=>Reflect.get(Q,K)?.enumerable===!0))throw new l0("invalid-data",`${_} cannot contain enumerable symbol properties.`);let Z=Object.keys(Q).filter((K)=>Q[K]?.enumerable===!0);if(Z.length!==F||Z.some((K,j)=>K!==String(j)))throw new l0("invalid-data",`${_} must be dense and cannot have named properties.`);let X=2+Math.max(0,F-1),Y=1,H=[];for(let K=0;KRE)throw new l0("invalid-data",`${_} contains more than ${String(RE)} JSON values.`);H.push(O.value)}return Object.freeze(H)}function AE($,_){return`${$}@${String(_)}`}function JV0($){return[...new Set($)].sort((_,F)=>_.localeCompare(F))}function DC($){if($==="studio")return"slopcamera";return $.replace(/^studio\./u,"slopcamera.")}function Pc($){let _=qE($).map((Q)=>{let Z=W5(Y3,Q,"operation discovery entry"),J=JV0(Z.policy.preparation);if(J.length!==Z.policy.preparation.length)throw new l0("invalid-data",`Duplicate preparation requirement for ${AE(Z.kind,Z.version)}.`,{kind:Z.kind,version:Z.version});let X=[...Z.policy.resources].sort((Y,H)=>Y.resource.localeCompare(H.resource));if(new Set(X.map((Y)=>Y.resource)).size!==X.length)throw new l0("invalid-data",`Duplicate resource claim for ${AE(Z.kind,Z.version)}.`,{kind:Z.kind,version:Z.version});return W5(Y3,{...Z,policy:{...Z.policy,preparation:J,resources:X}},"normalized operation discovery entry")}).sort((Q,Z)=>Q.kind.localeCompare(Z.kind)||Q.version-Z.version),F=new Set;for(let Q of _){let Z=AE(Q.kind,Q.version);if(F.has(Z))throw new l0("conflict",`Duplicate operation discovery entry: ${Z}`,{kind:Q.kind,version:Q.version});F.add(Z)}return _}function XV0($){return Pc($).map((_)=>W5(Y3,{..._,inputSchemaId:DC(_.inputSchemaId),kind:DC(_.kind),outputSchemaId:DC(_.outputSchemaId)},"canonical operation discovery entry"))}function YV0($){return Object.freeze($.map((_)=>Object.freeze({..._,policy:Object.freeze({..._.policy,preparation:Object.freeze([..._.policy.preparation]),resources:Object.freeze(_.policy.resources.map((F)=>Object.freeze({...F})))})})))}function Ic($,_=e70){return zN(`${_}\x00`,{discovery:$.discovery,id:$.id,trustedCompute:$.trustedCompute})}function LC($,_,F={}){let Q=DC(W5(I6,$,"registry projection id")),Z=XV0(ZV0(_)),J=F.trustedCompute??!1,X=W5(NC,{discovery:Z,id:Q,projectionSha256:Ic({discovery:Z,id:Q,trustedCompute:J}),trustedCompute:J},"workflow registry projection"),Y=Object.freeze({...X,discovery:YV0(X.discovery)});return Tc.add(Y),Y}function bc($){if(typeof $==="object"&&$!==null&&Tc.has($))return $;let _=a0($,_V0,"workflow registry projection",{maximumDepth:FV0,maximumValues:QV0}).value,F=W5(NC,_,"workflow registry projection"),Q=Pc(F.discovery),Z={discovery:Q,id:F.id,trustedCompute:F.trustedCompute},J=Ic(Z);if(F.projectionSha256!==J)throw new l0("invalid-data","Workflow registry projection hash does not match its contents.",{actualProjectionSha256:F.projectionSha256,expectedProjectionSha256:J,projectionId:F.id});if(m(F.discovery)!==m(Q))throw new l0("invalid-data","Workflow registry projection discovery is not normalized.",{projectionId:F.id});return LC(F.id,Q,{trustedCompute:F.trustedCompute})}function HV0(){return Oj.map(($)=>{let _=cZ[$];return{inputSchemaId:_.inputSchemaId,kind:_.kind,lifecycle:_.lifecycle,outputSchemaId:_.outputSchemaId,policy:_.policy,version:_.version}})}function KV0(){return LC($V0,HV0(),{trustedCompute:!1})}var BY=KV0();var jV0="slopcamera.workflow.graph/v1",VV0="slopcamera.workflow.compilation/v1",PE=Object.freeze({maxDepth:64,maxEdges:2048,maxFanOut:64,maxNodes:256,maxTotalOperationFanOut:4096}),WV0=67108864,NV0=160,gc=1100000,OV0=1024,GV0=2,wV0=16;var DV0=17+X3.length+3*dZ.length,LV0=5+LY*DV0,CV0=21+3*A8+JC.length+X3.length+3*dZ.length+XC.length+YC.length,BV0=1+2*A8,zV0=6,t91=gc+LV0+CV0+BV0+zV0+4;function Q8($,_){throw new l0("invalid-data",$,_)}function vc($){if(typeof $!=="object"||$===null||Object.isFrozen($))return $;for(let _ of Object.values($))vc(_);return Object.freeze($)}function CC($,_){return`${$}@${String(_)}`}function H3($){return[...new Set($)].sort((_,F)=>_.localeCompare(F))}function zY($){if($==="studio")return"slopcamera";return $.replace(/^studio\./u,"slopcamera.")}function pZ($,_,F){let Q=$+_;if(!Number.isSafeInteger(Q))return Q8(`${F} exceeds the safe integer range.`,{left:$,right:_});return Q}function UV0($){if($===void 0)return PE;let _=a0($,OV0,"graph compiler limits",{maximumDepth:GV0,maximumValues:wV0}).value;if(typeof _!=="object"||_===null||Array.isArray(_))return W5(Wj,_,"graph compiler limits");return W5(Wj,{...PE,..._},"graph compiler limits")}function kV0($,_){if(typeof $!=="object"||$===null||Array.isArray($))return;let F=Object.getOwnPropertyDescriptor($,"nodes")?.value;if(Array.isArray(F)&&F.length>_)return Q8(`Workflow has ${String(F.length)} nodes; the limit is ${String(_)}.`,{actual:F.length,limit:_})}function MV0($,_=A8){kV0($,_);let F=a0($,WV0,"Authored workflow graph",{maximumDepth:NV0,maximumValues:gc}).value,Q=W5(u_,F,"authored workflow graph");if(Q.nodes.length>_)return Q8(`Workflow has ${String(Q.nodes.length)} nodes; the limit is ${String(_)}.`,{actual:Q.nodes.length,limit:_});let Z={...Q,nodes:[...Q.nodes].sort((J,X)=>J.key.localeCompare(X.key))};return $0(Z)}function BC($){if(xc($))return{$ref:{...$.$ref,schemaId:zY($.$ref.schemaId)},version:MN};if(Array.isArray($))return $.map(BC);if(typeof $==="object"&&$!==null)return Object.fromEntries(Object.entries($).map(([_,F])=>[_,BC(F)]));return $}function AV0($){return $0(W5(u_,{...$,nodes:$.nodes.map((_)=>({..._,executor:_.executor.kind==="operation"?{kind:"operation",operation:{..._.executor.operation,kind:zY(_.executor.operation.kind)}}:{compute:{..._.executor.compute,key:zY(_.executor.compute.key)},kind:"compute"},input:BC(_.input),inputSchemaId:zY(_.inputSchemaId),outputSchemaId:zY(_.outputSchemaId)})),outputs:BC($.outputs),version:kN,workflow:{...$.workflow,id:zY($.workflow.id),inputSchemaId:zY($.workflow.inputSchemaId)}},"canonical authored workflow graph"))}function Gj($,_=A8){return AV0(MV0($,_))}function RV0($){return zN(`${jV0}\x00`,$)}function xc($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.hasOwn($,"$ref")}function TV0($){return Array.isArray($)}function Sc($){let _=[],F=[$];while(F.length>0){let Q=F.pop();if(Q===void 0)continue;if(xc(Q)){_.push(Q);continue}if(TV0(Q)){for(let Z of Q)F.push(Z);continue}if(typeof Q==="object"&&Q!==null)for(let Z of Object.values(Q))F.push(Z)}return _}function fc($,_){return $.length===_.length&&$.every((F,Q)=>F===_[Q])}function yc($,_,F){let Q=_.get($.$ref.nodeKey);if(Q===void 0)return Q8(`${F} contains a dangling reference to ${$.$ref.nodeKey}.`,{nodeKey:$.$ref.nodeKey,owner:F});if(Q.outputSchemaId!==$.$ref.schemaId)return Q8(`${F} expects schema ${$.$ref.schemaId} from ${Q.key}, but the producer declares ${Q.outputSchemaId}.`,{actualSchemaId:Q.outputSchemaId,expectedSchemaId:$.$ref.schemaId,nodeKey:Q.key,owner:F})}function qV0($,_){let F=new Map,Q=new Map,Z=0;for(let j of $){let V=new Set(j.dependencies);F.set(j.key,V),Z=pZ(Z,V.size,"Workflow edge count");for(let O of V){let W=Q.get(O)??new Set;W.add(j.key),Q.set(O,W)}}if(Z>_.maxEdges)return Q8(`Workflow has ${String(Z)} edges; the limit is ${String(_.maxEdges)}.`,{actual:Z,limit:_.maxEdges});let J=Math.max(0,...[...Q.values()].map((j)=>j.size));if(J>_.maxFanOut)return Q8(`Workflow fan-out is ${String(J)}; the limit is ${String(_.maxFanOut)}.`,{actual:J,limit:_.maxFanOut});let X=$.filter((j)=>(F.get(j.key)?.size??0)===0).map((j)=>j.key).sort((j,V)=>j.localeCompare(V)),Y=new Map($.map((j)=>[j.key,F.get(j.key)?.size??0])),H=[],K=0;while(X.length>0){let j=X;H.push(j),K+=j.length;let V=new Set;for(let O of j)for(let W of Q.get(O)??[]){let G=(Y.get(W)??0)-1;if(Y.set(W,G),G===0)V.add(W)}X=[...V].sort((O,W)=>O.localeCompare(W))}if(K!==$.length)return Q8("Workflow graph contains a dependency cycle.");if(H.length>_.maxDepth)return Q8(`Workflow depth is ${String(H.length)}; the limit is ${String(_.maxDepth)}.`,{actual:H.length,limit:_.maxDepth});return{depth:H.length,edges:Z,structuralFanOut:J,waves:H}}function EV0($,_,F){let Q=Gj($,F.maxNodes);if(Q.nodes.length>F.maxNodes)return Q8(`Workflow has ${String(Q.nodes.length)} nodes; the limit is ${String(F.maxNodes)}.`,{actual:Q.nodes.length,limit:F.maxNodes});let Z=new Map;for(let H of Q.nodes){if(Z.has(H.key))return Q8(`Duplicate workflow node key: ${H.key}`,{nodeKey:H.key});Z.set(H.key,H)}let J=new Map(_.discovery.map((H)=>[CC(H.kind,H.version),H])),X=new Map,Y=0;for(let H of Q.nodes){let K;if(M4(H)){let G=H.executor.operation,D=J.get(CC(G.kind,G.version));if(D===void 0)throw new l0("unsupported-plan",`Unsupported operation: ${CC(G.kind,G.version)}`,{kind:G.kind,nodeKey:H.key,projectionId:_.id,version:G.version});if(H.inputSchemaId!==D.inputSchemaId||H.outputSchemaId!==D.outputSchemaId)return Q8(`Operation schema identity mismatch for ${CC(G.kind,G.version)} at node ${H.key}.`,{actualInputSchemaId:H.inputSchemaId,actualOutputSchemaId:H.outputSchemaId,expectedInputSchemaId:D.inputSchemaId,expectedOutputSchemaId:D.outputSchemaId,kind:G.kind,nodeKey:H.key,version:G.version});K=D.policy}else if(F8(H)){if(!_.trustedCompute)throw new l0("unsupported-plan",`Trusted compute is unsupported at node ${H.key}.`,{executorKind:"compute",nodeKey:H.key,projectionId:_.id});K=Vj(H.executor.compute)}else throw new l0("internal",`Unknown node executor for ${H.key}.`);X.set(H.key,K),Y=pZ(Y,K.maxFanOut,"Total operation fan-out");let j=Sc(H.input);for(let G of j)yc(G,Z,`Node ${H.key}`);let V=H.controlDependencies??[],O=H3(V);if(!fc(V,O))return Q8(`Node ${H.key} control dependencies must be unique and sorted.`,{nodeKey:H.key});for(let G of V){if(!Z.has(G))return Q8(`Node ${H.key} contains a dangling control dependency to ${G}.`,{dependency:G,nodeKey:H.key});if(G===H.key)return Q8(`Node ${H.key} cannot depend on itself.`,{nodeKey:H.key})}let W=H3([...j.map((G)=>G.$ref.nodeKey),...V]);if(!fc(H.dependencies,W))return Q8(`Node ${H.key} dependencies do not match its embedded references and explicit control dependencies. Expected [${W.join(", ")}].`,{expectedDependencies:W,nodeKey:H.key})}if(Y>F.maxTotalOperationFanOut)return Q8(`Workflow operation fan-out bound is ${String(Y)}; the limit is ${String(F.maxTotalOperationFanOut)}.`,{actual:Y,limit:F.maxTotalOperationFanOut});for(let H of Sc(Q.outputs))yc(H,Z,"Workflow outputs");return{graph:Q,policiesByNode:X,topology:qV0(Q.nodes,F)}}function PV0($){let _=$.indexOf(".");if(_<1)throw new l0("internal",`Operation ${$} has no namespace family.`,{kind:$});return $.slice(0,_)}function IV0($,_,F){$.set(_,pZ($.get(_)??0,F,`Resource ${_} claim`))}function bV0($){let _=new Set,F=new Set,Q=new Set,Z=new Set,J=new Set,X=new Map,Y=new Set,H=0,K=0,j=0,V=0,O=0;for(let G of $.graph.nodes){let D=$.policiesByNode.get(G.key);if(D===void 0)throw new l0("internal",`Node ${G.key} lost its execution policy.`);if(F.add(D.effect),Y.add(D.resume),M4(G))Q.add(PV0(G.executor.operation.kind)),Z.add(G.executor.operation.kind);else if(F8(G))Q.add("compute"),_.add(G.executor.compute.key);for(let w of D.preparation)J.add(w);for(let w of D.resources)IV0(X,w.resource,w.amount);if(D.effect==="paid-cloud"&&D.preparation.includes("local-media"))H=pZ(H,1,"Local media upload node count");K=pZ(K,D.maxDurationMs,"Workflow duration bound"),j=pZ(j,D.maxInputBytes,"Workflow input byte bound"),V=pZ(V,D.maxOutputBytes,"Workflow output byte bound"),O=pZ(O,D.maxFanOut,"Workflow operation fan-out bound")}let W=new Set;if($.topology.edges>0)W.add("dependency-outputs");if(J.has("local-media")||J.has("project-state")||J.has("recording-metadata"))W.add("exact-media-hashes");if(J.has("recording-metadata")||J.has("typed-text")||J.has("window-metadata"))W.add("exact-sensitive-metadata-hashes");if(F.has("paid-cloud")||X.has("paid-call"))W.add("prices");if(F.has("project-mutation")||Z.has("render.project")||Z.has("render.project-plan"))W.add("project-generations");if(Q.has("render"))W.add("render-plans");return W5(EN,{bounds:{depth:$.topology.depth,edges:$.topology.edges,localMediaUploadNodes:H,maxDurationMs:K,maxInputBytes:j,maxOutputBytes:V,nodes:$.graph.nodes.length,paidCallClaims:X.get("paid-call")??0,structuralFanOut:$.topology.structuralFanOut,totalOperationFanOut:O},computeKeys:H3(_),effects:H3(F),operationFamilies:H3(Q),operationKinds:H3(Z),preparation:H3(J),resources:[...X].map(([G,D])=>({amount:D,resource:G})).sort((G,D)=>G.resource.localeCompare(D.resource)),resumeClasses:H3(Y),unresolved:H3(W),version:AN},"workflow requirement envelope")}function SV0($){if($.projection!==void 0){if($.registry!==void 0||$.projectionId!==void 0||$.trustedCompute!==void 0)throw new l0("invalid-data","Compile with either a projection or a registry projection source, not both.");return bc($.projection)}if($.registry!==void 0){if($.projectionId===void 0)throw new l0("invalid-data","A registry projection source requires an explicit projection id.");return LC($.projectionId,$.registry,{trustedCompute:$.trustedCompute??!1})}if($.projectionId!==void 0||$.trustedCompute!==void 0)throw new l0("invalid-data","A projection id or trusted-compute authority requires a registry projection source.");return BY}var PN=EE.unknown().refine(($)=>$!==void 0,"Required"),e91=EE.strictObject({compilationSha256:W2,envelope:PN,graph:PN,graphSha256:W2,limits:PN,projection:PN,topologicalWaves:PN,version:EE.literal(HC)});function fV0($){return zN(`${VV0}\x00`,$)}function hc($){let _=UV0($.limits),F=SV0($),Q=EV0($.graph,F,_),Z=RV0(Q.graph),J={envelope:bV0(Q),graph:Q.graph,graphSha256:Z,limits:_,projection:F,topologicalWaves:Q.topology.waves,version:HC};return vc(W5(Lc,{...J,compilationSha256:fV0(J)},"compiled workflow graph"))}var zC=128,IN=1e6,mc=new WeakMap;function pc($){if($.consumed>=$.maximum)throw new l0("invalid-data",`Workflow authoring values exceed the ${String(IN)} value limit.`);$.consumed+=1}function sc($,_){bN($,_),$.consumed+=_}function bN($,_){if(_>$.maximum-$.consumed)throw new l0("invalid-data",`Workflow authoring values exceed the ${String(IN)} value limit.`)}function nc($){return{consumed:0,maximum:IN-$.authoredValues}}function uc($,_){if(_>IN-$.authoredValues)throw new l0("invalid-data",`Workflow authoring values exceed the ${String(IN)} value limit.`)}function yV0($){if($[kE]===!0)return $;if(Reflect.get($,Cc)!==!0)return;let _=mc.get($);if(_!==void 0)return _;let F=Object.freeze({[kE]:!0,bounds:$.bounds,inputSchema:$.inputSchema,inputSchemaId:$.inputSchemaId,key:$.key,outputSchema:$.outputSchema,outputSchemaId:$.outputSchemaId,run:$.run});return mc.set($,F),F}function IE($,_){return`${$}@${String(_)}`}function gV0($){let _=$,F=typeof _.list==="function"?_.list():$.discovery;return qE(F)}function rc($){let _=Object.getPrototypeOf($);return _===Object.prototype||_===null}function SN($,_){if(Object.getOwnPropertySymbols($).some((F)=>Reflect.get($,F)?.enumerable===!0))throw new l0("invalid-data",`${_} cannot contain enumerable symbol properties.`)}function fE($){return $0(W5(VC,$.serialized,"workflow reference"))}function oc($){let _=$.$ref.path;return _===void 0?5:6+_.length}function yE($,_){return typeof $==="object"&&$!==null&&OC in $&&_.references.has($)}function bE($,_,F,Q,Z,J){if(Z>zC)throw new l0("invalid-data",`Workflow input nesting exceeds ${String(zC)} levels.`);if(yE($,_)){let X=fE($);return sc(J,oc(X)),F.add(X.$ref.nodeKey),X}if(pc(J),typeof $==="object"&&$!==null&&OC in $)throw new l0("invalid-data","Use a typed Ref value created by this workflow graph builder.");if($===null||typeof $==="boolean"||typeof $==="string")return $;if(typeof $==="number"){if(!Number.isFinite($))throw new l0("invalid-data","Workflow node input numbers must be finite.");return Object.is($,-0)?0:$}if(typeof $!=="object")throw new l0("invalid-data",`Workflow node input cannot contain ${typeof $} values.`);if(Q.has($))throw new l0("invalid-data","Workflow node input cannot contain cycles.");Q.add($);try{if(Array.isArray($)){let K=$.length;bN(J,K);let j=Object.getOwnPropertyDescriptors($);SN(j,"Workflow node input arrays");let V=Object.keys(j).filter((W)=>j[W]?.enumerable===!0);if(V.length!==K||V.some((W,G)=>W!==String(G)))throw new l0("invalid-data","Workflow node input arrays must be dense and cannot have named properties.");let O=[];for(let W=0;WX[K]?.enumerable===!0).sort();bN(J,Y.length);let H={};for(let K of Y){if(K==="__proto__")throw new l0("invalid-data","Workflow inputs cannot contain the reserved __proto__ object key.");let j=X[K];if(j===void 0||j.get!==void 0||j.set!==void 0)throw new l0("invalid-data","Workflow node input properties must be plain data properties.");H[K]=bE(j.value,_,F,Q,Z+1,J)}return H}finally{Q.delete($)}}function lc($,_){let F=new Set,Q=nc(_),Z=bE($,_,F,new Set,0,Q);return{dependencies:[...F].sort((J,X)=>J.localeCompare(X)),value:Z,values:Q.consumed}}function dc($,_){if($===void 0)return[];let F=new Set,Q=(Y)=>{if(!yE(Y,_))throw new l0("invalid-data","Operation control dependencies must be typed Ref values created by this workflow graph builder.");F.add(fE(Y).$ref.nodeKey)};if(!Array.isArray($))return Q($),[...F];let Z=$.length;if(Z>UN)throw new l0("invalid-data",`Operation control dependencies cannot exceed ${String(UN)} entries.`);let J=Object.getOwnPropertyDescriptors($);SN(J,"Operation control dependencies");let X=Object.keys(J).filter((Y)=>J[Y]?.enumerable===!0);if(X.length!==Z||X.some((Y,H)=>Y!==String(H)))throw new l0("invalid-data","Operation control dependencies must be a dense array without named properties.");for(let Y=0;YY.localeCompare(H))}function cc($,_){return[...new Set([...$,..._])].sort((F,Q)=>F.localeCompare(Q))}function SE($,_,F,Q,Z){if(Q>zC)throw new l0("invalid-data",`Workflow output nesting exceeds ${String(zC)} levels.`);if(yE($,_)){let J=fE($);return sc(Z,oc(J)),J}if(pc(Z),typeof $!=="object"||$===null)throw new l0("invalid-data","Workflow outputs must contain only typed references, arrays, and named objects.");if(F.has($))throw new l0("invalid-data","Workflow outputs cannot contain cycles.");F.add($);try{if(Array.isArray($)){let H=$.length;bN(Z,H);let K=Object.getOwnPropertyDescriptors($);SN(K,"Workflow output arrays");let j=Object.keys(K).filter((O)=>K[O]?.enumerable===!0);if(j.length!==H||j.some((O,W)=>O!==String(W)))throw new l0("invalid-data","Workflow output arrays must be dense and cannot have named properties.");let V=[];for(let O=0;OJ[H]?.enumerable===!0).sort();bN(Z,X.length);let Y={};for(let H of X){if(H==="__proto__")throw new l0("invalid-data","Workflow outputs cannot contain the reserved __proto__ object key.");let K=J[H];if(K===void 0||K.get!==void 0||K.set!==void 0)throw new l0("invalid-data","Workflow output properties must be plain data properties.");Y[H]=SE(K.value,_,F,Q+1,Z)}return Y}finally{F.delete($)}}function UC($,_,F,Q=[]){if(Q.length>lZ)throw new l0("invalid-data",`Workflow reference paths cannot exceed ${String(lZ)} segments.`);let Z=$0({$ref:{nodeKey:$,...Q.length===0?{}:{path:[...Q]},schemaId:_},version:MN}),J=Object.freeze({[OC]:()=>{throw new l0("internal","A workflow reference type marker is not executable.")},at:(X)=>{if(!Number.isSafeInteger(X)||X<0)throw new l0("invalid-data","Workflow reference array indexes must be nonnegative safe integers.");if(Q.length>=lZ)throw new l0("invalid-data",`Workflow reference paths cannot exceed ${String(lZ)} segments.`);return UC($,_,F,[...Q,X])},select:(X)=>{if(typeof X!=="string"||X.length<1||X.length>128)throw new l0("invalid-data","Workflow reference field names must contain 1\u2013128 characters.");if(Q.length>=lZ)throw new l0("invalid-data",`Workflow reference paths cannot exceed ${String(lZ)} segments.`);return UC($,_,F,[...Q,X])},serialized:Z});return F.references.add(J),J}function vV0($){let _=new Map;for(let F of gV0($)){let Q=W5(Y3,F,"operation discovery entry"),Z=IE(Q.kind,Q.version);if(_.has(Z))throw new l0("conflict",`Duplicate operation discovery entry: ${Z}`,{kind:Q.kind,version:Q.version});_.set(Z,Q)}return{authoredValues:7,computes:new Map,discovery:_,nodes:new Map,references:new WeakSet}}class wj{#$;#_;constructor($,_){this.#$=_,this.#_=$}static create($){return new wj(vV0($),[])}namespace($){let _=W5(KC,$,"workflow namespace segment");return new wj(this.#_,[...this.#$,_])}fragment($,_,F){return _.build(this.namespace($),F)}operation($,_,F,Q={}){return this.#J($,{input:F,inputSchemaId:_.inputSchemaId,kind:_.kind,outputSchemaId:_.outputSchemaId,version:_.version},Q)}operationByKind($,_,F={}){let Q=this.#_.discovery.get(IE(_.kind,_.version));if(Q===void 0)throw new l0("unsupported-plan",`Unsupported operation: ${_.kind}@${String(_.version)}`,{kind:_.kind,version:_.version});return this.#J($,{input:_.input,inputSchemaId:Q.inputSchemaId,kind:_.kind,outputSchemaId:Q.outputSchemaId,version:_.version},F)}compute($,_,F,Q={}){if(typeof _!=="object"||_===null)throw new l0("invalid-data","Compute nodes require a definition created by defineCompute().");let Z=yV0(_);if(Z===void 0)throw new l0("invalid-data","Compute nodes require a definition created by defineCompute().");let J=W5(RN,{bounds:Z.bounds,key:Z.key,version:GE},"trusted compute identity"),X=this.#_.computes.get(J.key);if(X!==void 0&&X!==Z)throw new l0("conflict",`Duplicate trusted compute key: ${J.key}`,{key:J.key});let Y=this.#Q($),H=lc(F,this.#_),K=dc(Q.after,this.#_),j=cc(H.dependencies,K),V=H.values+15+K.length+j.length+(Q.label===void 0?0:1);uc(this.#_,V);let O=W5(WC,{controlDependencies:K,dependencies:j,executor:{compute:J,kind:"compute"},input:H.value,inputSchemaId:Z.inputSchemaId,key:Y,...Q.label===void 0?{}:{label:Q.label},outputSchemaId:Z.outputSchemaId},"authored compute node");return this.#_.computes.set(J.key,Z),this.#_.nodes.set(Y,O),this.#_.authoredValues+=V,UC(Y,Z.outputSchemaId,this.#_)}computeDefinitions(){return Object.freeze([...this.#_.computes.values()].sort(($,_)=>$.key.localeCompare(_.key)))}build($,_){let F=W5(qN,$,"workflow identity"),Q=nc(this.#_),Z=SE(_,this.#_,new Set,0,Q);return $0(W5(u_,{nodes:[...this.#_.nodes.values()].sort((J,X)=>J.key.localeCompare(X.key)),outputs:Z,version:kN,workflow:F},"authored workflow graph"))}#Q($){let _=W5(KC,$,"workflow node key segment"),F=[...this.#$,_].join("/");if(this.#_.nodes.has(F))throw new l0("conflict",`Duplicate workflow node key: ${F}`,{nodeKey:F});if(this.#_.nodes.size>=A8)throw new l0("invalid-data",`Workflow nodes cannot exceed ${String(A8)} entries.`);return F}#J($,_,F){let Q=this.#Q($),Z=this.#_.discovery.get(IE(_.kind,_.version));if(Z===void 0)throw new l0("unsupported-plan",`Unsupported operation: ${_.kind}@${String(_.version)}`,{kind:_.kind,version:_.version});if(_.inputSchemaId!==Z.inputSchemaId||_.outputSchemaId!==Z.outputSchemaId)throw new l0("invalid-data",`Operation contract schema mismatch for ${_.kind}@${String(_.version)}.`,{actualInputSchemaId:_.inputSchemaId,actualOutputSchemaId:_.outputSchemaId,expectedInputSchemaId:Z.inputSchemaId,expectedOutputSchemaId:Z.outputSchemaId,kind:_.kind,version:_.version});let J=lc(_.input,this.#_),X=dc(F.after,this.#_),Y=cc(J.dependencies,X),H=J.values+11+X.length+Y.length+(F.label===void 0?0:1);uc(this.#_,H);let K=W5(WC,{controlDependencies:X,dependencies:Y,executor:{kind:"operation",operation:{kind:Z.kind,version:Z.version}},input:J.value,inputSchemaId:Z.inputSchemaId,key:Q,...F.label===void 0?{}:{label:F.label},outputSchemaId:Z.outputSchemaId},"authored operation node");return this.#_.nodes.set(Q,K),this.#_.authoredValues+=H,UC(Q,Z.outputSchemaId,this.#_)}}var N=l0,uF=YE;function UY($){return Zc($)}var kC={usage:2,"not-found":3,conflict:4,unavailable:5,"unsafe-path":6,"invalid-data":7,subprocess:8,"unsupported-plan":9,"authorization-required":10,cancelled:11,ambiguous:12,incompatible:13,internal:1};function kY($){if($ instanceof N)return $;return new N("internal",uF($))}var Dj=1e4;var gE=["blender-product","blender-character","blender-shaded-street","blender-cloth","blender-fluid","cadquery-bracket","manim-lesson"];import{createHash as AC,randomUUID as KW0}from"crypto";import{link as jW0,mkdir as Jp,rm as VW0,writeFile as WW0}from"fs/promises";import{dirname as NW0,join as RC,resolve as OW0}from"path";import MY from"sharp";class h1 extends Error{code;constructor($,_,F){super(`[${$}] ${_}`,F);this.name="SlopcameraCloudError",this.code=$}}import{createHash as xE,randomUUID as tc}from"crypto";import{link as xV0,rm as hV0,writeFile as mV0}from"fs/promises";import{dirname as uV0,extname as lV0,resolve as ic}from"path";var fN="https://ai-gateway.vercel.sh/v4/ai",ec=Object.freeze(["openai/gpt-image-1.5","recraft/recraft-v4.1-utility"]),dV0=Object.freeze(["image/png","image/jpeg","image/webp"]),nZ=32768,cV0=67108864,pV0=300000,ac=1800000,sV0=100663296;function Lj($){throw new h1("INVALID_ARGUMENT",$)}function MC($){if($.length<16||$.length>16384||$.trim()!==$||/[^\x21-\x7e]/u.test($))throw new h1("AUTHENTICATION_REQUIRED","The selected Vercel AI Gateway credential is invalid.");return $}function $p($){return $??process.env}function hE($){let _=$p($);if(_.AI_GATEWAY_API_KEY!==void 0)return{source:"AI_GATEWAY_API_KEY",token:MC(_.AI_GATEWAY_API_KEY)};if(_.VERCEL_OIDC_TOKEN!==void 0)return{source:"VERCEL_OIDC_TOKEN",token:MC(_.VERCEL_OIDC_TOKEN)};throw new h1("AUTHENTICATION_REQUIRED","Set AI_GATEWAY_API_KEY or run Slopcamera through `vercel env run -- \u2026` with VERCEL_OIDC_TOKEN available.")}function _p($){let _=$p($);if(_.AI_GATEWAY_API_KEY!==void 0)return MC(_.AI_GATEWAY_API_KEY),{available:!0,source:"AI_GATEWAY_API_KEY"};if(_.VERCEL_OIDC_TOKEN!==void 0)return MC(_.VERCEL_OIDC_TOKEN),{available:!0,source:"VERCEL_OIDC_TOKEN"};return{available:!1,source:null}}function nV0($){if(typeof $!=="string"||$.length<3||$.length>256||!/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/iu.test($))Lj("Model must be a bounded Vercel AI Gateway provider/model id.");return $}function rV0($){if(typeof $!=="string"||$.trim().length===0||/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test($)||Buffer.byteLength($,"utf8")>nZ)Lj(`Prompt must be non-empty and no more than ${nZ} UTF-8 bytes.`);return $}function oV0($){let _=$??pV0;if(!Number.isSafeInteger(_)||_<1000||_>ac)Lj(`timeoutMs must be an integer from 1000 through ${ac}.`);return _}function sZ($){return typeof $==="object"&&$!==null||typeof $==="function"}function iV0($){if(typeof $!=="function")throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.");return $}function aV0(){globalThis.AI_SDK_LOG_WARNINGS=!1}function vE($){if($.aborted)throw new h1("GENERATION_FAILED","Vercel AI Gateway image generation was cancelled or exceeded its deadline.")}async function tV0(){let $,_;try{[$,_]=await Promise.all([import("ai-v7"),import("@ai-sdk/gateway-v4")])}catch{throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.")}if(!sZ($)||!sZ(_))throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.");let F=iV0($.generateImage);if(typeof _.createGateway!=="function")throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.");let Q=_.createGateway;return{createGateway:(Z)=>{let J=Q(Z);if(!sZ(J)||typeof J.imageModel!=="function")throw new h1("GENERATION_FAILED","The Vercel AI Gateway runtime is unavailable.");let X=J.imageModel;return{imageModel:(Y)=>X.call(J,Y)}},generateImage:F}}function eV0($){try{if($ instanceof Request)return new URL($.url);if($ instanceof URL)return new URL($.href);return new URL($,fN)}catch{throw new h1("GENERATION_FAILED","The Vercel AI Gateway request was rejected.")}}function $W0($,_){if(!($ instanceof Request))return _;let F=new Request($),Q=F.method==="GET"||F.method==="HEAD"?void 0:F.body??void 0,Z={headers:F.headers,method:F.method,signal:F.signal,...Q===void 0?{}:{body:Q,duplex:"half"}};return new Request(_.href,Z)}function _W0($,_){let F=$.headers.get("content-length");if(F!==null){let X=Number(F);if(!Number.isSafeInteger(X)||X<0||X>_)throw $.body?.cancel().catch(()=>{return}),new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded response.")}if($.body===null)return $;let Q=$.body.getReader(),Z=0,J=new ReadableStream({cancel:async(X)=>await Q.cancel(X),pull:async(X)=>{try{let Y=await Q.read();if(Y.done){Q.releaseLock(),X.close();return}if(Z+=Y.value.byteLength,Z>_){await Q.cancel().catch(()=>{return}),X.error(new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded response."));return}X.enqueue(Y.value)}catch{X.error(new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded response."))}}});return new Response(J,{headers:$.headers,status:$.status,statusText:$.statusText})}function mE($={}){let _=$.fetch??globalThis.fetch,F=$.maximumResponseBytes??sV0;if(!Number.isSafeInteger(F)||F<1||F>1073741824)Lj("maximumResponseBytes is outside the supported range.");let Q=new URL(fN);return async(Z,J)=>{let X=eV0(Z);if(X.origin!==Q.origin||X.pathname!==Q.pathname&&!X.pathname.startsWith(`${Q.pathname}/`)||X.username!==""||X.password!=="")throw new h1("GENERATION_FAILED","The Vercel AI Gateway request was rejected.");let Y=$W0(Z,X),H;try{H=await _(Y,{...J,redirect:"error"})}catch(K){if(K instanceof h1)throw K;throw new h1("GENERATION_FAILED","Vercel AI Gateway image generation failed; the request was not retried.")}if(H.redirected||H.status>=300&&H.status<400)throw await H.body?.cancel().catch(()=>{return}),new h1("GENERATION_FAILED","The Vercel AI Gateway request was rejected.");return _W0(H,F)}}function FW0($,_){let F=new AbortController,Q=()=>F.abort($?.reason),Z,J=new Promise((H,K)=>{Z=K}),X=()=>{Z?.(new h1("GENERATION_FAILED","Vercel AI Gateway image generation was cancelled or exceeded its deadline."))};if(F.signal.addEventListener("abort",X,{once:!0}),$?.aborted===!0)Q();$?.addEventListener("abort",Q,{once:!0});let Y=setTimeout(()=>F.abort(),_);return{dispose:()=>{clearTimeout(Y),$?.removeEventListener("abort",Q),F.signal.removeEventListener("abort",X),Z=void 0},interruption:J,signal:F.signal}}function QW0($){if(typeof $!=="string"||!dV0.includes($))throw new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an unsupported image type.");return $}function ZW0($,_){if($.byteLength<12||$.byteLength>cV0)return!1;if(_==="image/png")return Buffer.from($.subarray(0,8)).equals(Buffer.from([137,80,78,71,13,10,26,10]));if(_==="image/jpeg")return $[0]===255&&$[1]===216&&$.at(-2)===255&&$.at(-1)===217;return $.byteLength>=16&&Buffer.from($.subarray(0,4)).toString("ascii")==="RIFF"&&Buffer.from($).readUInt32LE(4)===$.byteLength-8&&Buffer.from($.subarray(8,12)).toString("ascii")==="WEBP"&&["VP8 ","VP8L","VP8X"].includes(Buffer.from($.subarray(12,16)).toString("ascii"))}function JW0($){let _="provider-warning",F="Provider warning";if(typeof $==="string")F=$;else if(sZ($)){if(typeof $.type==="string"&&$.type.length<=64)_=$.type.replace(/[^a-z0-9._-]/giu,"-")||_;if(typeof $.message==="string")F=$.message;else if(typeof $.details==="string")F=$.details}return`${_} sha256:${xE("sha256").update(F).digest("hex")}`}function XW0($,_){if(!sZ($)||!Array.isArray($.images)||$.images.length!==1)throw new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway did not return exactly one image.");let F=$.images[0];if(!sZ(F)||!(F.uint8Array instanceof Uint8Array))throw new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded image.");let Q=QW0(F.mediaType);if(!ZW0(F.uint8Array,Q))throw new h1("GENERATION_INVALID_RESPONSE","Vercel AI Gateway returned an invalid bounded image.");let Z=sZ($.providerMetadata)&&sZ($.providerMetadata.gateway)?$.providerMetadata.gateway:void 0,J=Z!==void 0&&typeof Z.generationId==="string"&&Z.generationId.length>0&&Z.generationId.length<=256&&!/[\u0000-\u001f\u007f]/u.test(Z.generationId)?Z.generationId:tc(),X=`sha256:${xE("sha256").update("slopcamera.gateway-generation-id/v1\x00").update(J).digest("hex")}`,Y=Array.isArray($.warnings)?$.warnings.slice(0,100).map(JW0):[];return{bytes:F.uint8Array,response:{image:{base64:Buffer.from(F.uint8Array).toString("base64"),mediaType:Q},model:_,provider:"vercel-ai-gateway",requestId:X,warnings:Y}}}async function Fp($,_){let F=nV0($.model),Q=rV0($.prompt),Z=hE(_.environment),J=FW0($.signal,oV0($.timeoutMs));try{let X=(async()=>{vE(J.signal),aV0();let Y=await(_.loadRuntime??tV0)();vE(J.signal);let H=Y.createGateway({apiKey:Z.token,baseURL:fN,fetch:mE({..._.fetch===void 0?{}:{fetch:_.fetch},..._.maximumResponseBytes===void 0?{}:{maximumResponseBytes:_.maximumResponseBytes}})});vE(J.signal);let K=await Y.generateImage({abortSignal:J.signal,maxRetries:0,model:H.imageModel(F),n:1,prompt:Q});return XW0(K,F)})();return await Promise.race([X,J.interruption])}catch(X){if(X instanceof h1)throw X;throw new h1("GENERATION_FAILED","Vercel AI Gateway image generation failed; the request was not retried.")}finally{J.dispose()}}async function Cj($,_={}){return(await Fp($,_)).response}function YW0($){let _=lV0($).toLocaleLowerCase("en-US");if(_===".png")return"image/png";if(_===".jpg"||_===".jpeg")return"image/jpeg";if(_===".webp")return"image/webp";Lj("Output path must end in .png, .jpg, .jpeg, or .webp.")}async function HW0($,_){let F=ic($),Q=ic(uV0(F),`.${tc()}.slopcamera-generate.tmp`);try{return await mV0(Q,_,{flag:"wx"}),await xV0(Q,F),F}catch{throw new h1("OUTPUT_WRITE_FAILED","Slopcamera could not atomically write the generated image.")}finally{await hV0(Q,{force:!0}).catch(()=>{return})}}async function Bj($,_={}){if(typeof $.outputPath!=="string"||$.outputPath.length<1||$.outputPath.length>4096||$.outputPath.includes("\x00"))Lj("Output path must be a non-empty local path.");let F=YW0($.outputPath),Q=await Fp($,_);if(Q.response.image.mediaType!==F)throw new h1("GENERATION_INVALID_RESPONSE",`Generated ${Q.response.image.mediaType} does not match the requested ${F} output path.`);let Z=await HW0($.outputPath,Q.bytes);return{bytes:Q.bytes.byteLength,mediaType:Q.response.image.mediaType,model:Q.response.model,outputPath:Z,provider:Q.response.provider,requestId:Q.response.requestId,sha256:xE("sha256").update(Q.bytes).digest("hex"),warnings:Q.response.warnings}}var K3=Object.freeze(["image","texture","skybox","backdrop","sprite"]),H_=Object.freeze(["style","palette","material","lighting","mood","detail"]),w1=Object.freeze({candidates:16,concurrency:4,subjectBytes:2048,candidatePromptBytes:nZ,variantBytes:1024,idLength:64,cellEdgeMin:64,cellEdgeMax:1024,cellEdgeDefault:512,labelHeight:28,cellGap:8,galleryPixels:33554432,candidatePixels:33554432,candidateEdge:8192}),Xp={image:{aspect:[1,1],frame:($)=>$,rules:"Clean readable composition; no text, captions, borders, or watermark."},texture:{aspect:[1,1],frame:($)=>`Seamless tileable texture of ${$}.`,rules:"Flat orthographic top-down material surface, uniform diffuse lighting, edge-to-edge surface detail that tiles in both directions; no shadows, no specular highlights, no vignette, no borders, no objects, no text."},skybox:{aspect:[2,1],frame:($)=>`Seamless equirectangular 360-degree panorama of ${$}.`,rules:"Full spherical environment in 2:1 equirectangular projection, continuous horizon exactly at the vertical center, left and right edges wrapping seamlessly; no seams, no text, no watermark, no foreground frame."},backdrop:{aspect:[16,9],frame:($)=>`Flat scenic backdrop plate of ${$}.`,rules:"Edge-to-edge environment plate for compositing behind foreground subjects, consistent perspective and lighting across the frame; no borders, no text, no watermark."},sprite:{aspect:[1,1],frame:($)=>`A single ${$} on a plain solid neutral background.`,rules:"One centered subject, fully visible with a clean silhouette, flat even lighting; no shadows, no extra objects, no text, no watermark."}},Qp={style:["photorealistic","stylized painterly","flat minimal","hand-drawn"],palette:["warm earthy palette","cool desaturated palette","neutral grayscale palette","vivid saturated palette"],material:["rough weathered surface","smooth polished surface","organic natural surface","synthetic industrial surface"],lighting:["soft diffuse lighting","dramatic directional lighting","flat ambient lighting","golden-hour lighting"],mood:["serene calm mood","dramatic mood","playful mood","mysterious mood"],detail:["minimal sparse detail","balanced detail","intricate dense detail"]},GW0={material:["clear air","light haze","thin clouds","dense dramatic clouds"],lighting:["golden hour","overcast midday","clear night sky","midday sun"]};function wW0($,_){return $==="skybox"?GW0[_]??Qp[_]:Qp[_]}function d2($){throw new h1("INVALID_ARGUMENT",$)}function gN($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function yN($,_,F){if(typeof $!=="string"||$.trim().length===0||/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test($)||Buffer.byteLength($,"utf8")>F)d2(`${_} must be non-empty text no more than ${F} UTF-8 bytes.`);return $.trim()}function DW0($){let _=yN($,"Candidate id",w1.idLength);if(!/^[a-z0-9][a-z0-9._-]*$/iu.test(_))d2("Candidate id must start with an alphanumeric and contain only alphanumerics, '.', '_', or '-'.");return _}function Yp($){let _=$.toLowerCase().split(/[^a-z0-9]+/u).filter((F)=>F.length>0).join("-").slice(0,w1.idLength);return _.length===0?"candidate":_}function LW0($){let _=$??"image";if(typeof _!=="string"||!K3.includes(_))d2(`kind must be one of: ${K3.join(", ")}.`);return _}function uE($,_,F){let Q=Xp[_],Z=[Q.frame($),`Rules: ${Q.rules}`],J=F?.trim();if(J!==void 0&&J.length>0)Z.push(`Variation direction: ${J}.`);return Z.join(` `)}function CW0($){if(typeof $==="string"){let Q=$.trim();if(!H_.includes(Q))d2(`vary axis must be one of: ${H_.join(", ")}.`);return{axis:Q}}if(!gN($))d2("vary entries must be axis names or {axis, values} objects.");let _=$.axis;if(!H_.includes(_))d2(`vary axis must be one of: ${H_.join(", ")}.`);let F=$.values;if(F!==void 0){if(!Array.isArray(F)||F.length<1||F.length>w1.candidates)d2("vary values must be a bounded non-empty list.");return{axis:_,values:F.map((Q)=>yN(Q,"vary value",w1.variantBytes))}}return{axis:_}}function BW0($){if(!gN($))d2("candidates entries must be {id, prompt|variant} objects.");let _=DW0($.id),F=$.prompt,Q=$.variant;if(F!==void 0&&Q!==void 0)d2("A candidate supplies prompt or variant, not both.");if(F===void 0&&Q===void 0)d2("A candidate requires a prompt or a variant.");return{id:_,...F===void 0?{}:{prompt:yN(F,"candidate prompt",w1.candidatePromptBytes)},...Q===void 0?{}:{variant:yN(Q,"candidate variant",w1.variantBytes)}}}function dE($){if(!gN($))d2("Gallery input must be an object.");let _=yN($.subject,"subject",w1.subjectBytes),F=LW0($.kind),Q=Xp[F].aspect,Z=($.vary??[]).map(CW0),J=$.candidates?.map(BW0);if(J!==void 0&&Z.length>0)d2("candidates and vary are mutually exclusive.");if(J!==void 0&&$.count!==void 0)d2("candidates and count are mutually exclusive.");if(Z.length>H_.length||new Set(Z.map((j)=>j.axis)).size!==Z.length)d2("vary axes must be unique.");let X=$.count;if(X!==void 0&&(!Number.isInteger(X)||X<1||X>w1.candidates))d2(`count must be an integer from 1 through ${w1.candidates}.`);let Y=$.tiled;if(Y!==void 0&&typeof Y!=="boolean")d2("tiled must be a boolean when set.");let H=Z.map((j)=>({axis:j.axis,values:j.values??wW0(F,j.axis).slice(0,w1.candidates)})),K=[];if(J!==void 0){if(J.length<1||J.length>w1.candidates)d2(`candidates must contain 1 through ${w1.candidates} entries.`);for(let j of J)K.push({id:j.id,prompt:j.prompt??uE(_,F,j.variant),label:j.id})}else if(H.length>0){let j=H.reduce((O,W)=>O*W.values.length,1);if(j<1||j>w1.candidates)d2(`vary expands to ${String(j)} candidates; the bound is ${w1.candidates}.`);let V=new Set;for(let O=0;O=0;L--){let C=H[L],B=C.values[W%C.values.length];W=Math.floor(W/C.values.length),G.unshift(`${C.axis}: ${B}`)}let D=G.join("; "),w=Yp(G.map((L)=>L.split(": ")[1]).join("-"));if(V.has(w))w=`${w}-${String(O+1)}`;V.add(w),K.push({id:w,prompt:uE(_,F,D),label:w})}}else{let j=X??4;for(let V=0;V({index:V+1,...j})),tiled:Y??F==="texture"}}function Hp($){let _=[];for(let F of $.split(";")){let Q=F.trim();if(Q==="")continue;let[Z,J]=Q.split("=",2);if(!H_.includes(Z.trim()))d2(`vary axis must be one of: ${H_.join(", ")}.`);if(J===void 0){_.push({axis:Z.trim()});continue}let X=J.split(",").map((Y)=>Y.trim()).filter((Y)=>Y.length>0);if(X.length===0||X.length>w1.candidates)d2("vary values must be a non-empty bounded comma-separated list.");_.push({axis:Z.trim(),values:X})}if(_.length===0)d2("vary requires at least one axis, e.g. 'style; palette=warm,cool'.");return _}var Zp={" ":["00000","00000","00000","00000","00000","00000","00000"],"0":["01110","10001","10011","10101","11001","10001","01110"],"1":["00100","01100","00100","00100","00100","00100","01110"],"2":["01110","10001","00001","00010","00100","01000","11111"],"3":["11111","00010","00100","00010","00001","10001","01110"],"4":["00010","00110","01010","11111","00010","00010","00010"],"5":["11111","10000","11110","00001","00001","10001","01110"],"6":["00110","01000","10000","11110","10001","10001","01110"],"7":["11111","00001","00010","00100","01000","01000","01000"],"8":["01110","10001","10001","01110","10001","10001","01110"],"9":["01110","10001","10001","01111","00001","00010","01100"],a:["00000","00000","01110","00001","01111","10001","01111"],b:["10000","10000","10110","11001","10001","10001","11110"],c:["00000","00000","01110","10000","10000","10001","01110"],d:["00001","00001","01101","10011","10001","10001","01111"],e:["00000","00000","01110","10001","11111","10000","01110"],f:["00110","01001","01000","11100","01000","01000","01000"],g:["00000","01111","10001","10001","01111","00001","01110"],h:["10000","10000","10110","11001","10001","10001","10001"],i:["00100","00000","01100","00100","00100","00100","01110"],j:["00010","00000","00110","00010","00010","10010","01100"],k:["10000","10000","10010","10100","11000","10100","10010"],l:["01100","00100","00100","00100","00100","00100","01110"],m:["00000","00000","11010","10101","10101","10101","10101"],n:["00000","00000","10110","11001","10001","10001","10001"],o:["00000","00000","01110","10001","10001","10001","01110"],p:["00000","00000","11110","10001","11110","10000","10000"],q:["00000","00000","01101","10011","01111","00001","00001"],r:["00000","00000","10110","11001","10000","10000","10000"],s:["00000","00000","01111","10000","01110","00001","11110"],t:["01000","01000","11100","01000","01000","01001","00110"],u:["00000","00000","10001","10001","10001","10011","01101"],v:["00000","00000","10001","10001","10001","01010","00100"],w:["00000","00000","10001","10101","10101","10101","01010"],x:["00000","00000","10001","01010","00100","01010","10001"],y:["00000","00000","10001","10001","01111","00001","01110"],z:["00000","00000","11111","00010","00100","01000","11111"],"#":["01010","01010","11111","01010","11111","01010","01010"],"-":["00000","00000","00000","11111","00000","00000","00000"],_:["00000","00000","00000","00000","00000","00000","11111"],".":["00000","00000","00000","00000","00000","01100","01100"],":":["00000","01100","01100","00000","01100","01100","00000"],"=":["00000","00000","11111","00000","11111","00000","00000"],"/":["00001","00010","00010","00100","01000","01000","10000"],"?":["01110","10001","00001","00010","00100","00000","00100"]};function zW0($,_,F){let Z=Buffer.alloc(_*F*4);for(let K=0;K<_*F;K++){let j=K*4;Z[j]=18,Z[j+1]=21,Z[j+2]=27,Z[j+3]=255}let J=(K,j)=>{let V=Zp[K]??Zp["?"],O=Math.floor((F-14)/2);for(let W=0;W<7;W++)for(let G=0;G<5;G++){if(V[W][G]!=="1")continue;for(let D=0;D<2;D++)for(let w=0;w<2;w++){let L=j+G*2+w,C=O+W*2+D;if(L<0||L>=_||C<0||C>=F)continue;let B=(C*_+L)*4;Z[B]=235,Z[B+1]=238,Z[B+2]=244,Z[B+3]=255}}},X=12,Y=Math.floor((_-8)/X),H=$.toLowerCase().replace(/[^a-z0-9 #._:=/?-]/gu,"?").slice(0,Math.max(0,Y));for(let K=0;K{return})}}async function kW0($,_,F,Q){let Z=Q.generate??Cj;try{let J=await Z({model:_,prompt:$.prompt,...F.signal===void 0?{}:{signal:F.signal},...F.timeoutMs===void 0?{}:{timeoutMs:F.timeoutMs}},Q),X=Buffer.from(J.image.base64,"base64");return{index:$.index,id:$.id,label:$.label,prompt:$.prompt,status:"generated",bytes:X,mediaType:J.image.mediaType,requestId:J.requestId,warnings:J.warnings}}catch(J){return{index:$.index,id:$.id,label:$.label,prompt:$.prompt,status:"failed",error:J instanceof Error?J.message:String(J)}}}async function MW0($,_,F){let Q=Array($.length),Z=0;return await Promise.all(Array.from({length:Math.min(_,$.length)},async()=>{while(Z<$.length){let J=Z++;Q[J]=await F($[J])}})),Q}function Kp($){let _=$??ec[1];if(typeof _!=="string"||_.length>256||!/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/iu.test(_))d2("model must be a bounded Vercel AI Gateway provider/model id.");return _}function jp($){let _=$??w1.cellEdgeDefault;if(typeof _!=="number"||!Number.isInteger(_)||_w1.cellEdgeMax)d2(`cellEdge must be an integer from ${String(w1.cellEdgeMin)} through ${String(w1.cellEdgeMax)}.`);return _}function Vp($){if(typeof $!=="string"||$.length<1||$.length>4096||$.includes("\x00"))d2("outputDir must be a non-empty bounded local directory path.");return OW0($)}async function zj($,_={}){if(!gN($))d2("Gallery input must be an object.");let F=$,Q=Vp(F.outputDir),Z=Kp(F.model),J=jp(F.cellEdge),X=dE(F);await Jp(Q,{recursive:!0});let Y=await MW0(X.candidates,w1.concurrency,async(H)=>await kW0(H,Z,F,_));return await TC({candidates:Y,cellEdge:J,model:Z,outputDir:Q,plan:X})}async function TC($){let _=Vp($.outputDir),F=Kp($.model),Q=jp($.cellEdge),{plan:Z}=$;if(!gN(Z)||!Array.isArray(Z.candidates)||Z.candidates.length===0)d2("plan must be a non-empty gallery plan from planSlopcameraGallery.");let J=$.candidates;await Jp(_,{recursive:!0});let X=w1.labelHeight,Y=Q,H=Math.round(Q*Z.aspect[1]/Z.aspect[0]),K=H+X,j=Math.max(1,Math.ceil(Math.sqrt(J.length))),V=Math.ceil(J.length/j),O=w1.cellGap,W=j*Y+(j-1)*O,G=V*K+(V-1)*O;if(W*G>w1.galleryPixels)d2("Gallery sheet exceeds its pixel budget; reduce count or cellEdge.");let D=[],w=[];for(let A of J){let q=(A.index-1)%j,E=Math.floor((A.index-1)/j),M=q*(Y+O),T=E*(K+O),P=A.status==="failed"?`#${String(A.index)} ${A.label} failed`:`#${String(A.index)} ${A.label}`;if(w.push({input:await MY(zW0(P,Y,X),{raw:{width:Y,height:X,channels:4}}).png().toBuffer(),left:M,top:T}),A.status==="generated"){if(A.bytes===void 0||A.mediaType===void 0)d2("A generated gallery candidate requires its bytes and media type.");let I=A.path??RC(_,`candidate-${String(A.index).padStart(2,"0")}-${Yp(A.id)}.${UW0(A.mediaType)}`);if(A.path===void 0)await lE(I,A.bytes);let g=AC("sha256").update(A.bytes).digest("hex");if(A.sha256!==void 0&&A.sha256!==g)d2("A pre-published gallery candidate digest does not match its bytes.");let b,y;if(A.cellImage!==void 0){let p=AC("sha256").update(A.cellImage.bytes).digest("hex");if(A.cellImage.sha256!==void 0&&A.cellImage.sha256!==p)d2("A gallery cell image digest does not match its bytes.");let S=MY(A.cellImage.bytes,{limitInputPixels:w1.candidatePixels,failOn:"warning"}),i=await S.metadata();if(i.width===void 0||i.height===void 0||i.width>w1.candidateEdge||i.height>w1.candidateEdge||i.width*i.height>w1.candidatePixels)d2("A gallery cell image exceeds its raster bounds.");b=S,y={sha256:p,bytes:A.cellImage.bytes.byteLength,mediaType:A.cellImage.mediaType,...A.cellImage.path===void 0?{}:{path:A.cellImage.path}}}else{let p=MY(A.bytes,{limitInputPixels:w1.candidatePixels,failOn:"warning"}),S=await p.metadata();if(S.width===void 0||S.height===void 0||S.width>w1.candidateEdge||S.height>w1.candidateEdge||S.width*S.height>w1.candidatePixels)d2("A generated candidate exceeds its raster bounds.");b=p}let r=await b.resize(Y,H,{fit:"cover"}).png().toBuffer(),h=Z.tiled&&A.cellImage===void 0?await(async()=>{let p=await MY(r).resize(Math.ceil(Y/2),Math.ceil(H/2),{fit:"fill"}).png().toBuffer(),S=[0,Math.floor(Y/2)],i=[0,Math.floor(H/2)];return MY({create:{width:Y,height:H,channels:4,background:{r:0,g:0,b:0,alpha:0}}}).composite(i.flatMap((Y0)=>S.map((_0)=>({input:p,left:_0,top:Y0})))).png().toBuffer()})():r;w.push({input:h,left:M,top:T+X}),D.push({index:A.index,id:A.id,label:A.label,prompt:A.prompt,status:"generated",path:I,sha256:g,bytes:A.bytes.byteLength,mediaType:A.mediaType,...A.requestId===void 0?{}:{requestId:A.requestId},...A.warnings===void 0?{}:{warnings:A.warnings},...A.job===void 0?{}:{job:A.job},...Z.tiled&&A.cellImage===void 0?{tiled:!0}:{},...y===void 0?{}:{cellImage:y},...A.scene===void 0?{}:{scene:A.scene},cell:{x:M,y:T,width:Y,height:K}})}else{let I=A.bytes!==void 0||A.mediaType!==void 0||A.path!==void 0||A.sha256!==void 0,g;if(I){if(A.bytes===void 0||A.mediaType===void 0||A.path===void 0)d2("A failed gallery candidate artifact requires bytes, media type, and path.");let y=AC("sha256").update(A.bytes).digest("hex");if(A.sha256!==void 0&&A.sha256!==y)d2("A failed gallery candidate artifact digest does not match its bytes.");g={bytes:A.bytes.byteLength,mediaType:A.mediaType,path:A.path,sha256:y}}let b=Buffer.alloc(Y*H*4);for(let y=0;yA.status==="failed").length,U=RC(_,"receipt.json"),k={kind:$.receipt?.kind??"slopcamera.image-gallery",schemaVersion:1,subject:Z.subject,galleryKind:$.receipt===void 0?Z.kind:"scene",model:F,provider:$.receipt===void 0?"vercel-ai-gateway":"local",...$.receipt===void 0?{}:{baseSceneSha256:$.receipt.baseSceneSha256},cell:{width:Y,height:H,labelHeight:X},axes:Z.axes,candidates:D,counts:{requested:J.length,generated:J.length-z,failed:z},gallery:{path:C,sha256:B,bytes:L.byteLength,mediaType:"image/png",width:W,height:G},receiptPath:U,clientMaxRetries:0};if(await lE(U,`${JSON.stringify(k,null,2)} -`),z===J.length)throw new h1("GENERATION_FAILED",`Every gallery candidate failed; see ${U} for the retained attempt record.`);return k}function d($){throw new N("usage",$)}function A0($,_){let F={},Q=[],Z=!1;for(let J=0;J<$.length;J+=1){let X=$[J];if(Z||!X.startsWith("-")){Q.push(X);continue}if(X==="--"){Z=!0;continue}let Y=X.indexOf("="),H=Y===-1?X:X.slice(0,Y),K=Y===-1?void 0:X.slice(Y+1),j=_[H];if(j===void 0)d(`Unknown option: ${H}`);if(j==="flag"){if(K!==void 0)d(`${H} does not take a value.`);if(F[H]!==void 0)d(`Option may be specified only once: ${H}`);F[H]=!0;continue}let V=K??$[J+1];if(V===void 0||K===void 0&&V.startsWith("--"))d(`Option requires a value: ${H}`);if(K===void 0)J+=1;if(j==="value"){if(F[H]!==void 0)d(`Option may be specified only once: ${H}`);F[H]=V}else{let O=F[H];F[H]=O===void 0?[V]:[...wp(O,H),V]}}return{options:F,positionals:Q}}function wp($,_){if(!Array.isArray($)||!$.every((F)=>typeof F==="string"))d(`Internal parser error for ${_}.`);return $}function f($,_){let F=$.options[_];if(F===void 0)return;if(typeof F!=="string")d(`Internal parser error for ${_}.`);return F}function j3($,_){let F=$.options[_];if(F===void 0)return[];return wp(F,_)}function Q0($,_){return $.options[_]===!0}function R8($,_,F){if($===void 0)return F;if(!/^[1-9][0-9]*$/u.test($))d(`${_} must be a positive integer.`);let Q=Number($);if(!Number.isSafeInteger(Q))d(`${_} exceeds the safe integer range.`);return Q}function V3($,_){return $===void 0?void 0:R8($,_,1)}function vN($,_){if($===void 0)return;if(!/^(?:0|[1-9][0-9]*)$/u.test($))d(`${_} must be a non-negative integer.`);let F=Number($);if(!Number.isSafeInteger(F))d(`${_} exceeds the safe integer range.`);return F}function EC($,_,F){let Q=R8($,_,F);if(Q%2!==0)d(`${_} must be an even positive integer.`);return Q}function w2($,_,F){if($===void 0){if(F===void 0)d(`${_} is required.`);return F}if($.trim()===""||!Number.isFinite(Number($)))d(`${_} must be a finite number.`);return Number($)}function b6($,_,F,Q,Z){let J=w2($,_,Z);if(JQ)d(`${_} must be between ${F} and ${Q}.`);return J}function K_($,_,F,Q){return $===void 0?void 0:b6($,_,F,Q)}function rZ($,_,F){if($===void 0)return F;if($==="true")return!0;if($==="false")return!1;d(`${_} must be true or false.`)}function N5($,_,F,Q){if($===void 0){if(Q===void 0)d(`${_} is required.`);return Q}let Z=F.find((J)=>J===$);if(Z===void 0)d(`${_} must be one of: ${F.join(", ")}.`);return Z}function b0($,_,F){if($.positionals.length!==_)d(`Usage: ${F}`);return $.positionals}var B0={"--json":"flag"};function AW0($){let _=A0($,B0);return b0(_,0,"slopcamera capabilities [--json]"),{json:Q0(_,"--json"),kind:"capabilities"}}function RW0($){let _=A0($,B0);return b0(_,0,"slopcamera doctor [--json]"),{json:Q0(_,"--json"),kind:"doctor"}}function PC($,_,F,Q){let Z=f($,_),J=f($,F);if(Z!==void 0&&J!==void 0)d(`${_} and ${F} are mutually exclusive.`);if(Q.required&&Z===void 0&&J===void 0)d(`Exactly one of ${_} or ${F} is required.`);return{inline:Z,path:J}}function TW0($){let _=[],F=new Set;for(let Q of $){let Z=Q.indexOf("="),J=Z===-1?"":Q.slice(0,Z),X=Z===-1?"":Q.slice(Z+1);if(J!=="first"&&J!=="last"||X.trim()==="")d("--frame must use first= or last=.");if(F.has(J))d(`--frame ${J} may be specified only once.`);F.add(J),_.push({frameType:J,path:X})}return _}function qW0($){let _=$[0];if(_==="list"){let F=A0($.slice(1),{...B0,"--limit":"value","--provider":"value","--query":"value","--refresh":"flag","--type":"value"});return b0(F,0,"slopcamera ai models list [options]"),{json:Q0(F,"--json"),kind:"ai-models-list",limit:(()=>{let Q=R8(f(F,"--limit"),"--limit",100);if(Q>500)d("--limit must be at most 500.");return Q})(),modelType:N5(f(F,"--type"),"--type",["all","image","video","speech","transcription"],"all"),provider:f(F,"--provider"),query:f(F,"--query"),refresh:Q0(F,"--refresh")}}if(_==="show"){let F=A0($.slice(1),{...B0,"--refresh":"flag"}),[Q]=b0(F,1,"slopcamera ai models show [--refresh] [--json]");return{json:Q0(F,"--json"),kind:"ai-models-show",model:Q,refresh:Q0(F,"--refresh")}}d("Usage: slopcamera ai models [options]")}function EW0($){if($[0]!=="inspect")d("Usage: slopcamera ai provider-options inspect [--json]");let _=A0($.slice(1),B0),[F]=b0(_,1,"slopcamera ai provider-options inspect [--json]");return{json:Q0(_,"--json"),kind:"ai-provider-options-inspect",path:F}}function PW0($){if($[0]==="gallery")return IW0($.slice(1));if($[0]!=="generate")d("Usage: slopcamera ai image --model [options]");let _=A0($.slice(1),{...B0,"--allow-cloud-upload":"flag","--aspect-ratio":"value","--count":"value","--hosted":"flag","--image":"repeat","--mask":"value","--max-per-call":"value","--max-output-tokens":"value","--model":"value","--prompt":"value","--prompt-file":"value","--provider-options":"value","--seed":"value","--size":"value","--stop":"repeat","--temperature":"value","--timeout":"value"});b0(_,0,"slopcamera ai image generate --model [options]");let F=PC(_,"--prompt","--prompt-file",{required:!1}),Q=j3(_,"--image");if(Q.length>16)d("--image may be specified at most 16 times.");if(F.inline===void 0&&F.path===void 0&&Q.length===0)d("Image generation requires a prompt or at least one --image reference.");let Z=f(_,"--model");if(Z===void 0)d("--model is required.");let J=R8(f(_,"--count"),"--count",1);if(J>16)d("--count must be at most 16.");let X=V3(f(_,"--max-per-call"),"--max-per-call");if(X!==void 0&&X>16)d("--max-per-call must be at most 16.");if(X!==void 0&&X --model --output-dir [options]"),Q=f(_,"--model");if(Q===void 0)d("--model is required.");let Z=f(_,"--output-dir");if(Z===void 0||Z.trim()==="")d("--output-dir is required.");let J=f(_,"--kind");if(J!==void 0&&!K3.includes(J))d(`--kind must be one of: ${K3.join(", ")}.`);let X=V3(f(_,"--count"),"--count");if(X!==void 0&&X>w1.candidates)d(`--count must be at most ${w1.candidates}.`);let Y=V3(f(_,"--cell"),"--cell");if(Y!==void 0&&(Yw1.cellEdgeMax))d(`--cell must be between ${w1.cellEdgeMin} and ${w1.cellEdgeMax}.`);let H=f(_,"--candidates"),K=f(_,"--vary");if(H!==void 0&&(K!==void 0||X!==void 0))d("--candidates is mutually exclusive with --vary and --count.");let j=Q0(_,"--tile"),V=Q0(_,"--no-tile");if(j&&V)d("--tile and --no-tile are mutually exclusive.");let O=f(_,"--preview");if(O!==void 0&&O!=="probe")d("--preview must be probe.");if(O==="probe"&&!["texture","skybox","backdrop"].includes(J??"image"))d("--preview probe requires --kind texture, skybox, or backdrop.");return{candidatesFile:H,cell:Y,count:X,galleryKind:J,json:Q0(_,"--json"),kind:"ai-image-gallery",model:Q,outputDir:Z,preview:O,subject:F,tiled:j?!0:V?!1:void 0,timeout:f(_,"--timeout")??"10m",vary:K}}function bW0($){if($[0]!=="gallery")d("Usage: slopcamera ai scene gallery --variants --output-dir [options]");let _=A0($.slice(1),{...B0,"--camera":"value","--cell":"value","--output-dir":"value","--time-us":"value","--variants":"value"}),[F]=b0(_,1,"slopcamera ai scene gallery --variants --output-dir [options]"),Q=f(_,"--variants");if(Q===void 0)d("--variants is required.");let Z=f(_,"--output-dir");if(Z===void 0||Z.trim()==="")d("--output-dir is required.");let J=f(_,"--time-us"),X;if(J!==void 0){if(!/^\d+$/u.test(J)||!Number.isSafeInteger(Number(J)))d("--time-us must be a nonnegative integer microsecond time.");X=Number(J)}let Y=V3(f(_,"--cell"),"--cell");if(Y!==void 0&&(Yw1.cellEdgeMax))d(`--cell must be between ${w1.cellEdgeMin} and ${w1.cellEdgeMax}.`);return{camera:f(_,"--camera"),cell:Y,json:Q0(_,"--json"),kind:"ai-scene-gallery",outputDir:Z,scene:F,timeUs:X,variants:Q}}function SW0($){if($[0]!=="generate")d("Usage: slopcamera ai video generate --model [options]");let _=A0($.slice(1),{...B0,"--allow-cloud-upload":"flag","--aspect-ratio":"value","--count":"value","--duration":"value","--fps":"value","--frame":"repeat","--generate-audio":"value","--image":"value","--max-per-call":"value","--model":"value","--prompt":"value","--prompt-file":"value","--provider-options":"value","--reference":"repeat","--resolution":"value","--seed":"value","--timeout":"value"});b0(_,0,"slopcamera ai video generate --model [options]");let F=PC(_,"--prompt","--prompt-file",{required:!1}),Q=f(_,"--image"),Z=TW0(j3(_,"--frame")),J=j3(_,"--reference");if(J.length>32)d("--reference may be specified at most 32 times.");if(Z.length>0&&J.length>0)d("--frame and --reference are mutually exclusive because frame images take precedence in AI SDK video requests.");if(Q!==void 0&&Z.some((K)=>K.frameType==="first"))d("--image and --frame first are mutually exclusive because the first frame takes precedence.");if(Z.some((K)=>K.frameType==="last")&&Q===void 0&&!Z.some((K)=>K.frameType==="first"))d("--frame last requires --image or --frame first.");if(F.inline===void 0&&F.path===void 0&&Q===void 0&&Z.length===0&&J.length===0)d("Video generation requires a prompt, --image, --frame, or --reference.");let X=f(_,"--model");if(X===void 0)d("--model is required.");let Y=R8(f(_,"--count"),"--count",1);if(Y>8)d("--count must be at most 8.");let H=V3(f(_,"--max-per-call"),"--max-per-call");if(H!==void 0&&H>8)d("--max-per-call must be at most 8.");if(H!==void 0&&H [options]");let _=A0($.slice(1),{...B0,"--format":"value","--instructions":"value","--instructions-file":"value","--language":"value","--model":"value","--provider-options":"value","--speed":"value","--text":"value","--text-file":"value","--timeout":"value","--voice":"value"});b0(_,0,"slopcamera ai speech generate --model [options]");let F=PC(_,"--text","--text-file",{required:!0}),Q=PC(_,"--instructions","--instructions-file",{required:!1}),Z=f(_,"--model");if(Z===void 0)d("--model is required.");return{instructions:Q.inline,instructionsFile:Q.path,json:Q0(_,"--json"),kind:"ai-speech-generate",language:f(_,"--language"),model:Z,outputFormat:f(_,"--format"),providerOptions:f(_,"--provider-options"),speed:K_(f(_,"--speed"),"--speed",0.25,4),text:F.inline,textFile:F.path,timeout:f(_,"--timeout")??"5m",voice:f(_,"--voice")}}function yW0($){let _=A0($,{...B0,"--allow-cloud-audio-upload":"flag","--format":"value","--model":"value","--provider-options":"value","--timeout":"value"}),[F]=b0(_,1,"slopcamera ai transcribe --model --allow-cloud-audio-upload [options]"),Q=f(_,"--model");if(Q===void 0)d("--model is required.");return{allowCloudAudioUpload:Q0(_,"--allow-cloud-audio-upload"),format:N5(f(_,"--format"),"--format",["all","json","srt","text","vtt"],"all"),input:F,json:Q0(_,"--json"),kind:"ai-transcribe",model:Q,providerOptions:f(_,"--provider-options"),timeout:f(_,"--timeout")??"30m"}}function gW0($){let _=$[0];if(_==="status"){let F=A0($.slice(1),B0);return b0(F,0,"slopcamera credits status [--json]"),{kind:"credits-status",json:Q0(F,"--json")}}if(_==="topup"){let F=A0($.slice(1),{...B0,"--email":"value","--pack":"value"});b0(F,0,"slopcamera credits topup [--pack ] [--email
] [--json]");let Q=f(F,"--email");if(Q!==void 0&&(Q.length>320||/[\s\u0000-\u001f\u007f]/u.test(Q)))d("--email must be a nonempty email address without whitespace or control characters.");let Z=f(F,"--pack");if(Z!==void 0&&!/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(Z))d("--pack must be a pack id such as p10, p25, p50, or p100.");return{email:Q,json:Q0(F,"--json"),kind:"credits-topup",pack:Z}}if(_==="wait"){let F=A0($.slice(1),{...B0,"--timeout":"value"});return b0(F,0,"slopcamera credits wait [--timeout