@hraness/slopcamera 3.3.5 → 3.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/apps/desktop/application/operation.ts +1 -1
- package/apps/desktop/cli/commands.ts +22 -20
- package/apps/desktop/dist/cli/main.js +5 -5
- package/dist/cli.js +1 -1
- package/dist/{index-11cb717y.js → index-10bz03js.js} +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/skills/slopcamera/references/install.md +1 -1
- package/src/version.ts +1 -1
package/README.md
CHANGED
|
@@ -44,14 +44,14 @@ the rendered output with source, runtime requirements and reproduction steps.
|
|
|
44
44
|
|
|
45
45
|
## Install Slopcamera
|
|
46
46
|
|
|
47
|
-
Slopcamera v3.3.
|
|
47
|
+
Slopcamera v3.3.5 adds paid hosted image generation through Hraness Credits top-up (`slopcamera credits`, `ai image --hosted`), public hosted model discovery, and checked patent-style vector drawing sheets.
|
|
48
48
|
|
|
49
49
|
Install [Bun 1.3.14 or newer](https://bun.sh), then install the verified
|
|
50
|
-
[Slopcamera v3.3.
|
|
50
|
+
[Slopcamera v3.3.5 release](https://github.com/hraness/slopcamera/releases/tag/v3.3.5)
|
|
51
51
|
from its canonical archive:
|
|
52
52
|
|
|
53
53
|
```sh
|
|
54
|
-
bun add --global https://github.com/hraness/slopcamera/releases/download/v3.3.
|
|
54
|
+
bun add --global https://github.com/hraness/slopcamera/releases/download/v3.3.5/hraness-slopcamera-3.3.5.tgz
|
|
55
55
|
slopcamera skill install --target agents
|
|
56
56
|
```
|
|
57
57
|
|
|
@@ -4,7 +4,7 @@ import type { z } from "zod";
|
|
|
4
4
|
|
|
5
5
|
import type { ApplicationContext } from "./context";
|
|
6
6
|
|
|
7
|
-
export const SLOPCAMERA_APPLICATION_TOOL_VERSION = "slopcamera-3.3.
|
|
7
|
+
export const SLOPCAMERA_APPLICATION_TOOL_VERSION = "slopcamera-3.3.6" as const;
|
|
8
8
|
|
|
9
9
|
export const OPERATION_KINDS = [
|
|
10
10
|
"scene.audit",
|
|
@@ -362,7 +362,7 @@ import {
|
|
|
362
362
|
workflowRunStore,
|
|
363
363
|
} from "./workflow-runs";
|
|
364
364
|
|
|
365
|
-
export const SLOPCAMERA_VERSION = "3.3.
|
|
365
|
+
export const SLOPCAMERA_VERSION = "3.3.6";
|
|
366
366
|
|
|
367
367
|
// Legacy direct renders predate per-target output contracts. Keep them
|
|
368
368
|
// bounded generously enough for long-form production while preventing one
|
|
@@ -5722,26 +5722,28 @@ async function handleCreditsWait(
|
|
|
5722
5722
|
} catch (error) {
|
|
5723
5723
|
throw creditsErrorToCli(error);
|
|
5724
5724
|
}
|
|
5725
|
+
// The issuing poll reports state "consumed" alongside the one-time token,
|
|
5726
|
+
// so the token check must precede state matching.
|
|
5727
|
+
if (status.deviceToken !== undefined) {
|
|
5728
|
+
// The token is returned exactly once; persist before reporting.
|
|
5729
|
+
await store.writeDeviceToken(status.deviceToken);
|
|
5730
|
+
await store.clearPendingClaim();
|
|
5731
|
+
const view = {
|
|
5732
|
+
claimId: pending.claimId,
|
|
5733
|
+
configured: true,
|
|
5734
|
+
state: "paid" as const,
|
|
5735
|
+
next: ["slopcamera credits status", "slopcamera ai image generate --hosted --model <id> --prompt <text>"],
|
|
5736
|
+
};
|
|
5737
|
+
writeValue(context.io, command.json, view, () => [
|
|
5738
|
+
"paid\tcredits wallet is configured on this device",
|
|
5739
|
+
"",
|
|
5740
|
+
"Next:",
|
|
5741
|
+
" slopcamera credits status",
|
|
5742
|
+
" slopcamera ai image generate --hosted --model <id> --prompt <text>",
|
|
5743
|
+
].join("\n"));
|
|
5744
|
+
return;
|
|
5745
|
+
}
|
|
5725
5746
|
if (status.state === "paid") {
|
|
5726
|
-
if (status.deviceToken !== undefined) {
|
|
5727
|
-
// The token is returned exactly once; persist before reporting.
|
|
5728
|
-
await store.writeDeviceToken(status.deviceToken);
|
|
5729
|
-
await store.clearPendingClaim();
|
|
5730
|
-
const view = {
|
|
5731
|
-
claimId: pending.claimId,
|
|
5732
|
-
configured: true,
|
|
5733
|
-
state: "paid" as const,
|
|
5734
|
-
next: ["slopcamera credits status", "slopcamera ai image generate --hosted --model <id> --prompt <text>"],
|
|
5735
|
-
};
|
|
5736
|
-
writeValue(context.io, command.json, view, () => [
|
|
5737
|
-
"paid\tcredits wallet is configured on this device",
|
|
5738
|
-
"",
|
|
5739
|
-
"Next:",
|
|
5740
|
-
" slopcamera credits status",
|
|
5741
|
-
" slopcamera ai image generate --hosted --model <id> --prompt <text>",
|
|
5742
|
-
].join("\n"));
|
|
5743
|
-
return;
|
|
5744
|
-
}
|
|
5745
5747
|
await store.clearPendingClaim();
|
|
5746
5748
|
const view = {
|
|
5747
5749
|
claimId: pending.claimId,
|
|
@@ -1554,7 +1554,7 @@ ${H}`.trim();return{exitCode:Y,output:j}}async function wM($,_,F){IQ(F);let Q=aw
|
|
|
1554
1554
|
for (const url of urls.keys()) nativeRevokeUrl(url);
|
|
1555
1555
|
urls.clear(); liveBytes = 0;
|
|
1556
1556
|
}, { once: true }]);
|
|
1557
|
-
}`);return r50(_,"return securityViolations;","return securityViolations + (sparkWorkerFailure === null ? 0 : 1);")}var gg=rH.string().regex(/^[a-f0-9]{64}$/u),wg0=rH.strictObject({key:rH.string().min(1).max(512),sha256:gg}),r9=rH.strictObject({algorithm:rH.literal("sha256-merkle-v1"),leaves:rH.array(wg0).min(4).max(256).superRefine(($,_)=>{for(let F=1;F<$.length;F+=1)if($[F-1].key>=$[F].key)_.addIssue({code:"custom",message:"HTML-overlay integrity leaves must have unique ASCII-sorted keys.",path:[F,"key"]})}),rootSha256:gg,runtimeSha256:gg,schemaVersion:rH.literal(1)}),d8=Object.freeze({browser:"playwright-chromium",browserVersion:Gg0.version,browserContext:Object.freeze({acceptDownloads:!1,colorScheme:"light",locale:"en-US",offline:!0,permissions:Object.freeze([]),reducedMotion:"no-preference",serviceWorkers:"block",timezoneId:"UTC"}),contentSecurityPolicy:Object.freeze(["default-src 'none'","base-uri 'none'","connect-src 'none'","font-src https://slopcamera-overlay.invalid data:","form-action 'none'","frame-src 'none'","img-src https://slopcamera-overlay.invalid data:","media-src https://slopcamera-overlay.invalid data:","object-src 'none'","script-src 'unsafe-inline' https://slopcamera-overlay.invalid","style-src 'unsafe-inline'","worker-src 'none'"]),documentUrl:"https://slopcamera-overlay.invalid/slopcamera-overlay/document",environment:Object.freeze({fixed:Object.freeze({LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",PATH:"/usr/bin:/bin",TZ:"UTC"}),inherited:Object.freeze([]),privateDirectories:Object.freeze(["HOME","TMPDIR"])}),launch:Object.freeze({args:Object.freeze(["--disable-background-networking","--disable-breakpad","--disable-component-update","--disable-default-apps","--disable-domain-reliability","--disable-extensions","--disable-features=Translate,MediaRouter,OptimizationHints","--disable-quic","--disable-sync","--enable-unsafe-swiftshader","--force-webrtc-ip-handling-policy=disable_non_proxied_udp","--metrics-recording-only","--mute-audio","--no-default-browser-check","--no-first-run","--no-proxy-server","--use-angle=swiftshader"]),headless:!0,libraryArgs:Object.freeze({vgpu:Object.freeze(["--enable-unsafe-webgpu","--use-webgpu-adapter=swiftshader"])})}),routing:Object.freeze({allowedOrigin:"https://slopcamera-overlay.invalid",declaredResourcesOnly:!0,remoteNetworkDenied:!0}),runtimeSnapshot:Object.freeze({macosAnchor:"/private/tmp",macosAnchorPolicy:"physical-root-owned-sticky-direct-child",cleanupIdentity:"container-direct-children-and-complete-runtime-manifest",copyBufferBytes:4194304,filesystemGuard:"anchor-basename-and-recursive-parent-watch-with-path-identities",orphanRecovery:"active-to-released-lease-last-atomic-quarantine-double-open-proof",verifiedMacosFilesystemFlags:"user-immutable-recursive"}),schemaVersion:1,screenshot:Object.freeze({omitBackground:!0,scale:"css",type:"png"})}),Dg0=Object.freeze({...d8.launch,args:Object.freeze([...d8.launch.args.filter(($)=>$!=="--enable-unsafe-swiftshader"&&$!=="--use-angle=swiftshader"),"--use-angle=metal","--disable-software-rasterizer"])});function Lg0($){if($===void 0)return d8;let _=L6.parse($);return Object.freeze({...d8,contentSecurityPolicy:_==="three-spark-webgl2-hardware-v1"?Object.freeze(d8.contentSecurityPolicy.map((F)=>{if(F==="worker-src 'none'")return"worker-src blob:";if(F==="connect-src 'none'")return"connect-src https://slopcamera-overlay.invalid data:";if(F.startsWith("script-src "))return`${F} 'wasm-unsafe-eval'`;return F})):d8.contentSecurityPolicy,executionProfile:_,launch:Dg0,gpu:Object.freeze({admission:"matching-active-webgl2-and-cdp-angle-metal-v1",capture:"host-held-native-context-health-before-and-after-every-screenshot",fallback:"reject-software-or-unknown",platform:"darwin",receipt:"bounded-context-device-driver-os-evidence-per-batch"}),schemaVersion:2})}function LM($,_=[]){let F=Lg0($),Z=PQ.parse(_).filter((J)=>J.transport==="fetch").map((J)=>`${d8.routing.allowedOrigin}${N6(J)}`);if(Z.length===0||!F.contentSecurityPolicy.includes("connect-src 'none'"))return F;return Object.freeze({...F,contentSecurityPolicy:Object.freeze(F.contentSecurityPolicy.map((J)=>J==="connect-src 'none'"?`connect-src ${Z.join(" ")}`:J)),schemaVersion:3})}function Jw($,_){if(_===void 0)return;L6.parse(_);let F=_==="three-webgl2-hardware-v1"?["three"]:["@sparkjsdev/spark","three","three/addons/postprocessing/Pass.js"];if(R([...$].sort())!==R(F))throw Error("Hardware execution profile requires its exact approved scene library set.")}function Zw($){return Og0("sha256").update($).digest("hex")}function Cg0($,_){return Zw(R({domain:"slopcamera.html-overlay-integrity-leaf/v1",key:$,value:_}))}function Bg0($){let _=$.map((F)=>Zw(["slopcamera.html-overlay-integrity-node/v1","leaf",F.key,F.sha256].join("\x00")));while(_.length>1){let F=[];for(let Q=0;Q<_.length;Q+=2){let Z=_[Q],J=_[Q+1]??Z;F.push(Zw(["slopcamera.html-overlay-integrity-node/v1","branch",Z,J].join("\x00")))}_=F}return _[0]}function o9($,_,F){let Q=w6.parse($);Jw(Q.libraries,F);let Z=o$.parse(_),J=Q.libraries.map(qQ),X=nk(Q.libraries),Y=Yg({canvas:Q.canvas,parameters:Q.parameters,resources:Q.resources,seed:Q.seed,timing:Q.timing}),H=F==="three-spark-webgl2-hardware-v1"?o50(Y):Y,K=Zw(Buffer.from(H,"utf8")),V=[{key:"authoring-config",value:{canvas:Q.canvas,kind:Q.kind,parameters:Q.parameters,schemaVersion:Q.schemaVersion,seed:Q.seed,timing:Q.timing}},{key:"browser-runtime",value:Z},{key:"renderer-contract",value:LM(F,Q.resources)},{key:"document",value:{bytes:Buffer.byteLength(Q.html,"utf8"),sha256:Zw(Buffer.from(Q.html,"utf8"))}},{key:"import-map",value:X},{key:"runtime",value:{bytes:Buffer.byteLength(H,"utf8"),sha256:K}},...J.map((W)=>({key:`library:${W.specifier}`,value:W})),...Q.resources.map((W)=>({key:`resource:${W.name}`,value:W}))].map((W)=>({key:W.key,sha256:Cg0(W.key,W.value)})).sort((W,G)=>W.key<G.key?-1:W.key>G.key?1:0),O=r9.parse({algorithm:"sha256-merkle-v1",leaves:V,rootSha256:Bg0(V),runtimeSha256:K,schemaVersion:1});return Object.freeze({importMap:X,integrity:Object.freeze(O),libraryLocks:Object.freeze(J),runtimeSource:H})}var LV="slopcamera-3.3.5",Xw=["scene.audit","scene.inspect","scene.patch","scene.evaluate","scene.render","scene.render-audit","scene.review","scene.direction.check","scene.direction.compile","scene.direction.gallery","scene.effects.check","scene.effects.plan","scene.behavior.check","scene.behavior.bake","scene.behavior.gallery","scene.behavior.audit","scene.temporal-audit","slopcamera.studio.run","spatial.project.snapshot","spatial.project.migrate","spatial.project.patch","spatial.project.restore","spatial.project.add-shot","spatial.project.add-candidate","spatial.project.select-candidate","spatial.project.reconcile","project.snapshot","analysis.project-inactivity","analysis.faces","analysis.music","analysis.scenes","analysis.project-auto-zooms","derive.edit-batch","project.commit-edits","derive.follow-faces","edit.create-revision","edit.create-candidate-revision","edit.bind-candidate-revision","edit.freeze-revision","iteration.create-candidate","iteration.create-matrix","iteration.select","project.promote-selection","render.bind-candidate-output","render.project-plan","render.project","render.materialize-selection","media.ingest","media.overlay","media.html-overlay","media.audio-effects","media.color-grade","gateway.image","gateway.video","gateway.speech","gateway.transcription","slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.vectorize","slopcamera.image.generate"],Yw=["cpu","local-io","ffmpeg","vision","whisper","network","paid-call","project-render","project-publication","output-publication","capture-device","browser"];import{isAbsolute as zg0,relative as vg,resolve as i50}from"path";import{z as v1}from"zod";var Ug0=v1.strictObject({path:L0}),oH=536870912,CM=v1.union([Ug0,NO,q0]),BM=v1.strictObject({endBehavior:v1.enum(["hide","loop","freeze-end"]).default("hide"),playbackRate:v1.number().finite().positive().max(64).default(1),sourceInUs:v1.number().int().safe().nonnegative().default(0),sourceOutUs:v1.number().int().safe().positive().optional()}).prefault({}),xg=v1.strictObject({artifact:q0,id:v1.string().min(1).max(256),provider:v1.enum(["apple-emoji-pack","brand-catalog"]),selector:CP,variant:v1.enum(["color","duotone"])}),kg0=v1.discriminatedUnion("kind",[v1.strictObject({artifact:CM,kind:v1.literal("image")}),v1.strictObject({artifact:CM,kind:v1.literal("svg")}),v1.strictObject({artifact:CM,kind:v1.literal("gif"),playback:BM}),v1.strictObject({artifact:CM,audioPolicy:pC.default({kind:"mute"}),kind:v1.literal("video"),playback:BM}),v1.strictObject({kind:v1.literal("emoji"),provider:v1.enum(["apple-emoji-pack","brand-catalog","auto"]).default("auto"),query:v1.string().min(1).max(256),resolved:xg.optional(),variant:v1.enum(["color","duotone"]).optional()})]),a50=v1.discriminatedUnion("kind",[v1.strictObject({artifact:q0,kind:v1.literal("image")}),v1.strictObject({artifact:q0,kind:v1.literal("svg")}),v1.strictObject({artifact:q0,kind:v1.literal("gif"),playback:BM}),v1.strictObject({artifact:q0,audioPolicy:pC,kind:v1.literal("video"),playback:BM}),v1.strictObject({kind:v1.literal("emoji"),provider:v1.enum(["apple-emoji-pack","brand-catalog","auto"]),query:v1.string().min(1).max(256),resolved:xg,variant:v1.enum(["color","duotone"]).optional()})]),hg=v1.strictObject({anchor:zP.default("center"),blendMode:v1.enum(["normal","addition","darken","lighten","multiply","overlay","screen"]).default("normal"),crop:kP.default({kind:"none"}),entrance:nN.default({kind:"none"}),exit:nN.default({kind:"none"}),fit:v1.enum(["contain","cover","fill"]).default("fill"),mask:MP.default({kind:"none"}),motion:AP.default({kind:"none"}),opacity:v1.number().finite().min(0).max(1).default(1),position:p_.default({x:0,y:0}),rotationDegrees:v1.number().finite().min(-3600).max(3600).default(0),scale:v1.number().finite().positive().max(128).default(1),size:UP.default({kind:"intrinsic"}),zIndex:v1.number().int().safe().default(0)}).prefault({}),iH=v1.strictObject({capabilityBindings:p4.optional(),identityKey:v1.string().min(1).max(128).optional(),layout:hg,project:K2,range:m0,source:kg0}),mg=iH.extend({source:a50}).strict(),KX=v1.strictObject({artifact:q0,created:v1.boolean(),operation:C5,receipt:q0}),ug=v1.strictObject({artifact:q0,createdAt:v1.string().datetime({offset:!0}),exactInputSha256:x,ffprobeVersion:v1.string().min(1).max(256).nullable(),kind:v1.union([v1.literal("slopcamera.local-overlay-preparation-receipt"),v1.literal("studio.local-overlay-preparation-receipt")]),operationSha256:x,overlayId:v1.string().min(1).max(128),projectGenerationSha256:x,projectId:K2,schemaVersion:v1.literal(1)});function Mg0($){let _=$.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test(_))return{kind:"id",value:_};if([...$].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test($))return{kind:"unicode",value:$};return{kind:"name",value:$}}function Ag0($){if(!("bytes"in $))return $;return q0.parse({bytes:$.bytes,path:$.path,sha256:$.sha256})}function t50($){return $.kind==="image"||$.kind==="gif"||$.kind==="video"?["ffprobe"]:[]}async function Rg0($,_,F,Q){let Z=await Q($.paths.repositoryRoot,_.query,_.variant,_.provider),J=vg($.paths.repositoryRoot,Z.path),X=await r1($,{path:J},F,oH);if(X.artifact.sha256!==Z.sha256)throw new N("conflict","Resolved emoji bytes disagree with the checked emoji catalog.");let Y=xg.parse({artifact:X.artifact,id:Z.id,provider:Z.provider,selector:Mg0(_.query),variant:Z.variant});if(_.resolved!==void 0&&R(_.resolved)!==R(Y))throw new N("conflict","The checked emoji asset changed after exact node planning.");return a50.parse({..._,resolved:Y})}async function lg($,_,F,Q={}){let Z=iH.parse(_),J=t50(Z.source),X=Z.source.kind==="emoji"?Rg0($,Z.source,F,Q.resolveEmoji??wV):r1($,Ag0(Z.source.artifact),F,oH).then((K)=>({...Z.source,artifact:K.artifact})),[Y,H]=await Promise.all([X,L5($,J,Z.capabilityBindings)]);return mg.parse({...Z,capabilityBindings:H,source:Y})}function Tg0($,_){let F=i50($,_),Q=vg(i50($),F);if(Q===""||Q.startsWith("..")||zg0(Q))throw new N("unsafe-path","Prepared overlay asset escaped its project bundle.");return F}function qg0($,_,F){let Q=BP.parse(_),Z={bytes:Q.asset.bytes,mediaType:Q.asset.mediaType,sha256:Q.asset.sha256},J=Q.kind==="image"||Q.kind==="svg"?{asset:Z,kind:Q.kind}:Q.kind==="emoji"?{asset:Z,kind:Q.kind,provider:Q.provider,selector:Q.selector}:{asset:Z,audioPolicy:Q.audioPolicy,kind:Q.kind,playback:Q.playback};return`overlay_${m({domain:"studio.media-overlay-operation/v1",identityKey:$.identityKey??null,intrinsicSize:F,layout:$.layout,project:$.project,range:$.range,source:J}).slice(0,32)}`}function Eg0($={}){let _=$.ingestFile??HM,F=$.ingestEmoji??KM,Q=$.inspectPng??sH,Z=$.inspectSvg??HX,J=$.probe??UQ,X=$.resolveEmoji??wV;return{inputSchema:iH,inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",lifecycle:{kind:"local-artifact",execute:async(Y,H)=>{a(Y.abortSignal);let K=await lg(Y.application,H,Y.abortSignal,{resolveEmoji:X}),j=t50(K.source);await s9(Y,Y.application,K.capabilityBindings,j);let V=K.capabilityBindings??await XZ(Y.application,j),O=await n2(Y.application,K.project);if(m8(Y.expectedProjectGeneration,O.generation),K.range.endUs>O.plan.timelineDurationUs)throw new N("usage","Overlay range exceeds the project timeline.");let W=o6(r6(O.plan),K.range).reduce((C,B)=>C+B.output.endUs-B.output.startUs,0);if(W<=0)throw new N("conflict","Overlay range has no visible kept output time.");let G=K.source.kind==="emoji"?void 0:await r1(Y.application,K.source.artifact,Y.abortSignal,oH),D=K.source.kind==="emoji"?K.source:void 0,w=D===void 0?void 0:await X(Y.application.paths.repositoryRoot,D.query,D.variant,D.provider);if(w!==void 0&&D!==void 0&&(w.id!==D.resolved.id||w.provider!==D.resolved.provider||w.variant!==D.resolved.variant||w.sha256!==D.resolved.artifact.sha256))throw new N("conflict","Resolved emoji changed immediately before preparation.");let L=await $5(Y);try{await Y.workflow?.beforePublication(),a(Y.abortSignal);let C=w===void 0?await _(O.openProject.directory.path,G.absolutePath,K.source.kind):await F(O.openProject.directory.path,w),B=G?.artifact??D.resolved.artifact;if(C.bytes!==B.bytes||C.sha256!==B.sha256||C.provenance.sourceSha256!==B.sha256)throw new N("conflict","Prepared overlay bytes disagree with the exact bound source.");let z=Tg0(O.openProject.directory.path,C.path),U=(await r1(Y.application,{path:vg(Y.application.paths.repositoryRoot,z)},Y.abortSignal,oH)).artifact;if(U.bytes!==C.bytes||U.sha256!==C.sha256)throw new N("conflict","Prepared project asset disagrees with its published bytes.");let k=C.mediaType==="image/svg+xml"?{...await Z(z),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:K.source.kind==="emoji"?{...await Q(z),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await J(Z5(V,"ffprobe"),new J8(l8(Y.application,V),Y.abortSignal),z),A={height:"pixelHeight"in k?k.pixelHeight:k.height,width:"pixelWidth"in k?k.pixelWidth:k.width},q={bytes:C.bytes,mediaType:C.mediaType,path:C.path,provenance:C.provenance,sha256:C.sha256},E;if(K.source.kind==="image"||K.source.kind==="svg")E={asset:q,kind:K.source.kind};else if(K.source.kind==="emoji")E={asset:q,kind:"emoji",provider:K.source.resolved.provider,selector:K.source.resolved.selector};else{if(k.durationUs===null||k.durationUs<=0)throw new N("invalid-data","Animated overlay media must report a positive duration.");let g=DV({mediaDurationUs:k.durationUs,outputDurationUs:W,playbackRate:K.source.playback.playbackRate,sourceInUs:K.source.playback.sourceInUs,sourceOutUs:K.source.playback.sourceOutUs}),b={audioEndUs:k.audioEndUs,audioStartUs:k.audioStartUs,audioStreamIndex:k.audioStreamIndex,endBehavior:K.source.playback.endBehavior,playbackRate:K.source.playback.playbackRate,streamStartUs:k.videoStartUs,videoStreamIndex:k.videoStreamIndex,...g};if(K.source.kind==="gif")E={asset:q,audioPolicy:{kind:"mute"},kind:"gif",playback:b};else{if(K.source.audioPolicy.kind!=="mute"&&!k.hasAudio)throw new N("conflict","The selected video overlay audio policy requires an audio stream.");E={asset:q,audioPolicy:K.source.audioPolicy,kind:"video",playback:b}}}let M=C5.parse({...K.layout,coordinateSpace:"output-pixels",intrinsicSize:A,overlayId:qg0(K,E,A),range:K.range,source:E}),T=ug.parse({artifact:U,createdAt:Y.application.clock.now().toISOString(),exactInputSha256:m(K),ffprobeVersion:j.length===0?null:n9(V,"ffprobe"),kind:"slopcamera.local-overlay-preparation-receipt",operationSha256:m(M),overlayId:M.overlayId,projectGenerationSha256:O.generation.generationSha256,projectId:O.project.projectId,schemaVersion:1}),P=await G_({context:Y,receipt:T,workspace:L}),I=KX.parse({artifact:U,created:C.created,operation:M,receipt:P});return await h5(Y,{inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",outputSchemaId:"slopcamera.operation.media.overlay.output/v1",version:1},I),I}finally{await L.dispose()}}},outputSchema:KX,outputSchemaId:"slopcamera.operation.media.overlay.output/v1",policy:{cache:"exact-run",cancellable:!0,effect:"local-derived-write",maxDurationMs:3600000,maxFanOut:0,maxInputBytes:262144,maxOutputBytes:2097152,preparation:["project-state","local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(Y)=>Y.receipt.path,summarize:(Y)=>({fields:{bytes:Y.artifact.bytes,created:Y.created,kind:Y.operation.source.kind,overlayId:Y.operation.overlayId,receipt:Y.receipt.path,sha256:Y.artifact.sha256},kind:"media.overlay"}),version:1}}var e50=Eg0();var zM=2097152,UM=134217728,pg=536870912,cg=["ffmpeg","ffprobe","html-browser"],yg0=s4.union([GV,s4.strictObject({path:L0}),q0]),gg0=s4.union([GV,q0]),vg0=s4.union([b5,NO]),xg0=G6.omit({bytes:!0,sha256:!0}).extend({artifact:vg0}).strict(),hg0=G6.extend({artifact:q0}).strict(),Hw=s4.strictObject({canvas:HZ,capabilityBindings:p4.optional(),document:yg0,identityKey:s4.string().min(1).max(128).optional(),layout:hg,libraries:TQ.default([]),parameters:ZX.default({}),project:K2,range:m0,resources:s4.array(xg0).max(64).default([]),seed:s4.number().int().min(0).max(4294967295).default(0),timing:BF}),sg=Hw.omit({document:!0,resources:!0}).extend({document:gg0,resources:s4.array(hg0).max(64)}).strict(),ng=s4.strictObject({artifact:q0,browserVersion:s4.string().min(1).max(512),createdAt:s4.string().datetime({offset:!0}),executionIntegrity:r9.optional(),exactInputSha256:x,ffmpegVersion:s4.string().min(1).max(512),ffprobeVersion:s4.string().min(1).max(512),frameCount:s4.number().int().safe().positive(),kind:s4.union([s4.literal("slopcamera.html-overlay-preparation-receipt"),s4.literal("studio.html-overlay-preparation-receipt")]),libraryLocks:_g,libraryLocksSha256:x,operationSha256:x,overlayId:s4.string().min(1).max(128),projectGenerationSha256:x,projectId:K2,schemaVersion:s4.literal(1)}),_$0=KX;function mg0($){if(!("mediaType"in $.artifact))return $.artifact;if($.artifact.mediaType!==$.mediaType)throw new N("invalid-data",`HTML overlay resource ${$.name} declares ${$.mediaType} but its generated artifact is ${$.artifact.mediaType}.`);return q0.parse({bytes:$.artifact.bytes,path:$.artifact.path,sha256:$.artifact.sha256})}async function ug0($,_,F){if("html"in _)return _;return(await r1($,_,F,zM)).artifact}function lg0($,_){return o6(r6($),_).reduce((F,Q)=>F+Q.output.endUs-Q.output.startUs,0)}async function rg($,_,F){let Q=Hw.parse(_),[Z,J,X]=await Promise.all([ug0($,Q.document,F),Promise.all(Q.resources.map(async(K)=>({...K,artifact:(await r1($,mg0(K),F,UM)).artifact}))),L5($,cg,Q.capabilityBindings)]),Y=PQ.parse(J.map(({artifact:K,...j})=>({...j,bytes:K.bytes,sha256:K.sha256}))),H=new Map(J.map((K)=>[K.name,K.artifact]));return sg.parse({...Q,capabilityBindings:X,document:Z,resources:Y.map((K)=>({...K,artifact:H.get(K.name)}))})}function dg0($){let _;try{_=new TextDecoder("utf-8",{fatal:!0}).decode($)}catch{throw new N("invalid-data","The HTML overlay document must be valid UTF-8.")}if(_.trim()==="")throw new N("invalid-data","The HTML overlay document is empty.");return _}async function cg0($,_){let F=await bg0($,$$0.O_RDONLY|($$0.O_NOFOLLOW??0));try{let Q=await F.stat();if(!Q.isFile()||Q.size<=0)throw new N("invalid-data","Rendered HTML overlay is empty.");let Z=Pg0("sha256"),J=Buffer.allocUnsafe(1048576),X=0;while(X<Q.size){a(_);let H=await F.read(J,0,Math.min(J.byteLength,Q.size-X),X);if(H.bytesRead===0)break;Z.update(J.subarray(0,H.bytesRead)),X+=H.bytesRead}let Y=await F.stat();if(X!==Q.size||Y.dev!==Q.dev||Y.ino!==Q.ino||Y.size!==Q.size||Y.mtimeMs!==Q.mtimeMs||Y.ctimeMs!==Q.ctimeMs)throw new N("conflict","Rendered HTML overlay changed while it was being verified.");return Z.digest("hex")}finally{await F.close()}}var pg0=s4.object({streams:s4.array(s4.object({codec_name:s4.string(),height:s4.number().int().positive(),pix_fmt:s4.string(),width:s4.number().int().positive()})).min(1)});async function sg0($,_,F,Q,Z){let J=await new J8(l8($,_),Z).run([Z5(_,"ffprobe"),"-v","error","-select_streams","v:0","-show_entries","stream=codec_name,pix_fmt,width,height","-of","json",F],{maxOutputBytes:65536,stdin:"ignore",timeoutMs:30000});if(J.exitCode!==0)throw new N("invalid-data","Rendered HTML overlay could not be inspected as an alpha video.");let X;try{X=JSON.parse(J.stdout)}catch{throw new N("invalid-data","Rendered HTML overlay inspection returned invalid JSON.")}let Y=pg0.parse(X).streams[0];if(Y.codec_name!=="qtrle"||Y.pix_fmt!=="argb"||Y.width!==Q.width||Y.height!==Q.height)throw new N("invalid-data","Rendered HTML overlay must be a canvas-sized qtrle/argb alpha video.",{stream:Y})}function ng0($,_,F){return`overlay_${m({assetSha256:F,authoring:_,domain:"studio.media-html-overlay-operation/v1",identityKey:$.identityKey??null,layout:$.layout,project:$.project,range:$.range}).slice(0,32)}`}function og($={}){let _=$.ingest??f50,F=$.probe??UQ,Q=$.bindBrowserRuntime??i$,Z=$.toolVersion??LV;return{inputSchema:Hw,inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",lifecycle:{kind:"local-artifact",execute:async(J,X)=>{a(J.abortSignal);let Y=await rg(J.application,X,J.abortSignal);await s9(J,J.application,Y.capabilityBindings,cg);let H=Y.capabilityBindings??await XZ(J.application,cg),K=J.application.htmlOverlayRenderer;if(K===void 0)throw new N("unavailable","This Slopcamera host does not provide an HTML-overlay browser renderer.");let j=await n2(J.application,Y.project);if(m8(J.expectedProjectGeneration,j.generation),Y.range.endUs>j.plan.timelineDurationUs)throw new N("usage","HTML overlay range exceeds the project timeline.");let V=lg0(j.plan,Y.range);if(V<=0)throw new N("conflict","HTML overlay range has no visible kept output time.");if(Y.timing.durationUs!==V)throw new N("conflict","HTML overlay timing duration must equal the range's visible output duration.",{actualDurationUs:Y.timing.durationUs,expectedDurationUs:V});let[O,W]=await Promise.all(["html"in Y.document?Promise.resolve(Y.document.html):C4(J.application,Y.document,J.abortSignal,zM).then((L)=>dg0(L.data)),Promise.all(Y.resources.map(async(L)=>({...L,absolutePath:(await r1(J.application,L.artifact,J.abortSignal,UM)).absolutePath})))]),G=w6.parse({canvas:Y.canvas,html:O,kind:"slopcamera.html-overlay",libraries:Y.libraries,parameters:Y.parameters,resources:W.map((L)=>({bytes:L.bytes,mediaType:L.mediaType,name:L.name,sha256:L.sha256,...L.transport===void 0?{}:{transport:L.transport},urlPath:L.urlPath})),schemaVersion:1,seed:Y.seed,timing:Y.timing}),D=await $5(J),w=await Ig0(dg(D.path,"html-overlay-"));try{let L=await Q(m5(H,"html-browser"),J.abortSignal),C=o9(G,L).integrity,B=await K.renderFrames({authoring:G,browserRuntime:L,outputDirectory:w,resources:W},J.abortSignal),z=r9.parse(B.executionIntegrity);if(m(z)!==m(C))throw new N("conflict","HTML-overlay renderer returned integrity evidence that does not match the planned browser execution.");let U=iG.parse(B.libraryLocks),k=G.libraries.map(qQ);if(m(U)!==m(k))throw new N("conflict","HTML-overlay renderer returned library locks that do not exactly match the authoring selection.");let A=k_(G.timing);if(B.frameCount!==A)throw new N("conflict","HTML-overlay renderer returned an unexpected frame count.");let q=dg(w,"overlay.mov"),E=[Z5(H,"ffmpeg"),"-hide_banner","-loglevel","error","-nostdin","-n","-framerate",String(G.timing.fps),"-start_number","0","-i",B.framePattern,"-frames:v",String(B.frameCount),"-an","-c:v","qtrle","-pix_fmt","argb","-movflags","+faststart",q],M=await new J8(l8(J.application,H),J.abortSignal).run(E,{cwd:w,maxOutputBytes:1048576,stdin:"ignore",timeoutMs:3600000});if(M.exitCode!==0)throw new N("invalid-data",`FFmpeg could not encode the HTML overlay: ${M.stderr.slice(0,2000)}`);await sg0(J.application,H,q,G.canvas,J.abortSignal);let T=await cg0(q,J.abortSignal);await J.workflow?.beforePublication(),a(J.abortSignal);let P=await _(j.openProject.directory.path,{command:E,generator:"slopcamera-html-overlay",generatorVersion:Z,path:q,sourceSha256:T}),I=dg(j.openProject.directory.path,P.path),g=(await r1(J.application,{path:fg0(J.application.paths.repositoryRoot,I)},J.abortSignal,pg)).artifact,b=await F(Z5(H,"ffprobe"),new J8(l8(J.application,H),J.abortSignal),I);if(b.durationUs===null||b.durationUs<=0||b.hasAudio||b.pixelWidth!==G.canvas.width||b.pixelHeight!==G.canvas.height)throw new N("invalid-data","Generated HTML overlay has invalid duration, dimensions, or audio streams.");let y=DV({mediaDurationUs:b.durationUs,outputDurationUs:V,playbackRate:1,sourceInUs:0,sourceOutUs:void 0}),r={asset:{bytes:P.bytes,mediaType:P.mediaType,path:P.path,provenance:P.provenance,sha256:P.sha256},audioPolicy:{kind:"mute"},kind:"video",playback:{audioEndUs:null,audioStartUs:0,audioStreamIndex:null,endBehavior:"hide",playbackRate:1,streamStartUs:b.videoStartUs,videoStreamIndex:b.videoStreamIndex,...y}},h=C5.parse({...Y.layout,coordinateSpace:"output-pixels",intrinsicSize:{height:G.canvas.height,width:G.canvas.width},overlayId:ng0(Y,G,g.sha256),range:Y.range,source:r}),p=ng.parse({artifact:g,browserVersion:n9(H,"html-browser"),createdAt:J.application.clock.now().toISOString(),executionIntegrity:z,exactInputSha256:m(Y),ffmpegVersion:n9(H,"ffmpeg"),ffprobeVersion:n9(H,"ffprobe"),frameCount:B.frameCount,kind:"slopcamera.html-overlay-preparation-receipt",libraryLocks:U,libraryLocksSha256:m(U),operationSha256:m(h),overlayId:h.overlayId,projectGenerationSha256:j.generation.generationSha256,projectId:j.project.projectId,schemaVersion:1}),S=await G_({context:J,receipt:p,workspace:D}),i=KX.parse({artifact:g,created:P.created,operation:h,receipt:S});return await h5(J,{inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",version:1},i),i}finally{await Sg0(w,{force:!0,recursive:!0}),await D.dispose()}}},outputSchema:KX,outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",policy:{cache:"exact-run",cancellable:!0,effect:"local-derived-write",maxDurationMs:3600000,maxFanOut:0,maxInputBytes:3145728,maxOutputBytes:2097152,preparation:["project-state","local-media"],resources:[{amount:1,resource:"browser"},{amount:1,resource:"cpu"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"local-io"},{amount:1,resource:"network"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(J)=>J.receipt.path,summarize:(J)=>({fields:{bytes:J.artifact.bytes,created:J.created,kind:"html",overlayId:J.operation.overlayId,receipt:J.receipt.path,sha256:J.artifact.sha256},kind:"media.html-overlay"}),version:1}}var sL1=og();var og0=["media.ingest","media.html-overlay","media.overlay","media.audio-effects","media.color-grade"],$C1=rg0.enum(og0);async function F$0($,_,F,Q=new AbortController().signal){switch(_){case"media.ingest":return await T40($,OV.parse(F),Q);case"media.overlay":return await lg($,iH.parse(F),Q);case"media.html-overlay":return await rg($,Hw.parse(F),Q);case"media.audio-effects":return await B40($,WV.parse(F),Q);case"media.color-grade":return await k40($,NV.parse(F),Q)}}import{z as Kw}from"zod";import{lstat as _v0,realpath as J$0}from"fs/promises";import{isAbsolute as Fv0,join as Qv0,relative as Zv0,sep as Jv0}from"path";import{z as bQ}from"zod";var kM=4096,ig=4,ig0=16777216,ag=Object.freeze({maximumCount:64,maximumTotalPixels:67108864,maximumTotalSvgBytes:67108864});function Q$0($){let _=1;while(_<$)_*=2;return _}function ag0($){let _=[],F=0,Q=[],Z=0,J=0,X=0,Y=0,H=()=>{if(Q.length===0)return;let K=Q$0(J+X),j=Q$0(Y),V=j*K;if(_.length>=ag.maximumCount||F+V>ag.maximumTotalPixels)throw RangeError("Generated caption sprites exceed the cumulative raster resource bound.");_.push({cards:Q,height:K,width:j}),F+=V,Q=[],Z=0,J=0,X=0,Y=0};for(let K of $){let{intrinsicHeight:j,intrinsicWidth:V}=K.rendered;if(V>kM||j>kM)throw RangeError("A social caption card exceeds the sprite dimension bound.");if(Z>0&&Z+V>kM)Z=0,J+=X+ig,X=0;if(J>0&&J+j>kM)H();Q.push({...K,x:Z,y:J}),Z+=V+ig,X=Math.max(X,j),Y=Math.max(Y,Z-ig)}return H(),_}function tg0($){let _=$.indexOf(">");if(!$.startsWith("<svg ")||_<0||!$.endsWith("</svg>"))throw TypeError("Social caption renderer returned an unsupported SVG document.");return $.slice(_+1,-6)}function eg0($){let _=$.cards.map((Z)=>`<g transform="translate(${Z.x} ${Z.y})">${tg0(Z.rendered.svg)}</g>`).join(""),F=[`<svg xmlns="http://www.w3.org/2000/svg" width="${$.width}" height="${$.height}" viewBox="0 0 ${$.width} ${$.height}" fill="none">`,_,`</svg>
|
|
1557
|
+
}`);return r50(_,"return securityViolations;","return securityViolations + (sparkWorkerFailure === null ? 0 : 1);")}var gg=rH.string().regex(/^[a-f0-9]{64}$/u),wg0=rH.strictObject({key:rH.string().min(1).max(512),sha256:gg}),r9=rH.strictObject({algorithm:rH.literal("sha256-merkle-v1"),leaves:rH.array(wg0).min(4).max(256).superRefine(($,_)=>{for(let F=1;F<$.length;F+=1)if($[F-1].key>=$[F].key)_.addIssue({code:"custom",message:"HTML-overlay integrity leaves must have unique ASCII-sorted keys.",path:[F,"key"]})}),rootSha256:gg,runtimeSha256:gg,schemaVersion:rH.literal(1)}),d8=Object.freeze({browser:"playwright-chromium",browserVersion:Gg0.version,browserContext:Object.freeze({acceptDownloads:!1,colorScheme:"light",locale:"en-US",offline:!0,permissions:Object.freeze([]),reducedMotion:"no-preference",serviceWorkers:"block",timezoneId:"UTC"}),contentSecurityPolicy:Object.freeze(["default-src 'none'","base-uri 'none'","connect-src 'none'","font-src https://slopcamera-overlay.invalid data:","form-action 'none'","frame-src 'none'","img-src https://slopcamera-overlay.invalid data:","media-src https://slopcamera-overlay.invalid data:","object-src 'none'","script-src 'unsafe-inline' https://slopcamera-overlay.invalid","style-src 'unsafe-inline'","worker-src 'none'"]),documentUrl:"https://slopcamera-overlay.invalid/slopcamera-overlay/document",environment:Object.freeze({fixed:Object.freeze({LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",PATH:"/usr/bin:/bin",TZ:"UTC"}),inherited:Object.freeze([]),privateDirectories:Object.freeze(["HOME","TMPDIR"])}),launch:Object.freeze({args:Object.freeze(["--disable-background-networking","--disable-breakpad","--disable-component-update","--disable-default-apps","--disable-domain-reliability","--disable-extensions","--disable-features=Translate,MediaRouter,OptimizationHints","--disable-quic","--disable-sync","--enable-unsafe-swiftshader","--force-webrtc-ip-handling-policy=disable_non_proxied_udp","--metrics-recording-only","--mute-audio","--no-default-browser-check","--no-first-run","--no-proxy-server","--use-angle=swiftshader"]),headless:!0,libraryArgs:Object.freeze({vgpu:Object.freeze(["--enable-unsafe-webgpu","--use-webgpu-adapter=swiftshader"])})}),routing:Object.freeze({allowedOrigin:"https://slopcamera-overlay.invalid",declaredResourcesOnly:!0,remoteNetworkDenied:!0}),runtimeSnapshot:Object.freeze({macosAnchor:"/private/tmp",macosAnchorPolicy:"physical-root-owned-sticky-direct-child",cleanupIdentity:"container-direct-children-and-complete-runtime-manifest",copyBufferBytes:4194304,filesystemGuard:"anchor-basename-and-recursive-parent-watch-with-path-identities",orphanRecovery:"active-to-released-lease-last-atomic-quarantine-double-open-proof",verifiedMacosFilesystemFlags:"user-immutable-recursive"}),schemaVersion:1,screenshot:Object.freeze({omitBackground:!0,scale:"css",type:"png"})}),Dg0=Object.freeze({...d8.launch,args:Object.freeze([...d8.launch.args.filter(($)=>$!=="--enable-unsafe-swiftshader"&&$!=="--use-angle=swiftshader"),"--use-angle=metal","--disable-software-rasterizer"])});function Lg0($){if($===void 0)return d8;let _=L6.parse($);return Object.freeze({...d8,contentSecurityPolicy:_==="three-spark-webgl2-hardware-v1"?Object.freeze(d8.contentSecurityPolicy.map((F)=>{if(F==="worker-src 'none'")return"worker-src blob:";if(F==="connect-src 'none'")return"connect-src https://slopcamera-overlay.invalid data:";if(F.startsWith("script-src "))return`${F} 'wasm-unsafe-eval'`;return F})):d8.contentSecurityPolicy,executionProfile:_,launch:Dg0,gpu:Object.freeze({admission:"matching-active-webgl2-and-cdp-angle-metal-v1",capture:"host-held-native-context-health-before-and-after-every-screenshot",fallback:"reject-software-or-unknown",platform:"darwin",receipt:"bounded-context-device-driver-os-evidence-per-batch"}),schemaVersion:2})}function LM($,_=[]){let F=Lg0($),Z=PQ.parse(_).filter((J)=>J.transport==="fetch").map((J)=>`${d8.routing.allowedOrigin}${N6(J)}`);if(Z.length===0||!F.contentSecurityPolicy.includes("connect-src 'none'"))return F;return Object.freeze({...F,contentSecurityPolicy:Object.freeze(F.contentSecurityPolicy.map((J)=>J==="connect-src 'none'"?`connect-src ${Z.join(" ")}`:J)),schemaVersion:3})}function Jw($,_){if(_===void 0)return;L6.parse(_);let F=_==="three-webgl2-hardware-v1"?["three"]:["@sparkjsdev/spark","three","three/addons/postprocessing/Pass.js"];if(R([...$].sort())!==R(F))throw Error("Hardware execution profile requires its exact approved scene library set.")}function Zw($){return Og0("sha256").update($).digest("hex")}function Cg0($,_){return Zw(R({domain:"slopcamera.html-overlay-integrity-leaf/v1",key:$,value:_}))}function Bg0($){let _=$.map((F)=>Zw(["slopcamera.html-overlay-integrity-node/v1","leaf",F.key,F.sha256].join("\x00")));while(_.length>1){let F=[];for(let Q=0;Q<_.length;Q+=2){let Z=_[Q],J=_[Q+1]??Z;F.push(Zw(["slopcamera.html-overlay-integrity-node/v1","branch",Z,J].join("\x00")))}_=F}return _[0]}function o9($,_,F){let Q=w6.parse($);Jw(Q.libraries,F);let Z=o$.parse(_),J=Q.libraries.map(qQ),X=nk(Q.libraries),Y=Yg({canvas:Q.canvas,parameters:Q.parameters,resources:Q.resources,seed:Q.seed,timing:Q.timing}),H=F==="three-spark-webgl2-hardware-v1"?o50(Y):Y,K=Zw(Buffer.from(H,"utf8")),V=[{key:"authoring-config",value:{canvas:Q.canvas,kind:Q.kind,parameters:Q.parameters,schemaVersion:Q.schemaVersion,seed:Q.seed,timing:Q.timing}},{key:"browser-runtime",value:Z},{key:"renderer-contract",value:LM(F,Q.resources)},{key:"document",value:{bytes:Buffer.byteLength(Q.html,"utf8"),sha256:Zw(Buffer.from(Q.html,"utf8"))}},{key:"import-map",value:X},{key:"runtime",value:{bytes:Buffer.byteLength(H,"utf8"),sha256:K}},...J.map((W)=>({key:`library:${W.specifier}`,value:W})),...Q.resources.map((W)=>({key:`resource:${W.name}`,value:W}))].map((W)=>({key:W.key,sha256:Cg0(W.key,W.value)})).sort((W,G)=>W.key<G.key?-1:W.key>G.key?1:0),O=r9.parse({algorithm:"sha256-merkle-v1",leaves:V,rootSha256:Bg0(V),runtimeSha256:K,schemaVersion:1});return Object.freeze({importMap:X,integrity:Object.freeze(O),libraryLocks:Object.freeze(J),runtimeSource:H})}var LV="slopcamera-3.3.6",Xw=["scene.audit","scene.inspect","scene.patch","scene.evaluate","scene.render","scene.render-audit","scene.review","scene.direction.check","scene.direction.compile","scene.direction.gallery","scene.effects.check","scene.effects.plan","scene.behavior.check","scene.behavior.bake","scene.behavior.gallery","scene.behavior.audit","scene.temporal-audit","slopcamera.studio.run","spatial.project.snapshot","spatial.project.migrate","spatial.project.patch","spatial.project.restore","spatial.project.add-shot","spatial.project.add-candidate","spatial.project.select-candidate","spatial.project.reconcile","project.snapshot","analysis.project-inactivity","analysis.faces","analysis.music","analysis.scenes","analysis.project-auto-zooms","derive.edit-batch","project.commit-edits","derive.follow-faces","edit.create-revision","edit.create-candidate-revision","edit.bind-candidate-revision","edit.freeze-revision","iteration.create-candidate","iteration.create-matrix","iteration.select","project.promote-selection","render.bind-candidate-output","render.project-plan","render.project","render.materialize-selection","media.ingest","media.overlay","media.html-overlay","media.audio-effects","media.color-grade","gateway.image","gateway.video","gateway.speech","gateway.transcription","slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.vectorize","slopcamera.image.generate"],Yw=["cpu","local-io","ffmpeg","vision","whisper","network","paid-call","project-render","project-publication","output-publication","capture-device","browser"];import{isAbsolute as zg0,relative as vg,resolve as i50}from"path";import{z as v1}from"zod";var Ug0=v1.strictObject({path:L0}),oH=536870912,CM=v1.union([Ug0,NO,q0]),BM=v1.strictObject({endBehavior:v1.enum(["hide","loop","freeze-end"]).default("hide"),playbackRate:v1.number().finite().positive().max(64).default(1),sourceInUs:v1.number().int().safe().nonnegative().default(0),sourceOutUs:v1.number().int().safe().positive().optional()}).prefault({}),xg=v1.strictObject({artifact:q0,id:v1.string().min(1).max(256),provider:v1.enum(["apple-emoji-pack","brand-catalog"]),selector:CP,variant:v1.enum(["color","duotone"])}),kg0=v1.discriminatedUnion("kind",[v1.strictObject({artifact:CM,kind:v1.literal("image")}),v1.strictObject({artifact:CM,kind:v1.literal("svg")}),v1.strictObject({artifact:CM,kind:v1.literal("gif"),playback:BM}),v1.strictObject({artifact:CM,audioPolicy:pC.default({kind:"mute"}),kind:v1.literal("video"),playback:BM}),v1.strictObject({kind:v1.literal("emoji"),provider:v1.enum(["apple-emoji-pack","brand-catalog","auto"]).default("auto"),query:v1.string().min(1).max(256),resolved:xg.optional(),variant:v1.enum(["color","duotone"]).optional()})]),a50=v1.discriminatedUnion("kind",[v1.strictObject({artifact:q0,kind:v1.literal("image")}),v1.strictObject({artifact:q0,kind:v1.literal("svg")}),v1.strictObject({artifact:q0,kind:v1.literal("gif"),playback:BM}),v1.strictObject({artifact:q0,audioPolicy:pC,kind:v1.literal("video"),playback:BM}),v1.strictObject({kind:v1.literal("emoji"),provider:v1.enum(["apple-emoji-pack","brand-catalog","auto"]),query:v1.string().min(1).max(256),resolved:xg,variant:v1.enum(["color","duotone"]).optional()})]),hg=v1.strictObject({anchor:zP.default("center"),blendMode:v1.enum(["normal","addition","darken","lighten","multiply","overlay","screen"]).default("normal"),crop:kP.default({kind:"none"}),entrance:nN.default({kind:"none"}),exit:nN.default({kind:"none"}),fit:v1.enum(["contain","cover","fill"]).default("fill"),mask:MP.default({kind:"none"}),motion:AP.default({kind:"none"}),opacity:v1.number().finite().min(0).max(1).default(1),position:p_.default({x:0,y:0}),rotationDegrees:v1.number().finite().min(-3600).max(3600).default(0),scale:v1.number().finite().positive().max(128).default(1),size:UP.default({kind:"intrinsic"}),zIndex:v1.number().int().safe().default(0)}).prefault({}),iH=v1.strictObject({capabilityBindings:p4.optional(),identityKey:v1.string().min(1).max(128).optional(),layout:hg,project:K2,range:m0,source:kg0}),mg=iH.extend({source:a50}).strict(),KX=v1.strictObject({artifact:q0,created:v1.boolean(),operation:C5,receipt:q0}),ug=v1.strictObject({artifact:q0,createdAt:v1.string().datetime({offset:!0}),exactInputSha256:x,ffprobeVersion:v1.string().min(1).max(256).nullable(),kind:v1.union([v1.literal("slopcamera.local-overlay-preparation-receipt"),v1.literal("studio.local-overlay-preparation-receipt")]),operationSha256:x,overlayId:v1.string().min(1).max(128),projectGenerationSha256:x,projectId:K2,schemaVersion:v1.literal(1)});function Mg0($){let _=$.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test(_))return{kind:"id",value:_};if([...$].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test($))return{kind:"unicode",value:$};return{kind:"name",value:$}}function Ag0($){if(!("bytes"in $))return $;return q0.parse({bytes:$.bytes,path:$.path,sha256:$.sha256})}function t50($){return $.kind==="image"||$.kind==="gif"||$.kind==="video"?["ffprobe"]:[]}async function Rg0($,_,F,Q){let Z=await Q($.paths.repositoryRoot,_.query,_.variant,_.provider),J=vg($.paths.repositoryRoot,Z.path),X=await r1($,{path:J},F,oH);if(X.artifact.sha256!==Z.sha256)throw new N("conflict","Resolved emoji bytes disagree with the checked emoji catalog.");let Y=xg.parse({artifact:X.artifact,id:Z.id,provider:Z.provider,selector:Mg0(_.query),variant:Z.variant});if(_.resolved!==void 0&&R(_.resolved)!==R(Y))throw new N("conflict","The checked emoji asset changed after exact node planning.");return a50.parse({..._,resolved:Y})}async function lg($,_,F,Q={}){let Z=iH.parse(_),J=t50(Z.source),X=Z.source.kind==="emoji"?Rg0($,Z.source,F,Q.resolveEmoji??wV):r1($,Ag0(Z.source.artifact),F,oH).then((K)=>({...Z.source,artifact:K.artifact})),[Y,H]=await Promise.all([X,L5($,J,Z.capabilityBindings)]);return mg.parse({...Z,capabilityBindings:H,source:Y})}function Tg0($,_){let F=i50($,_),Q=vg(i50($),F);if(Q===""||Q.startsWith("..")||zg0(Q))throw new N("unsafe-path","Prepared overlay asset escaped its project bundle.");return F}function qg0($,_,F){let Q=BP.parse(_),Z={bytes:Q.asset.bytes,mediaType:Q.asset.mediaType,sha256:Q.asset.sha256},J=Q.kind==="image"||Q.kind==="svg"?{asset:Z,kind:Q.kind}:Q.kind==="emoji"?{asset:Z,kind:Q.kind,provider:Q.provider,selector:Q.selector}:{asset:Z,audioPolicy:Q.audioPolicy,kind:Q.kind,playback:Q.playback};return`overlay_${m({domain:"studio.media-overlay-operation/v1",identityKey:$.identityKey??null,intrinsicSize:F,layout:$.layout,project:$.project,range:$.range,source:J}).slice(0,32)}`}function Eg0($={}){let _=$.ingestFile??HM,F=$.ingestEmoji??KM,Q=$.inspectPng??sH,Z=$.inspectSvg??HX,J=$.probe??UQ,X=$.resolveEmoji??wV;return{inputSchema:iH,inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",lifecycle:{kind:"local-artifact",execute:async(Y,H)=>{a(Y.abortSignal);let K=await lg(Y.application,H,Y.abortSignal,{resolveEmoji:X}),j=t50(K.source);await s9(Y,Y.application,K.capabilityBindings,j);let V=K.capabilityBindings??await XZ(Y.application,j),O=await n2(Y.application,K.project);if(m8(Y.expectedProjectGeneration,O.generation),K.range.endUs>O.plan.timelineDurationUs)throw new N("usage","Overlay range exceeds the project timeline.");let W=o6(r6(O.plan),K.range).reduce((C,B)=>C+B.output.endUs-B.output.startUs,0);if(W<=0)throw new N("conflict","Overlay range has no visible kept output time.");let G=K.source.kind==="emoji"?void 0:await r1(Y.application,K.source.artifact,Y.abortSignal,oH),D=K.source.kind==="emoji"?K.source:void 0,w=D===void 0?void 0:await X(Y.application.paths.repositoryRoot,D.query,D.variant,D.provider);if(w!==void 0&&D!==void 0&&(w.id!==D.resolved.id||w.provider!==D.resolved.provider||w.variant!==D.resolved.variant||w.sha256!==D.resolved.artifact.sha256))throw new N("conflict","Resolved emoji changed immediately before preparation.");let L=await $5(Y);try{await Y.workflow?.beforePublication(),a(Y.abortSignal);let C=w===void 0?await _(O.openProject.directory.path,G.absolutePath,K.source.kind):await F(O.openProject.directory.path,w),B=G?.artifact??D.resolved.artifact;if(C.bytes!==B.bytes||C.sha256!==B.sha256||C.provenance.sourceSha256!==B.sha256)throw new N("conflict","Prepared overlay bytes disagree with the exact bound source.");let z=Tg0(O.openProject.directory.path,C.path),U=(await r1(Y.application,{path:vg(Y.application.paths.repositoryRoot,z)},Y.abortSignal,oH)).artifact;if(U.bytes!==C.bytes||U.sha256!==C.sha256)throw new N("conflict","Prepared project asset disagrees with its published bytes.");let k=C.mediaType==="image/svg+xml"?{...await Z(z),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:K.source.kind==="emoji"?{...await Q(z),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await J(Z5(V,"ffprobe"),new J8(l8(Y.application,V),Y.abortSignal),z),A={height:"pixelHeight"in k?k.pixelHeight:k.height,width:"pixelWidth"in k?k.pixelWidth:k.width},q={bytes:C.bytes,mediaType:C.mediaType,path:C.path,provenance:C.provenance,sha256:C.sha256},E;if(K.source.kind==="image"||K.source.kind==="svg")E={asset:q,kind:K.source.kind};else if(K.source.kind==="emoji")E={asset:q,kind:"emoji",provider:K.source.resolved.provider,selector:K.source.resolved.selector};else{if(k.durationUs===null||k.durationUs<=0)throw new N("invalid-data","Animated overlay media must report a positive duration.");let g=DV({mediaDurationUs:k.durationUs,outputDurationUs:W,playbackRate:K.source.playback.playbackRate,sourceInUs:K.source.playback.sourceInUs,sourceOutUs:K.source.playback.sourceOutUs}),b={audioEndUs:k.audioEndUs,audioStartUs:k.audioStartUs,audioStreamIndex:k.audioStreamIndex,endBehavior:K.source.playback.endBehavior,playbackRate:K.source.playback.playbackRate,streamStartUs:k.videoStartUs,videoStreamIndex:k.videoStreamIndex,...g};if(K.source.kind==="gif")E={asset:q,audioPolicy:{kind:"mute"},kind:"gif",playback:b};else{if(K.source.audioPolicy.kind!=="mute"&&!k.hasAudio)throw new N("conflict","The selected video overlay audio policy requires an audio stream.");E={asset:q,audioPolicy:K.source.audioPolicy,kind:"video",playback:b}}}let M=C5.parse({...K.layout,coordinateSpace:"output-pixels",intrinsicSize:A,overlayId:qg0(K,E,A),range:K.range,source:E}),T=ug.parse({artifact:U,createdAt:Y.application.clock.now().toISOString(),exactInputSha256:m(K),ffprobeVersion:j.length===0?null:n9(V,"ffprobe"),kind:"slopcamera.local-overlay-preparation-receipt",operationSha256:m(M),overlayId:M.overlayId,projectGenerationSha256:O.generation.generationSha256,projectId:O.project.projectId,schemaVersion:1}),P=await G_({context:Y,receipt:T,workspace:L}),I=KX.parse({artifact:U,created:C.created,operation:M,receipt:P});return await h5(Y,{inputSchemaId:"slopcamera.operation.media.overlay.input/v1",kind:"media.overlay",outputSchemaId:"slopcamera.operation.media.overlay.output/v1",version:1},I),I}finally{await L.dispose()}}},outputSchema:KX,outputSchemaId:"slopcamera.operation.media.overlay.output/v1",policy:{cache:"exact-run",cancellable:!0,effect:"local-derived-write",maxDurationMs:3600000,maxFanOut:0,maxInputBytes:262144,maxOutputBytes:2097152,preparation:["project-state","local-media"],resources:[{amount:1,resource:"cpu"},{amount:1,resource:"local-io"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(Y)=>Y.receipt.path,summarize:(Y)=>({fields:{bytes:Y.artifact.bytes,created:Y.created,kind:Y.operation.source.kind,overlayId:Y.operation.overlayId,receipt:Y.receipt.path,sha256:Y.artifact.sha256},kind:"media.overlay"}),version:1}}var e50=Eg0();var zM=2097152,UM=134217728,pg=536870912,cg=["ffmpeg","ffprobe","html-browser"],yg0=s4.union([GV,s4.strictObject({path:L0}),q0]),gg0=s4.union([GV,q0]),vg0=s4.union([b5,NO]),xg0=G6.omit({bytes:!0,sha256:!0}).extend({artifact:vg0}).strict(),hg0=G6.extend({artifact:q0}).strict(),Hw=s4.strictObject({canvas:HZ,capabilityBindings:p4.optional(),document:yg0,identityKey:s4.string().min(1).max(128).optional(),layout:hg,libraries:TQ.default([]),parameters:ZX.default({}),project:K2,range:m0,resources:s4.array(xg0).max(64).default([]),seed:s4.number().int().min(0).max(4294967295).default(0),timing:BF}),sg=Hw.omit({document:!0,resources:!0}).extend({document:gg0,resources:s4.array(hg0).max(64)}).strict(),ng=s4.strictObject({artifact:q0,browserVersion:s4.string().min(1).max(512),createdAt:s4.string().datetime({offset:!0}),executionIntegrity:r9.optional(),exactInputSha256:x,ffmpegVersion:s4.string().min(1).max(512),ffprobeVersion:s4.string().min(1).max(512),frameCount:s4.number().int().safe().positive(),kind:s4.union([s4.literal("slopcamera.html-overlay-preparation-receipt"),s4.literal("studio.html-overlay-preparation-receipt")]),libraryLocks:_g,libraryLocksSha256:x,operationSha256:x,overlayId:s4.string().min(1).max(128),projectGenerationSha256:x,projectId:K2,schemaVersion:s4.literal(1)}),_$0=KX;function mg0($){if(!("mediaType"in $.artifact))return $.artifact;if($.artifact.mediaType!==$.mediaType)throw new N("invalid-data",`HTML overlay resource ${$.name} declares ${$.mediaType} but its generated artifact is ${$.artifact.mediaType}.`);return q0.parse({bytes:$.artifact.bytes,path:$.artifact.path,sha256:$.artifact.sha256})}async function ug0($,_,F){if("html"in _)return _;return(await r1($,_,F,zM)).artifact}function lg0($,_){return o6(r6($),_).reduce((F,Q)=>F+Q.output.endUs-Q.output.startUs,0)}async function rg($,_,F){let Q=Hw.parse(_),[Z,J,X]=await Promise.all([ug0($,Q.document,F),Promise.all(Q.resources.map(async(K)=>({...K,artifact:(await r1($,mg0(K),F,UM)).artifact}))),L5($,cg,Q.capabilityBindings)]),Y=PQ.parse(J.map(({artifact:K,...j})=>({...j,bytes:K.bytes,sha256:K.sha256}))),H=new Map(J.map((K)=>[K.name,K.artifact]));return sg.parse({...Q,capabilityBindings:X,document:Z,resources:Y.map((K)=>({...K,artifact:H.get(K.name)}))})}function dg0($){let _;try{_=new TextDecoder("utf-8",{fatal:!0}).decode($)}catch{throw new N("invalid-data","The HTML overlay document must be valid UTF-8.")}if(_.trim()==="")throw new N("invalid-data","The HTML overlay document is empty.");return _}async function cg0($,_){let F=await bg0($,$$0.O_RDONLY|($$0.O_NOFOLLOW??0));try{let Q=await F.stat();if(!Q.isFile()||Q.size<=0)throw new N("invalid-data","Rendered HTML overlay is empty.");let Z=Pg0("sha256"),J=Buffer.allocUnsafe(1048576),X=0;while(X<Q.size){a(_);let H=await F.read(J,0,Math.min(J.byteLength,Q.size-X),X);if(H.bytesRead===0)break;Z.update(J.subarray(0,H.bytesRead)),X+=H.bytesRead}let Y=await F.stat();if(X!==Q.size||Y.dev!==Q.dev||Y.ino!==Q.ino||Y.size!==Q.size||Y.mtimeMs!==Q.mtimeMs||Y.ctimeMs!==Q.ctimeMs)throw new N("conflict","Rendered HTML overlay changed while it was being verified.");return Z.digest("hex")}finally{await F.close()}}var pg0=s4.object({streams:s4.array(s4.object({codec_name:s4.string(),height:s4.number().int().positive(),pix_fmt:s4.string(),width:s4.number().int().positive()})).min(1)});async function sg0($,_,F,Q,Z){let J=await new J8(l8($,_),Z).run([Z5(_,"ffprobe"),"-v","error","-select_streams","v:0","-show_entries","stream=codec_name,pix_fmt,width,height","-of","json",F],{maxOutputBytes:65536,stdin:"ignore",timeoutMs:30000});if(J.exitCode!==0)throw new N("invalid-data","Rendered HTML overlay could not be inspected as an alpha video.");let X;try{X=JSON.parse(J.stdout)}catch{throw new N("invalid-data","Rendered HTML overlay inspection returned invalid JSON.")}let Y=pg0.parse(X).streams[0];if(Y.codec_name!=="qtrle"||Y.pix_fmt!=="argb"||Y.width!==Q.width||Y.height!==Q.height)throw new N("invalid-data","Rendered HTML overlay must be a canvas-sized qtrle/argb alpha video.",{stream:Y})}function ng0($,_,F){return`overlay_${m({assetSha256:F,authoring:_,domain:"studio.media-html-overlay-operation/v1",identityKey:$.identityKey??null,layout:$.layout,project:$.project,range:$.range}).slice(0,32)}`}function og($={}){let _=$.ingest??f50,F=$.probe??UQ,Q=$.bindBrowserRuntime??i$,Z=$.toolVersion??LV;return{inputSchema:Hw,inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",lifecycle:{kind:"local-artifact",execute:async(J,X)=>{a(J.abortSignal);let Y=await rg(J.application,X,J.abortSignal);await s9(J,J.application,Y.capabilityBindings,cg);let H=Y.capabilityBindings??await XZ(J.application,cg),K=J.application.htmlOverlayRenderer;if(K===void 0)throw new N("unavailable","This Slopcamera host does not provide an HTML-overlay browser renderer.");let j=await n2(J.application,Y.project);if(m8(J.expectedProjectGeneration,j.generation),Y.range.endUs>j.plan.timelineDurationUs)throw new N("usage","HTML overlay range exceeds the project timeline.");let V=lg0(j.plan,Y.range);if(V<=0)throw new N("conflict","HTML overlay range has no visible kept output time.");if(Y.timing.durationUs!==V)throw new N("conflict","HTML overlay timing duration must equal the range's visible output duration.",{actualDurationUs:Y.timing.durationUs,expectedDurationUs:V});let[O,W]=await Promise.all(["html"in Y.document?Promise.resolve(Y.document.html):C4(J.application,Y.document,J.abortSignal,zM).then((L)=>dg0(L.data)),Promise.all(Y.resources.map(async(L)=>({...L,absolutePath:(await r1(J.application,L.artifact,J.abortSignal,UM)).absolutePath})))]),G=w6.parse({canvas:Y.canvas,html:O,kind:"slopcamera.html-overlay",libraries:Y.libraries,parameters:Y.parameters,resources:W.map((L)=>({bytes:L.bytes,mediaType:L.mediaType,name:L.name,sha256:L.sha256,...L.transport===void 0?{}:{transport:L.transport},urlPath:L.urlPath})),schemaVersion:1,seed:Y.seed,timing:Y.timing}),D=await $5(J),w=await Ig0(dg(D.path,"html-overlay-"));try{let L=await Q(m5(H,"html-browser"),J.abortSignal),C=o9(G,L).integrity,B=await K.renderFrames({authoring:G,browserRuntime:L,outputDirectory:w,resources:W},J.abortSignal),z=r9.parse(B.executionIntegrity);if(m(z)!==m(C))throw new N("conflict","HTML-overlay renderer returned integrity evidence that does not match the planned browser execution.");let U=iG.parse(B.libraryLocks),k=G.libraries.map(qQ);if(m(U)!==m(k))throw new N("conflict","HTML-overlay renderer returned library locks that do not exactly match the authoring selection.");let A=k_(G.timing);if(B.frameCount!==A)throw new N("conflict","HTML-overlay renderer returned an unexpected frame count.");let q=dg(w,"overlay.mov"),E=[Z5(H,"ffmpeg"),"-hide_banner","-loglevel","error","-nostdin","-n","-framerate",String(G.timing.fps),"-start_number","0","-i",B.framePattern,"-frames:v",String(B.frameCount),"-an","-c:v","qtrle","-pix_fmt","argb","-movflags","+faststart",q],M=await new J8(l8(J.application,H),J.abortSignal).run(E,{cwd:w,maxOutputBytes:1048576,stdin:"ignore",timeoutMs:3600000});if(M.exitCode!==0)throw new N("invalid-data",`FFmpeg could not encode the HTML overlay: ${M.stderr.slice(0,2000)}`);await sg0(J.application,H,q,G.canvas,J.abortSignal);let T=await cg0(q,J.abortSignal);await J.workflow?.beforePublication(),a(J.abortSignal);let P=await _(j.openProject.directory.path,{command:E,generator:"slopcamera-html-overlay",generatorVersion:Z,path:q,sourceSha256:T}),I=dg(j.openProject.directory.path,P.path),g=(await r1(J.application,{path:fg0(J.application.paths.repositoryRoot,I)},J.abortSignal,pg)).artifact,b=await F(Z5(H,"ffprobe"),new J8(l8(J.application,H),J.abortSignal),I);if(b.durationUs===null||b.durationUs<=0||b.hasAudio||b.pixelWidth!==G.canvas.width||b.pixelHeight!==G.canvas.height)throw new N("invalid-data","Generated HTML overlay has invalid duration, dimensions, or audio streams.");let y=DV({mediaDurationUs:b.durationUs,outputDurationUs:V,playbackRate:1,sourceInUs:0,sourceOutUs:void 0}),r={asset:{bytes:P.bytes,mediaType:P.mediaType,path:P.path,provenance:P.provenance,sha256:P.sha256},audioPolicy:{kind:"mute"},kind:"video",playback:{audioEndUs:null,audioStartUs:0,audioStreamIndex:null,endBehavior:"hide",playbackRate:1,streamStartUs:b.videoStartUs,videoStreamIndex:b.videoStreamIndex,...y}},h=C5.parse({...Y.layout,coordinateSpace:"output-pixels",intrinsicSize:{height:G.canvas.height,width:G.canvas.width},overlayId:ng0(Y,G,g.sha256),range:Y.range,source:r}),p=ng.parse({artifact:g,browserVersion:n9(H,"html-browser"),createdAt:J.application.clock.now().toISOString(),executionIntegrity:z,exactInputSha256:m(Y),ffmpegVersion:n9(H,"ffmpeg"),ffprobeVersion:n9(H,"ffprobe"),frameCount:B.frameCount,kind:"slopcamera.html-overlay-preparation-receipt",libraryLocks:U,libraryLocksSha256:m(U),operationSha256:m(h),overlayId:h.overlayId,projectGenerationSha256:j.generation.generationSha256,projectId:j.project.projectId,schemaVersion:1}),S=await G_({context:J,receipt:p,workspace:D}),i=KX.parse({artifact:g,created:P.created,operation:h,receipt:S});return await h5(J,{inputSchemaId:"slopcamera.operation.media.html-overlay.input/v1",kind:"media.html-overlay",outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",version:1},i),i}finally{await Sg0(w,{force:!0,recursive:!0}),await D.dispose()}}},outputSchema:KX,outputSchemaId:"slopcamera.operation.media.html-overlay.output/v1",policy:{cache:"exact-run",cancellable:!0,effect:"local-derived-write",maxDurationMs:3600000,maxFanOut:0,maxInputBytes:3145728,maxOutputBytes:2097152,preparation:["project-state","local-media"],resources:[{amount:1,resource:"browser"},{amount:1,resource:"cpu"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"local-io"},{amount:1,resource:"network"},{amount:1,resource:"output-publication"}],resume:"verified-receipt"},receiptReference:(J)=>J.receipt.path,summarize:(J)=>({fields:{bytes:J.artifact.bytes,created:J.created,kind:"html",overlayId:J.operation.overlayId,receipt:J.receipt.path,sha256:J.artifact.sha256},kind:"media.html-overlay"}),version:1}}var sL1=og();var og0=["media.ingest","media.html-overlay","media.overlay","media.audio-effects","media.color-grade"],$C1=rg0.enum(og0);async function F$0($,_,F,Q=new AbortController().signal){switch(_){case"media.ingest":return await T40($,OV.parse(F),Q);case"media.overlay":return await lg($,iH.parse(F),Q);case"media.html-overlay":return await rg($,Hw.parse(F),Q);case"media.audio-effects":return await B40($,WV.parse(F),Q);case"media.color-grade":return await k40($,NV.parse(F),Q)}}import{z as Kw}from"zod";import{lstat as _v0,realpath as J$0}from"fs/promises";import{isAbsolute as Fv0,join as Qv0,relative as Zv0,sep as Jv0}from"path";import{z as bQ}from"zod";var kM=4096,ig=4,ig0=16777216,ag=Object.freeze({maximumCount:64,maximumTotalPixels:67108864,maximumTotalSvgBytes:67108864});function Q$0($){let _=1;while(_<$)_*=2;return _}function ag0($){let _=[],F=0,Q=[],Z=0,J=0,X=0,Y=0,H=()=>{if(Q.length===0)return;let K=Q$0(J+X),j=Q$0(Y),V=j*K;if(_.length>=ag.maximumCount||F+V>ag.maximumTotalPixels)throw RangeError("Generated caption sprites exceed the cumulative raster resource bound.");_.push({cards:Q,height:K,width:j}),F+=V,Q=[],Z=0,J=0,X=0,Y=0};for(let K of $){let{intrinsicHeight:j,intrinsicWidth:V}=K.rendered;if(V>kM||j>kM)throw RangeError("A social caption card exceeds the sprite dimension bound.");if(Z>0&&Z+V>kM)Z=0,J+=X+ig,X=0;if(J>0&&J+j>kM)H();Q.push({...K,x:Z,y:J}),Z+=V+ig,X=Math.max(X,j),Y=Math.max(Y,Z-ig)}return H(),_}function tg0($){let _=$.indexOf(">");if(!$.startsWith("<svg ")||_<0||!$.endsWith("</svg>"))throw TypeError("Social caption renderer returned an unsupported SVG document.");return $.slice(_+1,-6)}function eg0($){let _=$.cards.map((Z)=>`<g transform="translate(${Z.x} ${Z.y})">${tg0(Z.rendered.svg)}</g>`).join(""),F=[`<svg xmlns="http://www.w3.org/2000/svg" width="${$.width}" height="${$.height}" viewBox="0 0 ${$.width} ${$.height}" fill="none">`,_,`</svg>
|
|
1558
1558
|
`].join(""),Q=Buffer.byteLength(F,"utf8");if(Q>ig0)throw RangeError("A generated caption sprite exceeds the 16 MiB SVG bound.");return{bytes:Q,contents:F}}function $v0($){let _=$.overlays.reduce((F,Q)=>Math.max(F,Q.operation.zIndex),-1);if(_>=Number.MAX_SAFE_INTEGER)throw RangeError("Existing overlay z-index leaves no safe caption layer.");return _+1}function Z$0($){let _=vJ($.plan),F=x.parse($.sourceSha256),Q=dP.parse($.style);if($.cues.length===0)throw TypeError("Captioned render planning requires at least one visible cue.");let Z=$.cues.map((V)=>({cue:V,rendered:Te(V,_.output)})),J=$v0(_),X=[],Y=[],H=0;for(let[V,O]of ag0(Z).entries()){let{bytes:W,contents:G}=eg0(O),D=X0(G);if(H+=W,H>ag.maximumTotalSvgBytes)throw RangeError("Generated caption sprites exceed the cumulative SVG byte bound.");let w=`renders/caption-assets/${D}.svg`,L=`overlay_caption_${m({domain:"slopcamera.social-caption-sprite/v1",sha256:D,sourceSha256:F,spriteIndex:V,style:Q}).slice(0,32)}`,C={asset:{bytes:W,mediaType:"image/svg+xml",path:w,provenance:{command:["slopcamera","caption",Q],generator:"slopcamera-social-caption-sprite",generatorVersion:"1",kind:"generated",sourceSha256:F},sha256:D},kind:"svg"};X.push({contents:G,path:w,sha256:D});for(let B of O.cards){let z={bottom:(O.height-B.y-B.rendered.intrinsicHeight)/O.height,kind:"normalized-insets",left:B.x/O.width,right:(O.width-B.x-B.rendered.intrinsicWidth)/O.width,top:B.y/O.height},U=C5.parse({anchor:"bottom",crop:z,entrance:{kind:"none"},exit:{kind:"none"},intrinsicSize:{height:O.height,width:O.width},opacity:1,overlayId:L,position:{x:0,y:-B.rendered.bottomSafeMargin},range:B.cue.projectRange,rotationDegrees:0,scale:1,size:{height:B.rendered.intrinsicHeight,kind:"pixels",width:B.rendered.intrinsicWidth},source:C,zIndex:J});Y.push({operation:U,outputRange:B.cue.outputRange,playbackOffsetUs:0,projectRange:B.cue.projectRange,visibleDurationUs:B.cue.outputRange.endUs-B.cue.outputRange.startUs})}}let K=m6.parse({..._,overlays:[..._.overlays,...Y],planSha256:"0".repeat(64)}),j=vJ(m6.parse({...K,planSha256:Yf(K)}));return{artifacts:X,plan:j}}var Xv0=268435456,X$0=bQ.strictObject({background:bQ.string().regex(/^#[0-9a-fA-F]{8}$/u).optional(),frameRate:bQ.number().finite().positive().max(240).optional()}),Yv0=X$0.extend({captions:xj}).strict(),Y$0=bQ.strictObject({analysisId:xj.shape.analysisId,analysisPath:L0,analysisSha256:x,assetId:g$,placementId:Y2,placementSyncSha256:x,streamId:G5,subjectIntegritySha256:x,wordCount:bQ.number().int().safe().positive().max(1e6)}),$v=bQ.strictObject({eventsSha256:x,manifestSha256:x,placementId:Y2,recordingId:P5}),tg=bQ.strictObject({metadataBindings:bQ.array($v).max(256).optional(),revision:Yy,settings:X$0.optional()}).superRefine(($,_)=>{if($.metadataBindings===void 0)return;for(let F=0;F<$.metadataBindings.length;F+=1){let Q=$.metadataBindings[F],Z=$.metadataBindings[F-1];if(Z!==void 0&&Z.placementId.localeCompare(Q.placementId)>=0)_.addIssue({code:"custom",message:"Render metadata bindings must have unique sorted placement IDs.",path:["metadataBindings",F,"placementId"]})}}),eg=bQ.strictObject({captionBinding:Y$0.optional(),metadataBindings:bQ.array($v).max(256).optional(),revision:Yy,settings:Yv0}).superRefine(($,_)=>{if($.metadataBindings===void 0)return;for(let F=0;F<$.metadataBindings.length;F+=1){let Q=$.metadataBindings[F],Z=$.metadataBindings[F-1];if(Z!==void 0&&Z.placementId.localeCompare(Q.placementId)>=0)_.addIssue({code:"custom",message:"Render metadata bindings must have unique sorted placement IDs.",path:["metadataBindings",F,"placementId"]})}}),H$0=H8;function Hv0($){return m({...$,domain:"slopcamera.social-caption-source/v1"})}function Kv0($,_){let F=Zv0($,_);return F===""||F!==".."&&!F.startsWith(`..${Jv0}`)&&!Fv0(F)}async function CV($,_){let F;try{F=await J$0($.paths.projectRoot)}catch{throw new N("not-found","The project root does not exist.")}let Q=Qv0(F,_),Z;try{Z=await _v0(Q)}catch{throw new N("not-found",`Project does not exist: ${_}`)}if(Z.isSymbolicLink()||!Z.isDirectory())throw new N("unsafe-path",`Project must be a physical directory: ${_}`);let J=await J$0(Q);if(!Kv0(F,J)||J===F)throw new N("unsafe-path",`Project directory escapes the configured project root: ${_}`);return J}function jv0($){return z_.parse({artifact:$.artifact,baseGeneration:$.baseGeneration,kind:$.kind,outputGeometrySha256:$.outputGeometrySha256,pixelHeight:$.pixelHeight,pixelWidth:$.pixelWidth,planId:$.planId,projectEditPlanSha256:$.projectEditPlanSha256,projectId:$.projectId,projectSha256:$.projectSha256,projectStructureSha256:$.projectStructureSha256,revisionSha256:$.revisionSha256,schemaVersion:$.schemaVersion})}function _v($,_){try{return JSON.parse($)}catch{throw new N("invalid-data",`${_} is not valid JSON.`)}}function Fv($){return new TextEncoder().encode($).byteLength}async function MM($,_){let F=jv0(_),Q=await CV($,F.projectId),Z=g0(Q),J=await Z.readText(F.artifact.path);if(Fv(J)!==F.artifact.bytes||X0(J)!==F.artifact.sha256)throw new N("conflict","Immutable project edit revision artifact failed its byte and SHA-256 identity.");let X=w9.parse(_v(J,"Project edit revision artifact"));if(J!==`${R(X)}
|
|
1559
1559
|
`)throw new N("conflict","Immutable project edit revision artifact is not its canonical document.");if(X.project.projectId!==F.projectId||X.projectEditPlan.planId!==F.planId||X.projectSha256!==F.projectSha256||X.projectEditPlanSha256!==F.projectEditPlanSha256||X.revisionSha256!==F.revisionSha256||H2(X.project)!==F.projectStructureSha256)throw new N("conflict","Immutable project edit revision reference does not match its frozen documents.");return{directory:Q,document:X,fileSystem:Z,reference:F}}function K$0($,_,F){return{...$?.background===void 0?{}:{background:$.background},...$?.frameRate===void 0?{}:{frameRate:$.frameRate},metadata:F,pixelHeight:_.pixelHeight,pixelWidth:_.pixelWidth}}async function AM($,_,F){let Q=new Set(F.zooms.map((J)=>J.placementId));if((F.effects.clicks.enabled||F.effects.cursor.enabled||F.effects.keystrokes.enabled||F.effects.typedText.enabled)&&F.effects.metadataPlacementId!==null)Q.add(F.effects.metadataPlacementId);let Z=await Promise.all([...Q].sort().map(async(J)=>{let X=_.placements.find((j)=>j.placementId===J);if(X===void 0)throw new N("not-found",`Unknown project metadata placement: ${J}`);let Y=_.assets.find((j)=>j.assetId===X.assetId);if(Y?.source.kind!=="recording")throw new N("conflict",`Placement ${X.placementId} is not backed by a Slopcamera recording with window and input metadata.`);let H=await U$($,Y.source.recordingId),K=await i3(H);return{binding:$v.parse({eventsSha256:m(K),manifestSha256:m(H.manifest),placementId:X.placementId,recordingId:Y.source.recordingId}),context:{events:K,manifest:H.manifest,placementId:X.placementId}}}));return{bindings:Z.map((J)=>J.binding),contexts:Z.map((J)=>J.context)}}async function j$0($,_){let F=xj.parse(_),Q=$.document.project,Z=Q.analyses.find((O)=>O.kind==="speech"&&O.analysisId===F.analysisId);if(Z===void 0||Z.kind!=="speech")throw new N("not-found",`Unknown project speech analysis: ${F.analysisId}`);let J=Q.placements.find((O)=>O.placementId===F.placementId);if(J===void 0)throw new N("not-found",`Unknown caption placement: ${F.placementId}`);if(!J.enabled||J.assetId!==Z.assetId)throw new N("conflict","Caption placement must be enabled and contain the analyzed audio asset.");if(J.audio.find((O)=>O.streamId===Z.streamId)?.presentation.enabled!==!0)throw new N("conflict","Caption source audio must be enabled and audible on the selected placement.");let Y=Q.assets.find((O)=>O.assetId===Z.assetId),H=Y?.streams.find((O)=>O.streamId===Z.streamId);if(Y===void 0||H?.kind!=="audio")throw new N("conflict","Caption speech analysis no longer identifies a project audio stream.");let K,j;try{K=await $.fileSystem.readText(Z.path),j=I8.parse(_v(K,"Speech analysis artifact"))}catch(O){if(O instanceof N)throw O;throw new N("invalid-data",`Speech analysis ${Z.analysisId} is unreadable or invalid.`)}if(K!==`${R(j)}
|
|
1560
1560
|
`||X0(K)!==Z.sha256||j.analysisId!==Z.analysisId||j.subject.assetId!==Z.assetId||j.subject.streamId!==Z.streamId||j.durationUs!==Y.durationUs)throw new N("conflict",`Speech analysis ${Z.analysisId} is stale or failed its exact identity check.`);let V=m({assetDurationUs:Y.durationUs,stream:H});if(j.subject.integritySha256!==V)throw new N("conflict",`Speech analysis ${Z.analysisId} no longer matches its audio stream.`);if(j.result.status!=="transcribed"||j.result.words.length===0)throw new N("unsupported-plan","Caption export requires a speech analysis with timed words.");if(Z.wordCount!==j.result.words.length||Z.fillerCount!==j.result.fillers.length)throw new N("invalid-data",`Speech analysis reference ${Z.analysisId} disagrees with its artifact counts.`);return{analysis:j,binding:Y$0.parse({analysisId:Z.analysisId,analysisPath:Z.path,analysisSha256:Z.sha256,assetId:Z.assetId,placementId:J.placementId,placementSyncSha256:S5(J),streamId:Z.streamId,subjectIntegritySha256:V,wordCount:j.result.words.length})}}async function RM($,_){let F=tg.parse(_),Q=await MM($,F.revision),Z=await AM($.paths.artifactRoot,Q.document.project,Q.document.projectEditPlan);return tg.parse({...F,metadataBindings:Z.bindings})}async function V$0($,_){let F=eg.parse(_),Q=await MM($,F.revision),[Z,J]=await Promise.all([AM($.paths.artifactRoot,Q.document.project,Q.document.projectEditPlan),j$0(Q,F.settings.captions)]);return eg.parse({...F,captionBinding:J.binding,metadataBindings:Z.bindings})}function Vv0($,_,F){return mG.parse({kind:"slopcamera.project-render-plan-document",outputGeometrySha256:F.outputGeometrySha256,plan:vJ($),projectEditPlanSha256:_.projectEditPlanSha256,projectSha256:_.projectSha256,renderPlanSha256:m($),revisionSha256:_.revisionSha256,schemaVersion:1})}async function jZ($,_){let F=H8.parse(_),Q=await CV($,F.projectId),Z=g0(Q),J=await Z.readText(F.artifact.path);if(Fv(J)!==F.artifact.bytes||X0(J)!==F.artifact.sha256)throw new N("conflict","Immutable project render plan artifact failed its byte and SHA-256 identity.");let X=mG.parse(_v(J,"Project render plan artifact"));if(J!==`${R(X)}
|
|
@@ -2079,7 +2079,7 @@ ${H}${K}trailer
|
|
|
2079
2079
|
startxref
|
|
2080
2080
|
${Y}
|
|
2081
2081
|
%%EOF
|
|
2082
|
-
`);let j=Buffer.from(J.join(""));if(j.length>33554432)throw Error("Drawing PDF exceeds output byte limit");return j}var HD="3.3.5";var u60="patent-line-art-v1",cA=1048576,Wh=9.070866141732283;class nA extends Error{constructor($){super(`Invalid drawing source: ${$}`);this.name="DrawingValidationError"}}function E2($){throw new nA($)}var sA=($)=>Cd0("sha256").update($).digest("hex"),v60=($)=>Rd0($)?$:Td0(new URL($,import.meta.url)),Nh=[v60(rM),v60(NX)],Ed0={background:"#ffffff",foreground:"#000000",muted:"#000000",stroke:"#000000",tones:Object.fromEntries(["neutral","blue","orange","green","red","purple","yellow"].map(($)=>[$,{fill:"#ffffff",stroke:"#000000",text:"#000000"}]))},Pd0={font:{family:"Nebula Sans",files:[{path:Nh[0],weight:400},{path:Nh[1],weight:700}]},theme:{light:Ed0}},Id0=($)=>$.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""");function Gh($){if($!=="us-letter"&&$!=="a4")E2("paper must be us-letter or a4");let _=$==="us-letter"?612:595.2755905511812,F=$==="us-letter"?792:841.8897637795276,Q={left:70.86614173228347,top:70.86614173228347,right:42.51968503937008,bottom:28.34645669291339};return{width:_,height:F,margins:Q,numberingHeight:30,body:{x:Q.left,y:Q.top+30,width:_-Q.left-Q.right,height:F-Q.top-Q.bottom-60}}}function AZ($,_,F){if(typeof $!=="object"||$===null||Array.isArray($))E2(`${F} must be an object`);let Q=$;for(let Z of Object.keys(Q))if(!_.includes(Z))E2(`${F}.${Z} is unsupported`);return Q}function bd0($){let _=AZ($,["$schema","version","name","canvas","layout","shapes","edges"],"diagram"),F=(Q)=>{for(let Z of Object.values(Q)){if(typeof Z==="number"&&(!Number.isFinite(Z)||Math.abs(Z)>1e4))E2("numeric drawing values must be finite and within 10000 points");if(typeof Z==="string"&&Z.length>1024)E2("drawing strings exceed the bounded text limit")}};if(F(_),F(AZ(_.canvas,["width","height","padding"],"canvas")),_.layout!==void 0)F(AZ(_.layout,["type","direction","gap","align"],"layout"));if(!Array.isArray(_.shapes)||_.shapes.length<1||_.shapes.length>100)E2("each sheet needs 1 to 100 shapes");for(let Q of _.shapes){let Z=AZ(Q,["id","type","x","y","tone","opacity","width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap","text","fontSize","fontFamily","weight","align","x2","y2"],"shape");F(Z);let J=["id","type","x","y","tone","opacity"],X=Z.type==="text"?["text","width","fontSize","fontFamily","weight","align"]:Z.type==="line"?["x2","y2","strokeWidth"]:["width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap"];if(AZ(Q,[...J,...X],"shape"),Z.labelRows!==void 0){if(!Array.isArray(Z.labelRows)||Z.labelRows.length>4)E2("labelRows must be bounded");for(let Y of Z.labelRows)F(AZ(Y,["text","fontSize","fontFamily","weight"],"label row"))}for(let Y of["label","text"])if(typeof Z[Y]==="string"&&Z[Y].length>500)E2("label exceeds text limit")}if(_.edges!==void 0){if(!Array.isArray(_.edges)||_.edges.length>150)E2("at most 150 edges are supported");for(let Q of _.edges)F(AZ(Q,["id","from","to","label","tone","start","end","bend","arrowhead","startPosition","endPosition","labelFontSize","labelFontFamily","labelWeight","labelPosition","labelOffset"],"edge"))}}function rA($){let _=AZ($,["$schema","version","name","title","paper","sheets"],"drawing");if(_.version!==1)E2("version must be 1");if(typeof _.name!=="string"||_.name.length>100||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(_.name))E2("name must be a bounded lowercase hyphenated name");if(_.paper!=="us-letter"&&_.paper!=="a4")E2("paper must be us-letter or a4");if(_.title!==void 0&&(typeof _.title!=="string"||_.title.length<1||Buffer.byteLength(_.title)>1024||/[\u0000-\u001f]/u.test(_.title)))E2("title must be a bounded metadata string");if(_.$schema!==void 0&&typeof _.$schema!=="string")E2("$schema must be a string");if(!Array.isArray(_.sheets)||_.sheets.length<1||_.sheets.length>20)E2("sheets must contain 1 to 20 sheets");let F=_.sheets.map((Z,J)=>{let X=AZ(Z,["figure","diagram"],`sheets[${J}]`);if(X.figure!==J+1)E2("figure numbers must be consecutive beginning at 1");bd0(X.diagram);let Y=Aw(X.diagram),H=M_(Y);if(H.shapes.length<1||H.shapes.length>100||(H.edges?.length??0)>150)E2("each sheet needs 1 to 100 shapes and at most 150 edges");return{figure:J+1,diagram:Y}}),Q={version:1,name:_.name,paper:_.paper,sheets:F,..._.title===void 0?{}:{title:_.title},..._.$schema===void 0?{}:{$schema:_.$schema}};if(Buffer.byteLength(JSON.stringify(Q))>cA)E2("source exceeds 1MiB byte limit");return Q}function pA($){return new qd0($,{font:{fontFiles:Nh,loadSystemFonts:!1,defaultFontFamily:"Nebula Sans"},logLevel:"off"})}function Oh($){let _=$.getBBox();if(_===void 0)E2("empty drawing ink");return{x:_.x,y:_.y,width:_.width,height:_.height}}function x60($,_,F){if($.x<_.x-0.01||$.y<_.y-0.01||$.x+$.width>_.x+_.width+0.01||$.y+$.height>_.y+_.height+0.01)E2(`${F} ink extends beyond its bounds`)}async function h60($){return(await B9($,"light",Pd0,{edgeStrokeWidth:1})).svg.replace('<rect width="100%" height="100%" fill="#ffffff"/>',"")}function l60($,_,F){let Q=`<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><text x="100" y="500" font-family="Nebula Sans" font-size="${_}" font-weight="${F}">${Id0($)}</text></svg>`;return Oh(pA(Q)).height}function Sd0($,_){let F=1/0,Q=(Z,J,X,Y)=>{if(Z.length<1||Z.length>500||!Array.from(Z).every((H)=>/^[A-Z0-9 \n]$/u.test(H)||".,:;()[]/+=_*'!?%-".includes(H)))E2("visible labels must be uppercase ASCII letters, numbers, spaces, or supported punctuation; labels are never rewritten");if(Y!==void 0&&Y!=="default")E2("only the bundled default font is supported");if(!Number.isFinite(J)||J<=0||J>18)E2("authored font size must be positive and at most 18 points, below the 20 point sheet numbering");for(let H of new Set(Z.match(/[A-Z0-9]/gu)??[])){let K=`${H}:${J}:${X}`,j=_.get(K)??l60(H,J,X);if(_.set(K,j),_.size>4096)E2("glyph measurement limit exceeded");if(F=Math.min(F,j),j+0.001<Wh)E2(`glyph ${H} has ${j.toFixed(3)}pt ink height; minimum is ${Wh.toFixed(3)}pt (3.2mm)`)}};for(let Z of $.shapes){if(Z.tone!==void 0&&Z.tone!=="neutral")E2("colored tones are unsupported; author monochrome relationships explicitly");if(Z.opacity!==void 0&&Z.opacity!==1)E2("transparency is unsupported");if(Z.type==="rect"||Z.type==="ellipse"){if(Z.icon!==void 0)E2("icons are unsupported");if((Z.strokeWidth??2)<0.5||(Z.strokeWidth??2)>4)E2("stroke width must be 0.5 to 4 points");for(let J of OX(Z).rows)Q(J.text,J.fontSize,J.weight,J.fontFamily)}else if(Z.type==="text")Q(Z.text,Z.fontSize??24,Z.weight??500,Z.fontFamily);else if((Z.strokeWidth??3)<0.5||(Z.strokeWidth??3)>4)E2("stroke width must be 0.5 to 4 points")}for(let Z of $.edges??[]){if(Z.tone!==void 0&&Z.tone!=="neutral")E2("colored edge tones are unsupported");if(Z.label!==void 0)Q(Z.label,Z.labelFontSize??18,Z.labelWeight??600,Z.labelFontFamily)}return F}async function oA($,_){let F=rA($),Q=_??sA(JSON.stringify(F));if(!/^[a-f0-9]{64}$/u.test(Q))E2("source SHA-256 is invalid");let Z=Gh(F.paper),J=[],X=new Map,Y=1/0;for(let K of F.sheets){let j=M_(K.diagram);if(j.canvas.width>Z.body.width+0.001||j.canvas.height>Z.body.height+0.001)E2(`figure ${K.figure} canvas exceeds ${Z.body.width.toFixed(3)} by ${Z.body.height.toFixed(3)}pt body; no automatic scaling is performed`);Y=Math.min(Y,Sd0(j,X));let V=await h60(j);x60(Oh(pA(V)),{x:0,y:0,width:j.canvas.width,height:j.canvas.height},`figure ${K.figure}`);for(let C of j.shapes)if((C.type==="rect"||C.type==="ellipse")&&(C.label!==void 0||C.labelRows!==void 0)){let B=(C.strokeWidth??2)/2,z=await h60({...j,shapes:[C],edges:[]});x60(Oh(pA(z)),{x:C.x-B,y:C.y-B,width:C.width+B*2,height:C.height+B*2},`shape ${C.id} label`)}let O=V.replace(/^<svg[^>]*>/u,"").replace(/<\/svg>$/u,""),W=Z.body.x+(Z.body.width-j.canvas.width)/2,G=`${K.figure}/${F.sheets.length}`,D=F.sheets.length===1?"":`<text x="${Z.width/2}" y="${Z.height-Z.margins.bottom-8}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">FIG. ${K.figure}</text>`,w=`<svg xmlns="http://www.w3.org/2000/svg" width="${Z.width}" height="${Z.height}" viewBox="0 0 ${Z.width} ${Z.height}"><rect width="100%" height="100%" fill="#ffffff"/><text x="${Z.width/2}" y="${Z.margins.top+21}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">${G}</text><g transform="translate(${W} ${Z.body.y})">${O}</g>${D}</svg>`,L=pA(w).toString().replace(/width="[^"]+" height="[^"]+" viewBox="[^"]+"/u,`width="${Z.width}pt" height="${Z.height}pt" viewBox="0 0 ${Z.width} ${Z.height}"`);if(Buffer.byteLength(L)>2097152)E2("sheet SVG exceeds output byte limit");J.push({svg:L,width:Z.width,height:Z.height,figure:K.figure})}for(let K of"FIG0123456789")Y=Math.min(Y,l60(K,20,400));if(Y+0.001<Wh)E2("sheet numbering falls below minimum glyph height");let H={profile:u60,paper:F.paper,sheetCount:F.sheets.length,minGlyphHeightPt:Y,findings:[]};return{sheets:J,checks:H,pdf:g60(J,{title:F.title??F.name,sourceSha256:Q,rendererVersion:HD})}}async function iA($){let _=m60($);if(!_.endsWith(".drawing.json"))E2("source filename must end in .drawing.json");let F=await zd0(_,Kh.O_RDONLY|Kh.O_NOFOLLOW|Kh.O_NONBLOCK),Q;try{let J=await F.stat();if(!J.isFile())E2("source must be a regular file");if(J.size>cA)E2("source exceeds 1MiB byte limit");let X=Buffer.alloc(cA+1),Y=0;while(Y<X.length){let H=await F.read(X,Y,X.length-Y,Y);if(H.bytesRead===0)break;Y+=H.bytesRead}if(Y>cA)E2("source exceeds 1MiB byte limit");Q=X.subarray(0,Y)}finally{await F.close()}let Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Q));return{absolutePath:_,source:rA(Z),sourceSha256:sA(Q)}}async function d60($){let{source:_,sourceSha256:F}=await iA($.filePath);return(await oA(_,F)).checks}async function Vh($,_){let F=`${$}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await Md0(F,_),await Ud0(F,$)}catch(Q){throw await kd0(F,{force:!0}),Q}}async function c60($){let{absolutePath:_,source:F,sourceSha256:Q}=await iA($.filePath),Z=await oA(F,Q),J=m60($.outDirectory??Ad0(_)),X={source:_,pdf:jh(J,`${F.name}.pdf`),sheets:Z.sheets.map((H,K)=>jh(J,`${F.name}.sheet-${String(K+1).padStart(3,"0")}.svg`)),receipt:jh(J,`${F.name}.drawing-receipt.json`)},Y={version:1,profile:u60,rendererVersion:HD,sourceSha256:Q,paper:F.paper,minGlyphHeightPt:Z.checks.minGlyphHeightPt,sheets:Z.sheets.map((H)=>({figure:H.figure,widthPt:H.width,heightPt:H.height,sha256:sA(H.svg)})),pdfSha256:sA(Z.pdf)};await Bd0(J,{recursive:!0});for(let[H,K]of Z.sheets.entries())await Vh(X.sheets[H],K.svg);return await Vh(X.pdf,Z.pdf),await Vh(X.receipt,`${JSON.stringify(Y,null,2)}
|
|
2082
|
+
`);let j=Buffer.from(J.join(""));if(j.length>33554432)throw Error("Drawing PDF exceeds output byte limit");return j}var HD="3.3.6";var u60="patent-line-art-v1",cA=1048576,Wh=9.070866141732283;class nA extends Error{constructor($){super(`Invalid drawing source: ${$}`);this.name="DrawingValidationError"}}function E2($){throw new nA($)}var sA=($)=>Cd0("sha256").update($).digest("hex"),v60=($)=>Rd0($)?$:Td0(new URL($,import.meta.url)),Nh=[v60(rM),v60(NX)],Ed0={background:"#ffffff",foreground:"#000000",muted:"#000000",stroke:"#000000",tones:Object.fromEntries(["neutral","blue","orange","green","red","purple","yellow"].map(($)=>[$,{fill:"#ffffff",stroke:"#000000",text:"#000000"}]))},Pd0={font:{family:"Nebula Sans",files:[{path:Nh[0],weight:400},{path:Nh[1],weight:700}]},theme:{light:Ed0}},Id0=($)=>$.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""");function Gh($){if($!=="us-letter"&&$!=="a4")E2("paper must be us-letter or a4");let _=$==="us-letter"?612:595.2755905511812,F=$==="us-letter"?792:841.8897637795276,Q={left:70.86614173228347,top:70.86614173228347,right:42.51968503937008,bottom:28.34645669291339};return{width:_,height:F,margins:Q,numberingHeight:30,body:{x:Q.left,y:Q.top+30,width:_-Q.left-Q.right,height:F-Q.top-Q.bottom-60}}}function AZ($,_,F){if(typeof $!=="object"||$===null||Array.isArray($))E2(`${F} must be an object`);let Q=$;for(let Z of Object.keys(Q))if(!_.includes(Z))E2(`${F}.${Z} is unsupported`);return Q}function bd0($){let _=AZ($,["$schema","version","name","canvas","layout","shapes","edges"],"diagram"),F=(Q)=>{for(let Z of Object.values(Q)){if(typeof Z==="number"&&(!Number.isFinite(Z)||Math.abs(Z)>1e4))E2("numeric drawing values must be finite and within 10000 points");if(typeof Z==="string"&&Z.length>1024)E2("drawing strings exceed the bounded text limit")}};if(F(_),F(AZ(_.canvas,["width","height","padding"],"canvas")),_.layout!==void 0)F(AZ(_.layout,["type","direction","gap","align"],"layout"));if(!Array.isArray(_.shapes)||_.shapes.length<1||_.shapes.length>100)E2("each sheet needs 1 to 100 shapes");for(let Q of _.shapes){let Z=AZ(Q,["id","type","x","y","tone","opacity","width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap","text","fontSize","fontFamily","weight","align","x2","y2"],"shape");F(Z);let J=["id","type","x","y","tone","opacity"],X=Z.type==="text"?["text","width","fontSize","fontFamily","weight","align"]:Z.type==="line"?["x2","y2","strokeWidth"]:["width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap"];if(AZ(Q,[...J,...X],"shape"),Z.labelRows!==void 0){if(!Array.isArray(Z.labelRows)||Z.labelRows.length>4)E2("labelRows must be bounded");for(let Y of Z.labelRows)F(AZ(Y,["text","fontSize","fontFamily","weight"],"label row"))}for(let Y of["label","text"])if(typeof Z[Y]==="string"&&Z[Y].length>500)E2("label exceeds text limit")}if(_.edges!==void 0){if(!Array.isArray(_.edges)||_.edges.length>150)E2("at most 150 edges are supported");for(let Q of _.edges)F(AZ(Q,["id","from","to","label","tone","start","end","bend","arrowhead","startPosition","endPosition","labelFontSize","labelFontFamily","labelWeight","labelPosition","labelOffset"],"edge"))}}function rA($){let _=AZ($,["$schema","version","name","title","paper","sheets"],"drawing");if(_.version!==1)E2("version must be 1");if(typeof _.name!=="string"||_.name.length>100||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(_.name))E2("name must be a bounded lowercase hyphenated name");if(_.paper!=="us-letter"&&_.paper!=="a4")E2("paper must be us-letter or a4");if(_.title!==void 0&&(typeof _.title!=="string"||_.title.length<1||Buffer.byteLength(_.title)>1024||/[\u0000-\u001f]/u.test(_.title)))E2("title must be a bounded metadata string");if(_.$schema!==void 0&&typeof _.$schema!=="string")E2("$schema must be a string");if(!Array.isArray(_.sheets)||_.sheets.length<1||_.sheets.length>20)E2("sheets must contain 1 to 20 sheets");let F=_.sheets.map((Z,J)=>{let X=AZ(Z,["figure","diagram"],`sheets[${J}]`);if(X.figure!==J+1)E2("figure numbers must be consecutive beginning at 1");bd0(X.diagram);let Y=Aw(X.diagram),H=M_(Y);if(H.shapes.length<1||H.shapes.length>100||(H.edges?.length??0)>150)E2("each sheet needs 1 to 100 shapes and at most 150 edges");return{figure:J+1,diagram:Y}}),Q={version:1,name:_.name,paper:_.paper,sheets:F,..._.title===void 0?{}:{title:_.title},..._.$schema===void 0?{}:{$schema:_.$schema}};if(Buffer.byteLength(JSON.stringify(Q))>cA)E2("source exceeds 1MiB byte limit");return Q}function pA($){return new qd0($,{font:{fontFiles:Nh,loadSystemFonts:!1,defaultFontFamily:"Nebula Sans"},logLevel:"off"})}function Oh($){let _=$.getBBox();if(_===void 0)E2("empty drawing ink");return{x:_.x,y:_.y,width:_.width,height:_.height}}function x60($,_,F){if($.x<_.x-0.01||$.y<_.y-0.01||$.x+$.width>_.x+_.width+0.01||$.y+$.height>_.y+_.height+0.01)E2(`${F} ink extends beyond its bounds`)}async function h60($){return(await B9($,"light",Pd0,{edgeStrokeWidth:1})).svg.replace('<rect width="100%" height="100%" fill="#ffffff"/>',"")}function l60($,_,F){let Q=`<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><text x="100" y="500" font-family="Nebula Sans" font-size="${_}" font-weight="${F}">${Id0($)}</text></svg>`;return Oh(pA(Q)).height}function Sd0($,_){let F=1/0,Q=(Z,J,X,Y)=>{if(Z.length<1||Z.length>500||!Array.from(Z).every((H)=>/^[A-Z0-9 \n]$/u.test(H)||".,:;()[]/+=_*'!?%-".includes(H)))E2("visible labels must be uppercase ASCII letters, numbers, spaces, or supported punctuation; labels are never rewritten");if(Y!==void 0&&Y!=="default")E2("only the bundled default font is supported");if(!Number.isFinite(J)||J<=0||J>18)E2("authored font size must be positive and at most 18 points, below the 20 point sheet numbering");for(let H of new Set(Z.match(/[A-Z0-9]/gu)??[])){let K=`${H}:${J}:${X}`,j=_.get(K)??l60(H,J,X);if(_.set(K,j),_.size>4096)E2("glyph measurement limit exceeded");if(F=Math.min(F,j),j+0.001<Wh)E2(`glyph ${H} has ${j.toFixed(3)}pt ink height; minimum is ${Wh.toFixed(3)}pt (3.2mm)`)}};for(let Z of $.shapes){if(Z.tone!==void 0&&Z.tone!=="neutral")E2("colored tones are unsupported; author monochrome relationships explicitly");if(Z.opacity!==void 0&&Z.opacity!==1)E2("transparency is unsupported");if(Z.type==="rect"||Z.type==="ellipse"){if(Z.icon!==void 0)E2("icons are unsupported");if((Z.strokeWidth??2)<0.5||(Z.strokeWidth??2)>4)E2("stroke width must be 0.5 to 4 points");for(let J of OX(Z).rows)Q(J.text,J.fontSize,J.weight,J.fontFamily)}else if(Z.type==="text")Q(Z.text,Z.fontSize??24,Z.weight??500,Z.fontFamily);else if((Z.strokeWidth??3)<0.5||(Z.strokeWidth??3)>4)E2("stroke width must be 0.5 to 4 points")}for(let Z of $.edges??[]){if(Z.tone!==void 0&&Z.tone!=="neutral")E2("colored edge tones are unsupported");if(Z.label!==void 0)Q(Z.label,Z.labelFontSize??18,Z.labelWeight??600,Z.labelFontFamily)}return F}async function oA($,_){let F=rA($),Q=_??sA(JSON.stringify(F));if(!/^[a-f0-9]{64}$/u.test(Q))E2("source SHA-256 is invalid");let Z=Gh(F.paper),J=[],X=new Map,Y=1/0;for(let K of F.sheets){let j=M_(K.diagram);if(j.canvas.width>Z.body.width+0.001||j.canvas.height>Z.body.height+0.001)E2(`figure ${K.figure} canvas exceeds ${Z.body.width.toFixed(3)} by ${Z.body.height.toFixed(3)}pt body; no automatic scaling is performed`);Y=Math.min(Y,Sd0(j,X));let V=await h60(j);x60(Oh(pA(V)),{x:0,y:0,width:j.canvas.width,height:j.canvas.height},`figure ${K.figure}`);for(let C of j.shapes)if((C.type==="rect"||C.type==="ellipse")&&(C.label!==void 0||C.labelRows!==void 0)){let B=(C.strokeWidth??2)/2,z=await h60({...j,shapes:[C],edges:[]});x60(Oh(pA(z)),{x:C.x-B,y:C.y-B,width:C.width+B*2,height:C.height+B*2},`shape ${C.id} label`)}let O=V.replace(/^<svg[^>]*>/u,"").replace(/<\/svg>$/u,""),W=Z.body.x+(Z.body.width-j.canvas.width)/2,G=`${K.figure}/${F.sheets.length}`,D=F.sheets.length===1?"":`<text x="${Z.width/2}" y="${Z.height-Z.margins.bottom-8}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">FIG. ${K.figure}</text>`,w=`<svg xmlns="http://www.w3.org/2000/svg" width="${Z.width}" height="${Z.height}" viewBox="0 0 ${Z.width} ${Z.height}"><rect width="100%" height="100%" fill="#ffffff"/><text x="${Z.width/2}" y="${Z.margins.top+21}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">${G}</text><g transform="translate(${W} ${Z.body.y})">${O}</g>${D}</svg>`,L=pA(w).toString().replace(/width="[^"]+" height="[^"]+" viewBox="[^"]+"/u,`width="${Z.width}pt" height="${Z.height}pt" viewBox="0 0 ${Z.width} ${Z.height}"`);if(Buffer.byteLength(L)>2097152)E2("sheet SVG exceeds output byte limit");J.push({svg:L,width:Z.width,height:Z.height,figure:K.figure})}for(let K of"FIG0123456789")Y=Math.min(Y,l60(K,20,400));if(Y+0.001<Wh)E2("sheet numbering falls below minimum glyph height");let H={profile:u60,paper:F.paper,sheetCount:F.sheets.length,minGlyphHeightPt:Y,findings:[]};return{sheets:J,checks:H,pdf:g60(J,{title:F.title??F.name,sourceSha256:Q,rendererVersion:HD})}}async function iA($){let _=m60($);if(!_.endsWith(".drawing.json"))E2("source filename must end in .drawing.json");let F=await zd0(_,Kh.O_RDONLY|Kh.O_NOFOLLOW|Kh.O_NONBLOCK),Q;try{let J=await F.stat();if(!J.isFile())E2("source must be a regular file");if(J.size>cA)E2("source exceeds 1MiB byte limit");let X=Buffer.alloc(cA+1),Y=0;while(Y<X.length){let H=await F.read(X,Y,X.length-Y,Y);if(H.bytesRead===0)break;Y+=H.bytesRead}if(Y>cA)E2("source exceeds 1MiB byte limit");Q=X.subarray(0,Y)}finally{await F.close()}let Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Q));return{absolutePath:_,source:rA(Z),sourceSha256:sA(Q)}}async function d60($){let{source:_,sourceSha256:F}=await iA($.filePath);return(await oA(_,F)).checks}async function Vh($,_){let F=`${$}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await Md0(F,_),await Ud0(F,$)}catch(Q){throw await kd0(F,{force:!0}),Q}}async function c60($){let{absolutePath:_,source:F,sourceSha256:Q}=await iA($.filePath),Z=await oA(F,Q),J=m60($.outDirectory??Ad0(_)),X={source:_,pdf:jh(J,`${F.name}.pdf`),sheets:Z.sheets.map((H,K)=>jh(J,`${F.name}.sheet-${String(K+1).padStart(3,"0")}.svg`)),receipt:jh(J,`${F.name}.drawing-receipt.json`)},Y={version:1,profile:u60,rendererVersion:HD,sourceSha256:Q,paper:F.paper,minGlyphHeightPt:Z.checks.minGlyphHeightPt,sheets:Z.sheets.map((H)=>({figure:H.figure,widthPt:H.width,heightPt:H.height,sha256:sA(H.svg)})),pdfSha256:sA(Z.pdf)};await Bd0(J,{recursive:!0});for(let[H,K]of Z.sheets.entries())await Vh(X.sheets[H],K.svg);return await Vh(X.pdf,Z.pdf),await Vh(X.receipt,`${JSON.stringify(Y,null,2)}
|
|
2083
2083
|
`),{artifacts:X,checks:Z.checks,receipt:Y}}function p60(){return{$schema:"https://raw.githubusercontent.com/hraness/slopcamera/main/schema/drawing.schema.json",version:1,name:"sensor-control",title:"Fictional sensor and controller drawings",paper:"us-letter",sheets:[{figure:1,diagram:{version:1,name:"sensor-system",canvas:{width:480,height:500},shapes:[{id:"sensor",type:"rect",x:105,y:40,width:280,height:100,radius:0,label:"SENSOR 100",labelFontSize:16},{id:"controller",type:"rect",x:105,y:280,width:280,height:100,radius:0,label:"CONTROLLER 200",labelFontSize:16}],edges:[{id:"signal",from:"sensor",to:"controller",label:"SIGNAL",labelFontSize:16}]}},{figure:2,diagram:{version:1,name:"control-flow",canvas:{width:480,height:500},shapes:[{id:"receive",type:"rect",x:105,y:40,width:280,height:100,radius:0,label:"RECEIVE SIGNAL 210",labelFontSize:16},{id:"actuate",type:"rect",x:105,y:280,width:280,height:100,radius:0,label:"SET OUTPUT 220",labelFontSize:16}],edges:[{id:"next",from:"receive",to:"actuate"}]}}]}}import{randomUUID as qc0}from"crypto";import{mkdir as Ec0,readFile as Pc0,rename as Ic0,rm as bc0,writeFile as Sc0}from"fs/promises";import{dirname as kF0,join as $W,resolve as MF0}from"path";uV();XD();k6();import{createHash as cd0,randomBytes as $F0}from"crypto";import{chmodSync as pd0,closeSync as a9,constants as MX,fchmodSync as sd0,fstatSync as lQ,ftruncateSync as nd0,fsyncSync as _F0,lstatSync as BK,mkdirSync as rd0,openSync as Ch,readSync as od0,readdirSync as FF0,realpathSync as id0,renameSync as ad0,statSync as td0,unlinkSync as eA,writeSync as ed0}from"fs";import{availableParallelism as $c0,homedir as _c0}from"os";import{isAbsolute as Bh,join as uQ}from"path";import{performance as ND}from"perf_hooks";import{readFileSync as fd0}from"fs";import{createRequire as yd0}from"module";var gd0=2,vd0=4,xd0=8,r60=4,tV,s60=[],hd0=yd0(import.meta.url);function md0(){return hd0("bun:ffi")}function n60($,_=process.arch){let F=[],Q=(Z)=>{if(!F.includes(Z))F.push(Z)};for(let Z of $.split(`
|
|
2084
2084
|
`)){let J=Z.indexOf("/");if(J<0||Z.endsWith(" (deleted)"))continue;let X=Z.slice(J).replace(/\\([0-7]{3})/gu,(Y,H)=>String.fromCodePoint(Number.parseInt(H,8)));if(/\/(?:libc(?:-[^/]+)?\.so(?:\.[0-9]+)*|libc\.musl-[^/]+\.so(?:\.[0-9]+)*|ld-musl-[^/]+\.so(?:\.[0-9]+)*)$/u.test(X))Q(X)}if(Q("libc.so.6"),_==="x64")Q("/lib/ld-musl-x86_64.so.1");if(_==="arm64")Q("/lib/ld-musl-aarch64.so.1");return F}function ud0(){try{return n60(fd0("/proc/self/maps","utf8"))}catch{return n60("")}}function o60(){if(tV!==void 0)return tV;let{dlopen:$,FFIType:_,read:F}=md0();if(process.platform==="darwin"){let Q=$("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:_.ptr},flock:{args:[_.i32,_.i32],returns:_.i32}});return s60.push(Q),tV={errnoLocation:Q.symbols.__error,flock:Q.symbols.flock,readInt32:F.i32},tV}if(process.platform==="linux"){let Q=[];for(let Z of ud0())try{let J=$(Z,{__errno_location:{args:[],returns:_.ptr},flock:{args:[_.i32,_.i32],returns:_.i32}});return s60.push(J),tV={errnoLocation:J.symbols.__errno_location,flock:J.symbols.flock,readInt32:F.i32},tV}catch(J){Q.push(`${Z}: ${J instanceof Error?J.message:String(J)}`)}throw Error(`Slopcamera could not load host flock support (${Q.join("; ")}).`)}throw Error(`Slopcamera host-resource coordination is unsupported on ${process.platform}.`)}function i60($){let _=$.errnoLocation();if(_===null)throw Error("Slopcamera could not read the host flock error.");return $.readInt32(_)}function ld0($){return process.platform==="darwin"?$===35:$===11}var dd0=Object.freeze(["darwin","linux"]);function aA($){return dd0.some((_)=>_===$)}function KD($){let _=o60();for(;;){if(_.flock($,gd0|vd0)===0)return!0;let F=i60(_);if(F===r60)continue;if(ld0(F))return!1;throw Error(`Slopcamera host-resource flock failed with errno ${F}.`)}}function jD($){let _=o60();for(;;){if(_.flock($,xd0)===0)return;let F=i60(_);if(F===r60)continue;throw Error(`Slopcamera host-resource unlock failed with errno ${F}.`)}}var Fc0=/^[a-z0-9][a-z0-9._/-]{0,119}$/u,Qc0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Zc0=/^[0-9a-f]{32}$/u,QF0=/^[1-9][0-9]{0,19}$/u,zh=/^lease-([0-9]{20})-([0-9a-f]{32})\.lock$/u,Jc0=/^\.host-resources-[0-9a-f]{32}\.tmp$/u,Uh="state.json",ZF0="control.lock",JF0="initialized.lock",a60=64,Xc0=64,Yc0=1024,XF0=65536,YF0=4096,HF0=1e6,kh=0xffff_ffff_ffff_ffffn,KF0=25,jF0=35000,Hc0=250,Kc0=4,t60=8,A6=86400000,rT1=Object.freeze(["cpu","local-io","ffmpeg","video-encode","vision","whisper","network","paid-call","browser","capture-device"]);class P2 extends Error{code;constructor($,_,F){super(`[${$}] ${_}`,F===void 0?void 0:{cause:F});this.name="HostResourceError",this.code=$}}function OD($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function $R($,_){let F=Object.keys($).sort(),Q=[..._].sort();return F.length===Q.length&&F.every((Z,J)=>Z===Q[J])}function Mh($,_){return Number.isSafeInteger($)&&$>=1&&$<=_}function Ah($){if(typeof $!=="object"||$===null||Object.isFrozen($))return $;for(let _ of Object.values($))Ah(_);return Object.freeze($)}function VF0($,_,F){let Q=F==="INVALID_CLAIMS"?0:1;if(!Array.isArray($)||$.length<Q||$.length>a60)throw new P2(F,`Host-resource ${_==="limit"?"capacities":"claims"} must contain ${Q} through ${a60} entries.`);let Z=new Set;return $.map((X)=>{if(!OD(X)||!$R(X,["resource",_])||typeof X.resource!=="string"||!Qc0.test(X.resource)||!Mh(X[_],HF0)||Z.has(X.resource))throw new P2(F,`Host-resource ${_==="limit"?"capacities":"claims"} are malformed or duplicated.`);return Z.add(X.resource),{resource:X.resource,value:X[_]}}).sort((X,Y)=>X.resource<Y.resource?-1:X.resource>Y.resource?1:0)}function GD($){if(!OD($)||!$R($,["id","capacities"])||typeof $.id!=="string"||!Fc0.test($.id))throw new P2("INVALID_PROFILE","Host-resource profile identity is invalid.");let _=VF0($.capacities,"limit","INVALID_PROFILE").map(({resource:F,value:Q})=>({resource:F,limit:Q}));return Ah({id:$.id,capacities:_})}function Rh($,_){let F=GD(_),Q=new Map(F.capacities.map(({resource:J,limit:X})=>[J,X])),Z=VF0($,"amount","INVALID_CLAIMS").map(({resource:J,value:X})=>{let Y=Q.get(J);if(Y===void 0||X>Y)throw new P2("INVALID_CLAIMS",`Host-resource claim ${J} is unavailable or exceeds its profile limit.`);return{resource:J,amount:X}});return Ah(Z)}function WF0($=$c0()){if(!Mh($,HF0))throw new P2("INVALID_PROFILE","Host parallelism must be a positive safe integer.");let _=$>=6?2:$>=2?1:0;return GD({id:"slopcamera.host-resources/v1",capacities:[{resource:"cpu",limit:Math.max(1,$-_)},{resource:"local-io",limit:2},{resource:"ffmpeg",limit:2},{resource:"video-encode",limit:1},{resource:"vision",limit:1},{resource:"whisper",limit:1},{resource:"network",limit:4},{resource:"paid-call",limit:1},{resource:"browser",limit:1},{resource:"capture-device",limit:1}]})}function jc0($=process.platform,_=process.env,F=_c0()){if(!aA($))throw new P2("UNSUPPORTED_PLATFORM","Slopcamera host-resource coordination requires Darwin or Linux.");if($==="darwin")return uQ(F,"Library","Application Support","Slopcamera","cli","host-resources-v1");let Q=_.XDG_STATE_HOME,Z=Q!==void 0&&Bh(Q)?Q:uQ(F,".local","state");return uQ(Z,"slopcamera","host-resources-v1")}function VD($){return JSON.stringify($)}function Th($){return cd0("sha256").update($).digest("hex")}function u2($,_){return new P2("UNSAFE_STATE",$,_)}function wD($,_){return OD($)&&$.code===_}function NF0(){let $=process.geteuid?.()??process.getuid?.();if($===void 0)throw u2("Host-resource owner identity is unavailable.");return $}function OF0($){return{device:$.dev,inode:$.ino}}function WD($,_){let F="device"in _?_.device:_.dev,Q="inode"in _?_.inode:_.ino;return $.device===F&&$.inode===Q}function Dh($){return $.isDirectory()&&!$.isSymbolicLink()&&$.uid===NF0()&&($.mode&511)===448}function RZ($){return $.isFile()&&!$.isSymbolicLink()&&$.nlink===1&&$.uid===NF0()&&($.mode&511)===384}function CK($){try{return BK($)}catch(_){if(wD(_,"ENOENT"))return null;throw _}}function Vc0($){if(!Bh($)||$.includes("\x00")||Buffer.byteLength($,"utf8")>YF0)throw u2("Host-resource state root must be a bounded absolute path.");let _=!1,F=CK($);if(F===null){try{rd0($,{recursive:!0,mode:448}),_=!0}catch(Z){if(!wD(Z,"EEXIST"))throw u2("Host-resource state root could not be created.",Z)}if(F=BK($),_)pd0($,448)}if(!Dh(F))throw u2("Host-resource state root is not one private owned directory.");let Q=id0($);if(!Dh(td0(Q)))throw u2("Host-resource state root canonicalization is unsafe.");return{path:Q}}function mQ($,_=!1){let F=CK($);if(F!==null&&!RZ(F))throw u2("Host-resource state contains an unsafe file.");let Q=MX.O_RDWR|MX.O_CREAT|MX.O_NOFOLLOW|(_?MX.O_EXCL:0),Z=Ch($,Q,384);try{sd0(Z,384);let J=lQ(Z),X=BK($);if(!RZ(J)||!RZ(X)||J.dev!==X.dev||J.ino!==X.ino)throw u2("Host-resource file identity changed while opening.");return Z}catch(J){throw a9(Z),J}}function GF0($){let _=lQ($);if(!RZ(_)||_.size>XF0)throw u2("Host-resource state file is malformed.");let F=Buffer.alloc(_.size),Q=0;while(Q<F.length){let Z=od0($,F,Q,F.length-Q,Q);if(Z===0)break;Q+=Z}if(Q!==F.length)throw u2("Host-resource state read was incomplete.");return F.toString("utf8")}function qh($,_){let F=Buffer.from(_,"utf8");if(F.length>XF0)throw u2("Host-resource state write exceeds its bound.");nd0($,0);let Q=0;while(Q<F.length){let Z=ed0($,F,Q,F.length-Q,Q);if(Z<1)throw u2("Host-resource state write was incomplete.");Q+=Z}_F0($)}function wF0($){return JSON.stringify({version:$.version,profile:$.profile,nextTicket:$.nextTicket})}function AX($){return JSON.stringify({version:$.version,owner:$.owner,profileSha256:$.profileSha256,ticket:$.ticket,phase:$.phase,claims:$.claims})}function Lh($){let _=Ch($,MX.O_RDONLY|MX.O_DIRECTORY|MX.O_NOFOLLOW);try{if(!Dh(lQ(_)))throw u2("Host-resource state root changed identity.");_F0(_)}finally{a9(_)}}function DF0($,_){let F=`.host-resources-${$F0(16).toString("hex")}.tmp`,Q=uQ($,F),Z=uQ($,Uh),J;try{J=mQ(Q,!0),qh(J,wF0(_)),a9(J),J=void 0;let X=CK(Z);if(X!==null&&!RZ(X))throw u2("Host-resource profile state is unsafe.");ad0(Q,Z);let Y=BK(Z);if(!RZ(Y))throw u2("Host-resource profile state was not published safely.");Lh($)}finally{if(J!==void 0)a9(J);try{eA(Q)}catch(X){if(!wD(X,"ENOENT"));}}}function Wc0($){let _;try{_=JSON.parse($)}catch(J){throw u2("Host-resource profile state is not valid JSON.",J)}if(!OD(_)||!$R(_,["version","profile","nextTicket"])||_.version!==1||typeof _.nextTicket!=="string"||!QF0.test(_.nextTicket))throw u2("Host-resource profile state is malformed.");let F;try{F=GD(_.profile)}catch(J){throw u2("Host-resource profile state is malformed.",J)}if(BigInt(_.nextTicket)>kh+1n)throw u2("Host-resource ticket state exceeds its bound.");let Z={version:1,profile:F,nextTicket:_.nextTicket};if(wF0(Z)!==$)throw u2("Host-resource profile state is not normalized.");return Z}function Nc0($,_){let F=uQ($,Uh),Q=uQ($,JF0);if(CK(F)===null){if(CK(Q)!==null||FF0($).some((Y)=>zh.test(Y)))throw u2("Host-resource profile state is missing.");let J={version:1,profile:_,nextTicket:"1"};DF0($,J);let X=mQ(Q,!0);return a9(X),Lh($),J}let Z=mQ(F);try{let J=Wc0(GF0(Z)),X=CK(Q)===null,Y=X?mQ(Q,!0):mQ(Q);try{if(lQ(Y).size!==0)throw u2("Host-resource initialization state is malformed.")}finally{a9(Y)}if(X)Lh($);return J}finally{a9(Z)}}function _R($,_){if(VD($.profile)===VD(_))return;throw new P2("PROFILE_MISMATCH","The machine-global Slopcamera host-resource profile does not match this process.")}function Oc0($,_){let F=BigInt(_.nextTicket);if(F>kh)throw u2("Host-resource tickets are exhausted.");return DF0($,{..._,nextTicket:String(F+1n)}),String(F)}function eV($,_,F,Q,Z){let J=$??_;if(!Mh(J,F))throw new P2(Q,`${Z} is outside its supported bound.`);return J}function tA($,_){if($?.aborted===!0)throw new P2("WAIT_ABORTED","Host-resource admission was cancelled before execution.");if(ND.now()>=_)throw new P2("WAIT_TIMEOUT","Host-resource admission exceeded its bounded wait.")}async function LF0($,_,F){tA(_,F);let Q=Math.max(1,Math.ceil(F-ND.now()));await new Promise((Z,J)=>{let X=!1,Y=()=>{if(X)return;X=!0,_?.removeEventListener("abort",H),Z()},H=()=>{if(X)return;X=!0,clearTimeout(K),_?.removeEventListener("abort",H),J(new P2("WAIT_ABORTED","Host-resource admission was cancelled before execution."))},K=setTimeout(Y,Math.min($,Q));if(_?.addEventListener("abort",H,{once:!0}),_?.aborted===!0)H()}),tA(_,F)}function Gc0($,_){let F=0xffff_ffff_ffff_ffffn,Q=BigInt($)+BigInt(_+1)*0x9e37_79b9_7f4a_7c15n&F;return Q=(Q^Q>>30n)*0xbf58_476d_1ce4_e5b9n&F,Q=(Q^Q>>27n)*0x94d0_49bb_1331_11ebn&F,(Q^Q>>31n)&F}function wc0($,_,F){let Q=$<=Kc0?$:Math.max($,Math.min(Hc0,$*t60)),Z=Math.min(F,Math.ceil(Math.log2(t60))),J=Math.min(Q,$*2**Z),X=Math.max(1,Math.ceil(J/2)),Y=J-X+1,H=Number(Gc0(_,F)%BigInt(Y));return X+H}async function FR($,_,F,Q,Z){let J=mQ(uQ($,ZF0)),X=!1;try{while(!(X=KD(J)))await LF0(_,F,Q);return tA(F,Q),Z()}catch(Y){if(Y instanceof P2)throw Y;throw u2("Host-resource control locking failed.",Y)}finally{if(X)try{jD(J)}catch{}a9(J)}}function CF0($){return $.padStart(20,"0")}function Dc0($,_,F,Q){let Z=zh.exec($),J;try{J=JSON.parse(_)}catch(H){throw u2("A live host-resource marker is not valid JSON.",H)}if(Z===null||!OD(J)||!$R(J,["version","owner","profileSha256","ticket","phase","claims"])||J.version!==1||typeof J.owner!=="string"||!Zc0.test(J.owner)||typeof J.profileSha256!=="string"||!/^[0-9a-f]{64}$/u.test(J.profileSha256)||typeof J.ticket!=="string"||!QF0.test(J.ticket)||J.phase!=="A"&&J.phase!=="W"||CF0(J.ticket)!==Z[1]||J.owner!==Z[2])throw u2("A live host-resource marker is malformed.");if(J.profileSha256!==Q)throw new P2("PROFILE_MISMATCH","A live lease belongs to a different host-resource profile.");let X;try{X=Rh(J.claims,F)}catch(H){throw u2("A live host-resource marker has invalid claims.",H)}let Y={version:1,owner:J.owner,profileSha256:J.profileSha256,ticket:J.ticket,phase:J.phase,claims:X};if(AX(Y)!==_)throw u2("A live host-resource marker is not normalized.");return Y}function BF0($,_){let F=BK($);if(!RZ(F)||!WD(_,F))throw new P2("OWNERSHIP_LOST","Host-resource marker identity changed before cleanup.");eA($)}function Lc0($){let _=mQ($);try{let F=lQ(_),Q=BK($);if(F.dev!==Q.dev||F.ino!==Q.ino)throw u2("Host-resource temporary state changed identity.");eA($)}finally{a9(_)}}function Eh($,_,F){let Q=FF0($,{withFileTypes:!0});if(Q.length>Yc0)throw u2("Host-resource state contains too many entries.");let Z=[],J=new Set,X=new Set;for(let Y of Q){if(Y.name===ZF0||Y.name===Uh||Y.name===JF0)continue;let H=uQ($,Y.name);if(Jc0.test(Y.name)){if(!Y.isFile()||Y.isSymbolicLink())throw u2("Host-resource temporary state is unsafe.");Lc0(H);continue}if(!zh.test(Y.name))throw u2("Host-resource state contains an unknown entry.");let K=mQ(H),j=!1;try{let V=lQ(K),O=OF0(V);if(j=KD(K),j){BF0(H,O);continue}let W=Dc0(Y.name,GF0(K),_,F);if(J.has(W.ticket)||X.has(W.owner))throw u2("Live host-resource marker identity is duplicated.");J.add(W.ticket),X.add(W.owner),Z.push({document:W,identity:O,name:Y.name,path:H})}finally{if(j)try{jD(K)}catch{}a9(K)}}return Z.sort((Y,H)=>{let K=BigInt(Y.document.ticket),j=BigInt(H.document.ticket);return K<j?-1:K>j?1:0})}function zF0($){if($.released)throw new P2("OWNERSHIP_LOST","Host-resource lease is no longer active.");let _,F;try{_=lQ($.descriptor),F=BK($.path)}catch(Q){throw new P2("OWNERSHIP_LOST","Host-resource marker is no longer reachable.",Q)}if(!RZ(_)||!RZ(F)||!WD($.identity,_)||!WD($.identity,F))throw new P2("OWNERSHIP_LOST","Host-resource descriptor no longer owns its published inode.")}function Cc0($,_,F,Q){let Z=Oc0($,_),J=$F0(16).toString("hex"),X=`lease-${CF0(Z)}-${J}.lock`,Y=uQ($,X),H;try{if(H=mQ(Y,!0),!KD(H))throw u2("A new host-resource marker could not be locked.");let K={version:1,owner:J,profileSha256:Q,ticket:Z,phase:"W",claims:F};return qh(H,AX(K)),{descriptor:H,document:K,identity:OF0(lQ(H)),name:X,path:Y,released:!1}}catch(K){if(H!==void 0){try{jD(H)}catch{}a9(H)}try{eA(Y)}catch(j){if(!wD(j,"ENOENT"));}throw K}}function Ph($,_){return $.name===_.name&&$.document.owner===_.document.owner&&$.document.ticket===_.document.ticket&&WD($.identity,_.identity)}function Ih($,_){let F=new Set($.map(({resource:Q})=>Q));return _.some(({resource:Q})=>F.has(Q))}function UF0($,_,F){let Q=new Map;for(let Z of _)for(let J of Z.document.claims)Q.set(J.resource,(Q.get(J.resource)??0)+J.amount);for(let{resource:Z,limit:J}of $.capacities)if((Q.get(Z)??0)>J)throw u2("Live host-resource leases exceed the declared profile.");return F.every(({resource:Z,amount:J})=>{let X=$.capacities.find((Y)=>Y.resource===Z)?.limit;return X!==void 0&&(Q.get(Z)??0)+J<=X})}function e60($,_){let F=BigInt($.document.ticket),Q=_.filter((Z)=>{if(Ph(Z,$))return!1;if(!Ih(Z.document.claims,$.document.claims))return!1;return Z.document.phase==="A"||BigInt(Z.document.ticket)<F});return Th(Q.map((Z)=>`${Z.name}\x00${AX(Z.document)}`).join(`
|
|
2085
2085
|
`))}function Bc0($,_,F){zF0($);let Q=_.find((H)=>Ph(H,$));if(Q===void 0||Q.document.phase!==$.document.phase||AX(Q.document)!==AX($.document))throw new P2("OWNERSHIP_LOST","Host-resource lease marker no longer matches its descriptor.");let Z=BigInt($.document.ticket);if(_.some((H)=>H.document.phase==="W"&&BigInt(H.document.ticket)<Z&&Ih(H.document.claims,$.document.claims)))return{admitted:!1,queueState:e60($,_)};let X=_.filter((H)=>H.document.phase==="A");if(!UF0(F,X,$.document.claims))return{admitted:!1,queueState:e60($,_)};let Y={...$.document,phase:"A"};return qh($.descriptor,AX(Y)),$.document=Y,{admitted:!0,queueState:""}}function zc0($,_){return Ph($,_)&&$.document.phase==="A"&&_.document.phase==="A"&&AX($.document)===AX(_.document)}async function Uc0($,_,F,Q,Z,J){let X,Y=0;for(;;){let H=await FR(_,F.pollIntervalMilliseconds,Q,Z,()=>{let K=J();_R(K,F.profile);let j=Eh(_,F.profile,F.profileSha256);return Bc0($,j,F.profile)});if(H.admitted)return;if(H.queueState===X)Y+=1;else X=H.queueState,Y=0;await LF0(wc0(F.pollIntervalMilliseconds,$.document.ticket,Y),Q,Z)}}async function kc0($,_,F,Q){zF0($);let Z=ND.now()+F.waitTimeoutMilliseconds;await FR(_,F.pollIntervalMilliseconds,void 0,Z,()=>{let J=Q();if(_R(J,F.profile),!Eh(_,F.profile,F.profileSha256).some((Y)=>zc0(Y,$)))throw new P2("OWNERSHIP_LOST","Host-resource lease is not backed by its exact active kernel lock.")})}async function Mc0($,_,F,Q){if($.released)return;$.released=!0;try{a9($.descriptor)}catch(J){if(!wD(J,"EBADF"))throw J}let Z=ND.now()+F.waitTimeoutMilliseconds;await FR(_,F.pollIntervalMilliseconds,void 0,Z,()=>{let J=Q();if(_R(J,F.profile),CK($.path)===null)return;let X=mQ($.path),Y=!1;try{let H=lQ(X);if(!WD($.identity,H))throw new P2("OWNERSHIP_LOST","Host-resource marker inode changed before release.");if(Y=KD(X),!Y)return;BF0($.path,$.identity)}finally{if(Y)try{jD(X)}catch{}a9(X)}})}function Ac0($){if(!aA(process.platform))throw new P2("UNSUPPORTED_PLATFORM","Slopcamera host-resource coordination requires Darwin or Linux.");let _=GD($.profile??WF0()),F=$.stateRoot??jc0();if(typeof F!=="string"||!Bh(F)||F.includes("\x00")||Buffer.byteLength(F,"utf8")>YF0)throw u2("Host-resource state root must be a bounded absolute path.");return{pollIntervalMilliseconds:eV($.pollIntervalMilliseconds,KF0,1000,"INVALID_PROFILE","Host-resource poll interval"),profile:_,profileSha256:Th(VD(_)),stateRoot:F,waitTimeoutMilliseconds:eV($.waitTimeoutMilliseconds,jF0,A6,"INVALID_PROFILE","Host-resource wait timeout")}}function Rc0($={}){let _=Ac0($),F,Q=()=>{if(F===void 0)F=Vc0(_.stateRoot);return F.path},Z=()=>{return Nc0(Q(),_.profile)},J={profile:_.profile,scope:"machine",async withLease(X,Y,H={}){let K=Rh(X,_.profile);if(typeof Y!=="function")throw new P2("INVALID_CLAIMS","Host-resource lease callback must be a function.");let j=eV(H.waitTimeoutMilliseconds,_.waitTimeoutMilliseconds,A6,"INVALID_CLAIMS","Host-resource lease wait timeout"),V=H.signal,O=ND.now()+j;tA(V,O);let W=Q(),G,D=!1,w,L;try{G=await FR(W,_.pollIntervalMilliseconds,V,O,()=>{let z=Z();return _R(z,_.profile),Eh(W,_.profile,_.profileSha256),Cc0(W,z,K,_.profileSha256)}),await Uc0(G,W,_,V,O,Z);let C=G,B=Object.freeze({claims:K,inheritedFileDescriptor:C.descriptor,profile:_.profile,ticket:C.document.ticket,assertOwned:async()=>{await kc0(C,W,_,Z)}});await B.assertOwned();try{w=await Y(B),D=!0,await B.assertOwned()}catch(z){L=z}}finally{if(G!==void 0)try{await Mc0(G,W,_,Z)}catch(C){if(L===void 0)L=C}}if(!D||L!==void 0)throw L;return w}};return Object.freeze(J)}var wh=new Map;function Tc0($={}){let _=GD($.profile??WF0()),F=eV($.waitTimeoutMilliseconds,jF0,A6,"INVALID_PROFILE","Host-resource wait timeout");if($.pollIntervalMilliseconds!==void 0)eV($.pollIntervalMilliseconds,KF0,1000,"INVALID_PROFILE","Host-resource poll interval");let Q=VD(_),Z=wh.get(Q);if(Z===void 0){if(wh.size>=Xc0)throw new P2("INVALID_PROFILE","This process already coordinates the maximum number of host-resource profiles.");Z={active:new Map,nextTicket:1n,waiting:[]},wh.set(Q,Z)}let{active:J,waiting:X}=Z,Y=(V)=>{if(V.timeout!==void 0)clearTimeout(V.timeout);if(V.abortListener!==void 0)V.signal?.removeEventListener("abort",V.abortListener)},H=()=>[...J.values()].map((V)=>({document:{version:1,owner:V.ticket.padStart(32,"0").slice(-32),profileSha256:Th(VD(_)),ticket:V.ticket,phase:"A",claims:V.claims},identity:{device:0,inode:0},name:V.ticket,path:""})),K=()=>{for(let V=0;V<X.length;){let O=X[V];if(O===void 0)break;if(X.slice(0,V).some((L)=>Ih(L.claims,O.claims))||!UF0(_,H(),O.claims)){V+=1;continue}X.splice(V,1),Y(O);let G;try{G=Ch(process.platform==="win32"?"NUL":"/dev/null",MX.O_RDONLY)}catch(L){O.settled=!0,O.reject(new P2("UNSAFE_STATE","Process-local host-resource admission could not open its lease descriptor.",L));continue}O.active=!0,J.set(O.ticket,O),O.descriptor=G;let w=Object.freeze({assertOwned:async()=>{if(O.settled||!O.active||J.get(O.ticket)!==O||O.descriptor!==G)throw new P2("OWNERSHIP_LOST","Process-local host-resource lease is no longer active.");try{lQ(G)}catch(L){throw new P2("OWNERSHIP_LOST","Process-local host-resource descriptor is no longer open.",L)}},claims:O.claims,inheritedFileDescriptor:G,profile:_,ticket:O.ticket});(async()=>{let L=!1,C,B;try{await w.assertOwned(),C=await O.callback(w),await w.assertOwned(),L=!0}catch(z){B=z}finally{O.active=!1,O.settled=!0,J.delete(O.ticket);try{a9(G)}catch(z){if(B===void 0)B=z}K()}if(L&&B===void 0)O.resolve(C);else O.reject(B)})()}};return Object.freeze({profile:_,scope:"process",async withLease(V,O,W={}){let G=Rh(V,_);if(typeof O!=="function")return Promise.reject(new P2("INVALID_CLAIMS","Host-resource lease callback must be a function."));if(Z.nextTicket>kh)return Promise.reject(u2("Host-resource tickets are exhausted."));let D=eV(W.waitTimeoutMilliseconds,F,A6,"INVALID_CLAIMS","Host-resource lease wait timeout"),w=String(Z.nextTicket);return Z.nextTicket+=1n,await new Promise((L,C)=>{let B={active:!1,callback:O,claims:G,reject:C,resolve:L,settled:!1,signal:W.signal,ticket:w},z=(U)=>{if(B.active||B.settled)return;B.settled=!0;let k=X.indexOf(B);if(k>=0)X.splice(k,1);Y(B),C(U),K()};if(B.abortListener=()=>z(new P2("WAIT_ABORTED","Host-resource admission was cancelled before execution.")),B.timeout=setTimeout(()=>z(new P2("WAIT_TIMEOUT","Host-resource admission exceeded its bounded wait.")),D),B.timeout.unref?.(),W.signal?.addEventListener("abort",B.abortListener,{once:!0}),W.signal?.aborted===!0){B.abortListener();return}X.push(B),K()})}})}function dQ($={},_=process.platform){if(aA(_))return Rc0($);let{profile:F,pollIntervalMilliseconds:Q,waitTimeoutMilliseconds:Z}=$;return Tc0({...F===void 0?{}:{profile:F},...Q===void 0?{}:{pollIntervalMilliseconds:Q},...Z===void 0?{}:{waitTimeoutMilliseconds:Z}})}var _W=["slopcamera.diagram.check","slopcamera.diagram.render","slopcamera.image.vectorize","slopcamera.image.generate","slopcamera.image.icon","slopcamera.image.gallery"];class z9 extends Error{code;constructor($,_){super(`[${$}] ${_}`);this.name="SlopcameraOperationError",this.code=$}}var QR={type:"string",minLength:3,maxLength:256,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*/[a-zA-Z0-9][a-zA-Z0-9._:-]*$"},RX={type:"string",minLength:1,maxLength:4096};function AF0($){if(typeof $!=="object"||$===null||Object.isFrozen($))return $;for(let _ of Object.values($))AF0(_);return Object.freeze($)}var CD=AF0([{code:"slopcamera.diagram.check",title:"Check diagram",description:"Parse and lint a checked Slopcamera diagram source without changing its files.",execution:"local",authentication:"none",destructive:!1,idempotent:!0,inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:RX}},resources:[{resource:"cpu",amount:1},{resource:"local-io",amount:1}]},{code:"slopcamera.diagram.render",title:"Render diagram",description:"Render a checked Slopcamera diagram source to its replaceable light, dark, PNG, SVG, and tldraw artifacts.",execution:"local",authentication:"none",destructive:!0,idempotent:!0,inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:RX,outDirectory:RX,scale:{type:"number",exclusiveMinimum:0,maximum:4}}},resources:[{resource:"cpu",amount:1},{resource:"local-io",amount:1}]},{code:"slopcamera.image.vectorize",title:"Vectorize image",description:"Convert a local caller-owned raster into a bounded inert SVG without authentication or network access.",execution:"local",authentication:"none",destructive:!0,idempotent:!1,inputSchema:{type:"object",additionalProperties:!1,required:["inputPath","outputPath"],properties:{inputPath:RX,outputPath:RX,duotone:{type:"array",minItems:2,maxItems:2,items:{type:"string",pattern:"^#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$"}},alphaCutoff:{type:"integer",minimum:1,maximum:64},timeoutMs:{type:"integer",minimum:1,maximum:300000}}},resources:[{resource:"cpu",amount:1},{resource:"local-io",amount:1}]},{code:"slopcamera.image.generate",title:"Generate image",description:"Generate one bounded image directly through Vercel AI Gateway with an environment credential and no client retry.",execution:"gateway",authentication:"environment",destructive:!0,idempotent:!1,inputSchema:{type:"object",additionalProperties:!1,required:["model","prompt","outputPath"],properties:{model:QR,prompt:{type:"string",minLength:1,maxLength:nZ},outputPath:RX}},resources:[{resource:"local-io",amount:1},{resource:"network",amount:1},{resource:"paid-call",amount:1}],transport:{method:"POST",authority:"https://ai-gateway.vercel.sh/v4/ai",authorization:"bearer",retry:"never"}},{code:"slopcamera.image.icon",title:"Generate line-art icon",description:"Generate one isometric line-art SVG icon: a style-locked Vercel AI Gateway raster normalized to canonical ink-on-transparent pixels, traced locally, and optionally critiqued by a vision model across bounded rounds.",execution:"gateway",authentication:"environment",destructive:!0,idempotent:!1,inputSchema:{type:"object",additionalProperties:!1,required:["subject","outputPath"],properties:{subject:{type:"string",minLength:1,maxLength:rV},outputPath:RX,model:QR,critiqueModel:QR,ink:{type:"string",pattern:"^#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$"},purpose:{type:"string",enum:["mark","illustration"]},rounds:{type:"integer",minimum:1,maximum:nV},keepRaster:{type:"boolean"}}},resources:[{resource:"cpu",amount:1},{resource:"local-io",amount:1},{resource:"network",amount:1},{resource:"paid-call",amount:1}],transport:{method:"POST",authority:"https://ai-gateway.vercel.sh/v4/ai",authorization:"bearer",retry:"never"}},{code:"slopcamera.image.gallery",title:"Generate image gallery",description:"Generate several bounded Vercel AI Gateway image candidates in parallel and compose a labelled contact sheet with per-candidate provenance for explicit review and selection.",execution:"gateway",authentication:"environment",destructive:!0,idempotent:!1,inputSchema:{type:"object",additionalProperties:!1,required:["subject","outputDir"],properties:{subject:{type:"string",minLength:1,maxLength:w1.subjectBytes},outputDir:RX,kind:{type:"string",enum:[...K3]},model:QR,count:{type:"integer",minimum:1,maximum:w1.candidates},vary:{type:"array",maxItems:H_.length,items:{anyOf:[{type:"string",enum:[...H_]},{type:"object",additionalProperties:!1,required:["axis"],properties:{axis:{type:"string",enum:[...H_]},values:{type:"array",minItems:1,maxItems:w1.candidates,items:{type:"string",minLength:1,maxLength:w1.variantBytes}}}}]}},candidates:{type:"array",minItems:1,maxItems:w1.candidates,items:{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string",minLength:1,maxLength:w1.idLength},prompt:{type:"string",minLength:1,maxLength:w1.candidatePromptBytes},variant:{type:"string",minLength:1,maxLength:w1.variantBytes}}}},cellEdge:{type:"integer",minimum:w1.cellEdgeMin,maximum:w1.cellEdgeMax},tiled:{type:"boolean"},timeoutMs:{type:"integer",minimum:1000,maximum:1800000}}},resources:[{resource:"cpu",amount:1},{resource:"local-io",amount:1},{resource:"network",amount:1},{resource:"paid-call",amount:1}],transport:{method:"POST",authority:"https://ai-gateway.vercel.sh/v4/ai",authorization:"bearer",retry:"never"}}]);function v4($){throw new z9("INVALID_OPERATION_INPUT",$)}function fc0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function FW($,_){if(!fc0($))v4("Operation input must be an object.");let F=Object.keys($).filter((Q)=>!_.includes(Q));if(F.length>0)v4(`Unsupported operation input field: ${F[0]}.`);return $}function TX($,_){if(typeof $!=="string"||$.length<1||$.length>4096||$.includes("\x00"))v4(`${_} must be a non-empty bounded local path.`);return $}function yc0($){let _=FW($,["path"]);return{path:TX(_.path,"path")}}function gc0($){let _=FW($,["path","outDirectory","scale"]),F=_.scale;if(F!==void 0&&(typeof F!=="number"||!Number.isFinite(F)||F<=0||F>4))v4("scale must be greater than zero and no more than 4.");return{path:TX(_.path,"path"),..._.outDirectory===void 0?{}:{outDirectory:TX(_.outDirectory,"outDirectory")},...F===void 0?{}:{scale:F}}}function vc0($){let _=FW($,["inputPath","outputPath","duotone","alphaCutoff","timeoutMs"]),F=TX(_.inputPath,"inputPath"),Q=TX(_.outputPath,"outputPath");if(!Q.toLowerCase().endsWith(".svg"))v4("outputPath must end in .svg.");let Z=_.duotone;if(Z!==void 0&&(!Array.isArray(Z)||Z.length!==2||Z.some((Y)=>typeof Y!=="string"||!/^#[a-f0-9]{3}(?:[a-f0-9]{3})?$/iu.test(Y))))v4("duotone must contain exactly two #rgb or #rrggbb colors.");let J=_.alphaCutoff;if(J!==void 0&&(!Number.isInteger(J)||J<1||J>64))v4("alphaCutoff must be an integer from 1 through 64.");let X=_.timeoutMs;if(X!==void 0&&(!Number.isInteger(X)||X<1||X>300000))v4("timeoutMs must be an integer from 1 through 300000.");return{inputPath:F,outputPath:Q,...Z===void 0?{}:{duotone:Z},...J===void 0?{}:{alphaCutoff:J},...X===void 0?{}:{timeoutMs:X}}}function xc0($){let _=FW($,["model","prompt","outputPath"]);if(typeof _.model!=="string"||_.model.length>256||!/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/iu.test(_.model))v4("model must be a bounded Vercel AI Gateway provider/model id.");if(typeof _.prompt!=="string"||_.prompt.trim().length<1||/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(_.prompt)||Buffer.byteLength(_.prompt,"utf8")>nZ)v4(`prompt must be non-empty and no more than ${nZ} UTF-8 bytes.`);let F=TX(_.outputPath,"outputPath");if(!/\.(?:jpe?g|png|webp)$/iu.test(F))v4("outputPath must end in .png, .jpg, .jpeg, or .webp.");return{model:_.model,prompt:_.prompt,outputPath:F}}function hc0($){let _=FW($,["subject","outputPath","model","critiqueModel","ink","rounds","keepRaster"]);if(typeof _.subject!=="string"||_.subject.trim().length<1||/[\u0000-\u001f\u007f]/u.test(_.subject)||Buffer.byteLength(_.subject,"utf8")>rV)v4(`subject must be non-empty and no more than ${rV} UTF-8 bytes.`);let F=TX(_.outputPath,"outputPath");if(!F.toLowerCase().endsWith(".svg"))v4("outputPath must end in .svg.");for(let Z of["model","critiqueModel"]){let J=_[Z];if(J!==void 0&&(typeof J!=="string"||J.length>256||!/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/iu.test(J)))v4(`${Z} must be a bounded Vercel AI Gateway provider/model id.`)}if(_.ink!==void 0&&(typeof _.ink!=="string"||!/^#[a-f0-9]{3}(?:[a-f0-9]{3})?$/iu.test(_.ink)))v4("ink must be a #rgb or #rrggbb color.");let Q=_.rounds;if(Q!==void 0&&(!Number.isInteger(Q)||Q<1||Q>nV))v4(`rounds must be an integer from 1 through ${nV}.`);if(_.keepRaster!==void 0&&typeof _.keepRaster!=="boolean")v4("keepRaster must be a boolean.");return{subject:_.subject,outputPath:F,..._.model===void 0?{}:{model:_.model},..._.critiqueModel===void 0?{}:{critiqueModel:_.critiqueModel},..._.ink===void 0?{}:{ink:_.ink},...Q===void 0?{}:{rounds:Q},..._.keepRaster===void 0?{}:{keepRaster:_.keepRaster}}}function mc0($){let _=FW($,["subject","outputDir","kind","model","count","vary","candidates","cellEdge","tiled","timeoutMs"]);if(typeof _.subject!=="string"||_.subject.trim().length<1||/[\u0000-\u001f\u007f]/u.test(_.subject)||Buffer.byteLength(_.subject,"utf8")>w1.subjectBytes)v4(`subject must be non-empty and no more than ${w1.subjectBytes} UTF-8 bytes.`);if(_.kind!==void 0&&(typeof _.kind!=="string"||!K3.includes(_.kind)))v4(`kind must be one of: ${K3.join(", ")}.`);if(_.model!==void 0&&(typeof _.model!=="string"||_.model.length>256||!/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/iu.test(_.model)))v4("model must be a bounded Vercel AI Gateway provider/model id.");if(_.count!==void 0&&(!Number.isInteger(_.count)||_.count<1||_.count>w1.candidates))v4(`count must be an integer from 1 through ${w1.candidates}.`);if(_.vary!==void 0&&(!Array.isArray(_.vary)||_.vary.length<1||_.vary.length>H_.length))v4(`vary must be a list of at most ${H_.length} axes.`);if(_.candidates!==void 0&&(!Array.isArray(_.candidates)||_.candidates.length<1||_.candidates.length>w1.candidates))v4(`candidates must contain 1 through ${w1.candidates} entries.`);if(_.vary!==void 0&&_.candidates!==void 0)v4("vary and candidates are mutually exclusive.");if(_.count!==void 0&&_.candidates!==void 0)v4("count and candidates are mutually exclusive.");let F=_.cellEdge;if(F!==void 0&&(!Number.isInteger(F)||F<w1.cellEdgeMin||F>w1.cellEdgeMax))v4(`cellEdge must be an integer from ${w1.cellEdgeMin} through ${w1.cellEdgeMax}.`);let Q=_.timeoutMs;if(Q!==void 0&&(!Number.isInteger(Q)||Q<1000||Q>1800000))v4("timeoutMs must be an integer from 1000 through 1800000.");if(_.tiled!==void 0&&typeof _.tiled!=="boolean")v4("tiled must be a boolean when set.");return{subject:_.subject,outputDir:TX(_.outputDir,"outputDir"),..._.kind===void 0?{}:{kind:_.kind},..._.model===void 0?{}:{model:_.model},..._.count===void 0?{}:{count:_.count},..._.vary===void 0?{}:{vary:_.vary},..._.candidates===void 0?{}:{candidates:_.candidates},...F===void 0?{}:{cellEdge:F},..._.tiled===void 0?{}:{tiled:_.tiled},...Q===void 0?{}:{timeoutMs:Q}}}function R6($,_){switch($){case"slopcamera.diagram.check":return yc0(_);case"slopcamera.diagram.render":return gc0(_);case"slopcamera.image.vectorize":return vc0(_);case"slopcamera.image.generate":return xc0(_);case"slopcamera.image.icon":return hc0(_);case"slopcamera.image.gallery":return mc0(_);default:throw new z9("INVALID_OPERATION","Unknown Slopcamera operation code.")}}function RF0($){return _W.includes($)}function ZR($){let _=CD.find((F)=>F.code===$);if(_===void 0)throw new z9("INVALID_OPERATION","Unknown Slopcamera operation code.");return _.resources}function JR($="",_=CD.length){if(typeof $!=="string"||$.length>200||/[\u0000-\u001f\u007f]/u.test($)||!Number.isInteger(_)||_<1||_>20)throw new z9("INVALID_SEARCH","Search requires a bounded query and a limit from 1 through 20.");let F=$.toLowerCase().split(/\s+/u).filter((Q)=>Q.length>0);return CD.filter((Q)=>{let Z=`${Q.code} ${Q.title} ${Q.description}`.toLowerCase();return F.every((J)=>Z.includes(J))}).slice(0,_)}function TF0($,_){let F=[...$.inheritedFileDescriptors??[],_.inheritedFileDescriptor].filter((Y,H,K)=>K.indexOf(Y)===H);if(F.length>16||F.some((Y)=>!Number.isSafeInteger(Y)||Y<0||Y>2147483647))throw new z9("INVALID_OPERATION_INPUT","Operation host-resource inheritance exceeds its descriptor bound.");let{hostResourceCoordinator:Q,signal:Z,waitTimeoutMilliseconds:J,...X}=$;return{...X,inheritedFileDescriptors:F}}async function bh($,_,F={}){return await(F.hostResourceCoordinator??dQ()).withLease(ZR($),async(Z)=>{return await Z.assertOwned(),await _(Z)},{...F.signal===void 0?{}:{signal:F.signal},...F.waitTimeoutMilliseconds===void 0?{}:{waitTimeoutMilliseconds:F.waitTimeoutMilliseconds}})}var DD=Object.freeze({icons:C9});async function qF0($){let _=MF0($),F;try{F=JSON.parse(await Pc0(_,"utf8"))}catch(Z){throw new z9("INVALID_OPERATION_INPUT","Diagram source could not be read as JSON.")}let Q=M_(F);for(let Z of Q.shapes)if((Z.type==="rect"||Z.type==="ellipse")&&Z.icon!==void 0&&!Object.hasOwn(C9,Z.icon))throw new z9("INVALID_OPERATION_INPUT","Diagram requests an unavailable built-in icon.");return{absolutePath:_,spec:Q}}async function LD($,_){let F=$W(kF0($),`.${qc0()}.slopcamera-operation.tmp`);try{await Sc0(F,_,{flag:"wx"}),await Ic0(F,$)}finally{await bc0(F,{force:!0}).catch(()=>{return})}}async function uc0($){let{spec:_}=await qF0($);return{findings:qF(_),configPath:null}}async function lc0($){let{absolutePath:_,spec:F}=await qF0($.path),Q=MF0($.outDirectory??kF0(_)),Z=$.scale??2,[J,X]=await Promise.all([B9(F,"light",DD),B9(F,"dark",DD)]),[Y,H]=[MF(J,DD,Z),MF(X,DD,Z)],K={spec:_,tldr:$W(Q,`${F.name}.tldr`),lightSvg:$W(Q,`${F.name}.light.svg`),darkSvg:$W(Q,`${F.name}.dark.svg`),lightPng:$W(Q,`${F.name}.light.png`),darkPng:$W(Q,`${F.name}.dark.png`)};return await Ec0(Q,{recursive:!0}),await Promise.all([LD(K.tldr,CX(F,DD)),LD(K.lightSvg,J.svg),LD(K.darkSvg,X.svg),LD(K.lightPng,Y),LD(K.darkPng,H)]),{artifacts:K,findings:qF(F),configPath:null}}async function EF0($,_,F={}){let Q=R6($,_);switch($){case"slopcamera.diagram.check":return await uc0(Q.path);case"slopcamera.diagram.render":return await lc0(Q);case"slopcamera.image.vectorize":{let Z=Q,J=await EF(Z.inputPath,{outputPath:Z.outputPath,...Z.duotone===void 0?{}:{duotone:Z.duotone},...Z.alphaCutoff===void 0?{}:{alphaCutoff:Z.alphaCutoff},...Z.timeoutMs===void 0?{}:{limits:{maxDurationMs:Z.timeoutMs}},...F.inheritedFileDescriptors===void 0?{}:{inheritedFileDescriptors:F.inheritedFileDescriptors}});if(J.outputPath===null)throw new z9("INVALID_OPERATION_INPUT","Vectorization did not publish its required output.");return{outputPath:J.outputPath,receipt:J.receipt}}case"slopcamera.image.generate":return await Bj({...Q,...F.signal===void 0?{}:{signal:F.signal}},F);case"slopcamera.image.icon":return await dA({...Q,...F.signal===void 0?{}:{signal:F.signal},...F.inheritedFileDescriptors===void 0?{}:{inheritedFileDescriptors:F.inheritedFileDescriptors}},F);case"slopcamera.image.gallery":return await zj({...Q,...F.signal===void 0?{}:{signal:F.signal}},F);default:throw new z9("INVALID_OPERATION","Unknown Slopcamera operation code.")}}async function zK($,_,F,Q={}){await F.assertOwned();let Z=new Map;for(let X of F.claims){if(typeof X.resource!=="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(X.resource)||!Number.isSafeInteger(X.amount)||X.amount<1)throw new z9("INVALID_OPERATION","The active host-resource lease contains invalid claims.");let Y=(Z.get(X.resource)??0)+X.amount;if(!Number.isSafeInteger(Y))throw new z9("INVALID_OPERATION","The active host-resource lease contains invalid claims.");Z.set(X.resource,Y)}let J=ZR($).filter((X)=>(Z.get(X.resource)??0)<X.amount);if(J.length>0)throw new z9("INVALID_OPERATION",`The active host-resource lease does not cover ${J.map((X)=>`${X.resource}:${String(X.amount)}`).join(", ")}.`);return await EF0($,_,TF0(Q,F))}async function UK($,_,F={}){let Q=R6($,_);return await bh($,async(Z)=>await EF0($,Q,TF0(F,Z)),F)}import{rename as SF0,rm as fF0,writeFile as ic0}from"fs/promises";import{dirname as ac0,join as QW}from"path";import{open as dc0,mkdir as cc0,realpath as BD,stat as Sh}from"fs/promises";import{basename as pc0,dirname as PF0,isAbsolute as IF0,join as sc0,relative as bF0,resolve as XR,win32 as nc0}from"path";var cQ=1048576;class r2 extends Error{code;constructor($,_){super(_);this.name="WorkspaceBoundaryError",this.code=$}}function HR($){if(typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string")return $.code;return}function YR($,_){if($.length===0||$.includes("\x00"))throw new r2("INVALID_PATH","Path must be a non-empty root-relative path.");if(IF0($)||nc0.isAbsolute($)||/^[A-Za-z]:/.test($))throw new r2("INVALID_PATH","Absolute paths are not allowed.");let F=$.split(/[\\/]/).filter((Q)=>Q!==""&&Q!==".");if(F.includes(".."))throw new r2("INVALID_PATH","Parent-directory traversal is not allowed.");if(F.length===0){if(!_.allowRoot)throw new r2("INVALID_PATH","Path must identify a file below the root.");return{native:".",portable:"."}}return{native:F.join("/"),portable:F.join("/")}}function rc0($,_){let F=bF0($,_);return F===""||!F.startsWith("..")&&!IF0(F)}async function oc0($,_){let F;try{F=await dc0($,"r");let Q=await F.stat();if(!Q.isFile())throw new r2("SOURCE_NOT_FILE",`${_} must be a regular file.`);if(Q.size>cQ)throw new r2("SOURCE_TOO_LARGE",`${_} exceeds the ${cQ}-byte limit.`);let Z=Buffer.allocUnsafe(cQ+1),J=0;while(J<=cQ){let X=await F.read(Z,J,cQ+1-J,null);if(X.bytesRead===0)break;J+=X.bytesRead}if(J>cQ)throw new r2("SOURCE_TOO_LARGE",`${_} exceeds the ${cQ}-byte limit.`);try{return new TextDecoder("utf-8",{fatal:!0}).decode(Z.subarray(0,J))}catch{throw new r2("SOURCE_ENCODING",`${_} must contain valid UTF-8.`)}}catch(Q){if(Q instanceof r2)throw Q;if(HR(Q)==="ENOENT")throw new r2("SOURCE_NOT_FOUND",`${_} does not exist.`);throw new r2("FILESYSTEM_ERROR",`${_} could not be read.`)}finally{await F?.close()}}class kK{rootDirectory;constructor($){this.rootDirectory=$}static async create($){let _;try{if(_=await BD(XR($)),!(await Sh(_)).isDirectory())throw new r2("OUTPUT_NOT_DIRECTORY","MCP root must be a directory.")}catch(F){if(F instanceof r2)throw F;throw new r2("FILESYSTEM_ERROR","MCP root could not be opened.")}return new kK(_)}assertConfined($){if(!rc0(this.rootDirectory,$))throw new r2("PATH_OUTSIDE_ROOT","Path resolves outside the MCP root.")}toRelativePath($){this.assertConfined($);let _=bF0(this.rootDirectory,$);return _===""?".":_.split("\\").join("/")}async readSource($,_="Diagram source"){let F=YR($,{allowRoot:!1}),Q=XR(this.rootDirectory,F.native);this.assertConfined(Q);let Z;try{Z=await BD(Q)}catch(J){if(HR(J)==="ENOENT")throw new r2("SOURCE_NOT_FOUND",`${_} does not exist.`);throw new r2("FILESYSTEM_ERROR",`${_} could not be resolved.`)}return this.assertConfined(Z),{absolutePath:Z,relativePath:this.toRelativePath(Z),text:await oc0(Z,_)}}async resolveInputFile($,_){let F=YR($,{allowRoot:!1}),Q=XR(this.rootDirectory,F.native);this.assertConfined(Q);let Z;try{Z=await BD(Q),this.assertConfined(Z);let J=await Sh(Z);if(!J.isFile())throw new r2("SOURCE_NOT_FILE","Input must be a regular file.");if(!Number.isSafeInteger(_)||_<1||J.size>_)throw new r2("SOURCE_TOO_LARGE",`Input exceeds the ${_}-byte limit.`)}catch(J){if(J instanceof r2)throw J;if(HR(J)==="ENOENT")throw new r2("SOURCE_NOT_FOUND","Input does not exist.");throw new r2("FILESYSTEM_ERROR","Input could not be resolved.")}return{absolutePath:Z,relativePath:this.toRelativePath(Z)}}async prepareOutputFile($){let _=YR($,{allowRoot:!1}),F=pc0(_.native);if(F==="."||F===".."||F.length===0)throw new r2("INVALID_PATH","Output path must identify a file below the root.");let Q=await this.prepareOutputDirectory(PF0(_.native)),Z=sc0(Q.absolutePath,F);return this.assertConfined(Z),{absolutePath:Z,relativePath:this.toRelativePath(Z)}}async prepareOutputDirectory($){let _=YR($,{allowRoot:!0}),F=XR(this.rootDirectory,_.native);this.assertConfined(F);let Q=F;for(;;)try{let Z=await BD(Q);this.assertConfined(Z);break}catch(Z){if(Z instanceof r2)throw Z;if(HR(Z)!=="ENOENT")throw new r2("FILESYSTEM_ERROR","Output directory could not be resolved.");let J=PF0(Q);if(J===Q)throw new r2("PATH_OUTSIDE_ROOT","Output directory resolves outside the MCP root.");Q=J}try{await cc0(F,{recursive:!0});let Z=await BD(F);if(this.assertConfined(Z),!(await Sh(Z)).isDirectory())throw new r2("OUTPUT_NOT_DIRECTORY","Output path must be a directory.");return{absolutePath:Z,relativePath:this.toRelativePath(Z)}}catch(Z){if(Z instanceof r2)throw Z;throw new r2("FILESYSTEM_ERROR","Output directory could not be created.")}}}var ZW=4,MD=16777216,AD=64,RD=128,EX=40,KR=256,dF0=8192,cF0=1024,yh=2,tc0=12,zD=Object.freeze({icons:C9}),yF0={type:"object",additionalProperties:!1,required:["code","message","shapeIds"],properties:{code:{type:"string"},message:{type:"string"},shapeIds:{type:"array",items:{type:"string"}}}},T6={type:"string",description:"Root-relative path to a spatial scene JSON source (1 MiB maximum)."},UD={type:"string",maxLength:128,pattern:"^camera_[a-zA-Z0-9][a-zA-Z0-9_-]*$",description:"Identifier of a camera declared by the scene (camera_\u2026)."},gF0={type:"object",additionalProperties:!1,required:["entityCount","returnedEntityCount","entitiesTruncated"],properties:{entityCount:{type:"integer",minimum:0},returnedEntityCount:{type:"integer",minimum:0},entitiesTruncated:{type:"boolean"}}};function pF0($){if(typeof $!=="object"||$===null||Object.isFrozen($))return $;for(let _ of Object.values($))pF0(_);return Object.freeze($)}var PX=pF0([{name:"check_diagram",title:"Check diagram",description:"Parse and lint one root-relative Slopcamera diagram source without changing files. Uses only built-in icons and themes.",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string",description:"Root-relative path to a diagram JSON source (1 MiB maximum)."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","findings","summary"],properties:{ok:{const:!0},source:{type:"string"},findings:{type:"array",items:yF0},summary:{type:"object",additionalProperties:!1,required:["shapeCount","edgeCount","findingCount","returnedFindingCount","findingsTruncated"],properties:{shapeCount:{type:"integer",minimum:0},edgeCount:{type:"integer",minimum:0},findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"}}}}},annotations:{title:"Check diagram",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"render_diagram",title:"Render diagram",description:"Render one root-relative Slopcamera diagram source with built-in icons and themes, overwriting its paired .tldr, light/dark SVG, and light/dark PNG artifacts.",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string",description:"Root-relative path to a diagram JSON source (1 MiB maximum)."},out_dir:{type:"string",description:"Optional root-relative output directory. Defaults to the source directory."},scale:{type:"number",exclusiveMinimum:0,maximum:ZW,default:yh,description:"PNG scale. The scaled canvas may contain at most 16,777,216 pixels."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","scale","findings","artifacts","summary"],properties:{ok:{const:!0},source:{type:"string"},scale:{type:"number"},findings:{type:"array",items:yF0},artifacts:{type:"object",additionalProperties:!1,required:["tldr","lightSvg","darkSvg","lightPng","darkPng"],properties:{tldr:{type:"string"},lightSvg:{type:"string"},darkSvg:{type:"string"},lightPng:{type:"string"},darkPng:{type:"string"}}},summary:{type:"object",additionalProperties:!1,required:["shapeCount","edgeCount","findingCount","returnedFindingCount","findingsTruncated"],properties:{shapeCount:{type:"integer",minimum:0},edgeCount:{type:"integer",minimum:0},findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"}}}}},annotations:{title:"Render diagram",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},{name:"search_slopcamera",title:"Search Slopcamera operations",description:"Search the fixed semantic Slopcamera operation registry by bounded text. This never executes code or changes files.",inputSchema:{type:"object",additionalProperties:!1,properties:{query:{type:"string",maxLength:200,description:"Optional terms matched against operation codes and descriptions."},limit:{type:"integer",minimum:1,maximum:20,default:4}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","operations"],properties:{ok:{const:!0},operations:{type:"array",maxItems:20,items:{type:"object",required:["code","title","description","execution","authentication","inputSchema"]}}}},annotations:{title:"Search Slopcamera operations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"execute_slopcamera",title:"Execute Slopcamera operation",description:"Execute one exact operation code with typed JSON input. Never accepts or evaluates source code. Local paths remain confined to the configured workspace root.",inputSchema:{type:"object",additionalProperties:!1,required:["operation","input"],properties:{operation:{type:"string",enum:_W},input:{type:"object",description:"Typed input matching the selected operation's registry schema."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","operation","result"],properties:{ok:{const:!0},operation:{type:"string",enum:_W},result:{type:"object"}}},annotations:{title:"Execute Slopcamera operation",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},{name:"check_scene",title:"Check scene",description:"Parse and validate one root-relative Slopcamera spatial scene JSON source without changing files.",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:T6}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","sceneId","sceneSha256","summary"],properties:{ok:{const:!0},source:{type:"string"},sceneId:{type:"string"},sceneSha256:{type:"string"},summary:{type:"object",additionalProperties:!1,required:["durationUs","entityCount","cameraCount","assetCount","animationCount","generatorCount","overrideCount"],properties:{durationUs:{type:"integer",minimum:0},entityCount:{type:"integer",minimum:0},cameraCount:{type:"integer",minimum:0},assetCount:{type:"integer",minimum:0},animationCount:{type:"integer",minimum:0},generatorCount:{type:"integer",minimum:0},overrideCount:{type:"integer",minimum:0}}}}},annotations:{title:"Check scene",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"inspect_scene",title:"Inspect scene",description:"Snapshot one root-relative spatial scene's entities, editable controls, placements, assets, and generators without changing files.",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:T6}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","inspection","summary"],properties:{ok:{const:!0},source:{type:"string"},inspection:{type:"object"},summary:gF0}},annotations:{title:"Inspect scene",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"audit_scene",title:"Audit scene",description:"Sample one root-relative spatial scene against a camera and report per-entity geometric coverage, visibility findings, and bounds gaps. Optional asset_bounds accepts a Record<assetId,{min,max}> map, a slopcamera.spatial-asset-admission document, a {manifest,facts} pair, or an array of those.",inputSchema:{type:"object",additionalProperties:!1,required:["path","camera_id"],properties:{path:T6,camera_id:UD,times_us:{type:"array",items:{type:"integer",minimum:0,maximum:w0.durationUs},minItems:1,maxItems:G$.samples,description:"Optional sample times in microseconds. Defaults to evenly spaced coverage of the scene duration."},asset_bounds:{description:"Optional decoded scene-space asset bounds: a Record<assetId,{min,max}> map, a slopcamera.spatial-asset-admission document, a {manifest,facts} pair, or an array of those documents."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","report","summary"],properties:{ok:{const:!0},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:!1,required:["findingCount","returnedFindingCount","findingsTruncated","entityCount","returnedEntityCount","entitiesTruncated"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},entityCount:{type:"integer",minimum:0},returnedEntityCount:{type:"integer",minimum:0},entitiesTruncated:{type:"boolean"}}}}},annotations:{title:"Audit scene",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"diff_scenes",title:"Diff scenes",description:"Compare two root-relative spatial scene JSON sources and report added, removed, and changed collection entries without changing files.",inputSchema:{type:"object",additionalProperties:!1,required:["path","other"],properties:{path:T6,other:{type:"string",description:"Root-relative path to the second spatial scene JSON source (1 MiB maximum)."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","other","sceneSha256","otherSha256","diff","summary"],properties:{ok:{const:!0},source:{type:"string"},other:{type:"string"},sceneSha256:{type:"string"},otherSha256:{type:"string"},diff:{type:"array"},summary:{type:"object",additionalProperties:!1,required:["entryCount","returnedEntryCount","diffTruncated"],properties:{entryCount:{type:"integer",minimum:0},returnedEntryCount:{type:"integer",minimum:0},diffTruncated:{type:"boolean"}}}}},annotations:{title:"Diff scenes",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"evaluate_scene",title:"Evaluate scene",description:"Evaluate one root-relative spatial scene at one camera and integer microsecond time into an immutable snapshot without changing files.",inputSchema:{type:"object",additionalProperties:!1,required:["path","camera_id","time_us"],properties:{path:T6,camera_id:UD,time_us:{type:"integer",minimum:0,maximum:w0.durationUs,description:"Evaluation time in integer microseconds."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","snapshot","summary"],properties:{ok:{const:!0},source:{type:"string"},snapshot:{type:"object"},summary:gF0}},annotations:{title:"Evaluate scene",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"check_scene_direction",title:"Check scene direction",description:"Validate one authored direction document against one root-relative spatial scene: stale project digests, unresolved entity references, and intervals outside scene duration report as errors without compiling or changing files.",inputSchema:{type:"object",additionalProperties:!1,required:["scene","direction"],properties:{scene:{...T6,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},direction:{type:"string",description:"Root-relative path to the slopcamera.spatial-direction JSON document."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","report","summary"],properties:{ok:{const:!0},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:!1,required:["findingCount","returnedFindingCount","findingsTruncated","errorCount","warningCount"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},errorCount:{type:"integer",minimum:0},warningCount:{type:"integer",minimum:0}}}}},annotations:{title:"Check scene direction",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"plan_scene_direction",title:"Plan scene direction",description:"Compile one authored direction document into a deterministic, unverified proposal document \u2014 performance actions, camera rigs, shots and looks bound to the actual scene digest. Proposals are advisory only; nothing is applied to the scene.",inputSchema:{type:"object",additionalProperties:!1,required:["scene","direction"],properties:{scene:{...T6,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},direction:{type:"string",description:"Root-relative path to the slopcamera.spatial-direction JSON document."},camera_id:{...UD,description:"Optional camera used to resolve coverage; defaults to the sole or first sorted scene camera."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","compilation","summary"],properties:{ok:{const:!0},source:{type:"string"},compilation:{type:"object"},summary:{type:"object",additionalProperties:!1,required:["advisoryCount","unresolvedIntentCount","proposalCounts"],properties:{advisoryCount:{type:"integer",minimum:0},unresolvedIntentCount:{type:"integer",minimum:0},proposalCounts:{type:"object",additionalProperties:!1,required:["performance","cameraRigs","shots","lookIntents"],properties:{performance:{type:"integer",minimum:0},cameraRigs:{type:"integer",minimum:0},shots:{type:"integer",minimum:0},lookIntents:{type:"integer",minimum:0}}}}}}},annotations:{title:"Plan scene direction",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"plan_scene_gallery",title:"Plan scene gallery",description:"Compile a bounded set of single-axis direction variants into separate content-addressed candidate compilations plus a preview-reel plan. The planner never selects or promotes a candidate.",inputSchema:{type:"object",additionalProperties:!1,required:["scene","direction","axis"],properties:{scene:{...T6,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},direction:{type:"string",description:"Root-relative path to the slopcamera.spatial-direction JSON document."},axis:{type:"string",enum:[...jQ.options],description:"Variation axis for the bounded candidate set."},camera_id:{...UD,description:"Optional camera used to resolve coverage."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","gallery","summary"],properties:{ok:{const:!0},source:{type:"string"},gallery:{type:"object"},summary:{type:"object",additionalProperties:!1,required:["axis","candidateCount","selected"],properties:{axis:{type:"string"},candidateCount:{type:"integer",minimum:0},selected:{const:!1}}}}},annotations:{title:"Plan scene gallery",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"check_scene_effects",title:"Check scene effects",description:"Validate one slopcamera.spatial-render-effects document or {document, documentSha256} binding against one scene: scene-digest bindings, entity and asset closure, and nested plan/particle/simulation digests report as findings before any host work.",inputSchema:{type:"object",additionalProperties:!1,required:["scene","effects"],properties:{scene:{...T6,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},effects:{type:"string",description:"Root-relative path to the render-effects document or binding JSON."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","report","summary"],properties:{ok:{const:!0},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:!1,required:["findingCount","returnedFindingCount","findingsTruncated","errorCount","warningCount"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},errorCount:{type:"integer",minimum:0},warningCount:{type:"integer",minimum:0}}}}},annotations:{title:"Check scene effects",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"plan_scene_effects",title:"Plan scene effects",description:"Assemble a canonical {document, documentSha256} render-effects binding for one scene from a draft JSON naming renderPlan, particleSystems and simulationBakes. Entity and asset closure rejects before the document is formed; the scene digest binds here, never by caller assertion.",inputSchema:{type:"object",additionalProperties:!1,required:["scene","draft"],properties:{scene:{...T6,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},draft:{type:"string",description:"Root-relative path to the effects draft JSON ({renderPlan, particleSystems?, simulationBakes?})."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","binding","summary"],properties:{ok:{const:!0},source:{type:"string"},binding:{type:"object"},summary:{type:"object",additionalProperties:!1,required:["documentSha256","particleSystemCount","simulationBakeCount"],properties:{documentSha256:{type:"string"},particleSystemCount:{type:"integer",minimum:0},simulationBakeCount:{type:"integer",minimum:0}}}}},annotations:{title:"Plan scene effects",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"check_scene_behavior",title:"Check scene behavior",description:"Validate one slopcamera.spatial-behavior document against one scene: bake-safe organism profile (input/const/fn/repeat/each/organism cells only), manifest-closure digests, entity and scene-digest bindings, channel declarations, fn-catalog resolution, wiring, and budget bounds report as findings before any host work.",inputSchema:{type:"object",additionalProperties:!1,required:["scene","behavior"],properties:{scene:{...T6,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},behavior:{type:"string",description:"Root-relative path to the spatial behavior document JSON."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","report","summary"],properties:{ok:{const:!0},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:!1,required:["findingCount","returnedFindingCount","findingsTruncated","errorCount","warningCount"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},errorCount:{type:"integer",minimum:0},warningCount:{type:"integer",minimum:0}}}}},annotations:{title:"Check scene behavior",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"audit_scene_behavior",title:"Audit scene behavior trace",description:"Analyze a baked behavior trace for pathological patterns: state thrash (rapid transitions), exact periodicity (trivially cyclic channels), dead channels (constant-valued), and unreachable states (declared in transitions but never visited). Advisory findings for gallery review \u2014 never selects or promotes.",inputSchema:{type:"object",additionalProperties:!1,required:["bake"],properties:{bake:{type:"string",description:"Root-relative path to the behavior bake JSON (slopcamera.spatial-behavior-bake)."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","report","summary"],properties:{ok:{const:!0},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:!1,required:["findingCount","channelCount","emittedCount"],properties:{findingCount:{type:"integer",minimum:0},channelCount:{type:"integer",minimum:0},emittedCount:{type:"integer",minimum:0}}}}},annotations:{title:"Audit scene behavior trace",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"audit_scene_temporal",title:"Audit scene temporal evidence",description:"Evaluate one root-relative spatial scene at bounded sample times under one camera and report deterministic temporal findings: visibility flicker, transform discontinuity, foot-slide against declared contact windows, camera acceleration/jerk/angular velocity, exposure and focus jumps, and resource spikes.",inputSchema:{type:"object",additionalProperties:!1,required:["path","camera_id"],properties:{path:T6,camera_id:UD,times_us:{type:"array",items:{type:"integer",minimum:0,maximum:w0.durationUs},minItems:2,maxItems:O9.samples,description:"Optional sample times in microseconds (2\u2013256). Defaults to evenly spaced coverage of the scene duration."},contacts:{type:"string",description:"Optional root-relative path to a {contacts: [...]} ground-contact evidence JSON."},cut_before_us:{type:"array",items:{type:"integer",minimum:0,maximum:w0.durationUs},maxItems:O9.cutBoundaries,description:"Optional intentional cut boundaries; discontinuities exactly at a cut are not findings."}}},outputSchema:{type:"object",additionalProperties:!1,required:["ok","source","report","summary"],properties:{ok:{const:!0},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:!1,required:["findingCount","returnedFindingCount","findingsTruncated","sampleCount"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},sampleCount:{type:"integer",minimum:2}}}}},annotations:{title:"Audit scene temporal evidence",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}]);class T2 extends Error{code;issues;constructor($,_,F){super(_);if(this.name="ToolFailure",this.code=$,F!==void 0)this.issues=F}}function c8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function U9($,_=160){return $.replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim().slice(0,_)}function vF0($){return $.slice(0,24).map((_)=>U9(_,240))}function q_($,_){let F=Object.keys($).filter((Q)=>!_.has(Q));if(F.length>0)throw new T2("INVALID_ARGUMENTS",`Unsupported argument: ${U9(F[0]??"unknown")}.`)}function sF0($){if(typeof $!=="string"||$.length===0)throw new T2("INVALID_ARGUMENTS","path must be a non-empty root-relative string.");if(!$.toLowerCase().endsWith(".diagram.json"))throw new T2("INVALID_ARGUMENTS","path must end in .diagram.json.");return $}function ec0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");return q_($,new Set(["path"])),{path:sF0($.path)}}function $p0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");q_($,new Set(["path","out_dir","scale"]));let _=$.out_dir;if(_!==void 0&&(typeof _!=="string"||_.length===0))throw new T2("INVALID_ARGUMENTS","out_dir must be a non-empty root-relative string when present.");let F=$.scale??yh;if(typeof F!=="number"||!Number.isFinite(F)||F<=0||F>ZW)throw new T2("RENDER_LIMIT",`scale must be greater than zero and no more than ${ZW}.`);return{path:sF0($.path),..._===void 0?{}:{outDirectory:_},scale:F}}function _p0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");q_($,new Set(["query","limit"]));let _=$.query??"",F=$.limit??_W.length;if(typeof _!=="string"||_.length>200||/[\u0000-\u001f\u007f]/u.test(_)||!Number.isInteger(F)||F<1||F>20)throw new T2("INVALID_ARGUMENTS","query must be a bounded string and limit must be an integer from 1 through 20.");return{query:_,limit:F}}function Fp0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");if(q_($,new Set(["operation","input"])),typeof $.operation!=="string"||!_W.includes($.operation)||!c8($.input))throw new T2("INVALID_ARGUMENTS","operation must be an exact Slopcamera operation code and input must be an object.");return{operation:$.operation,input:$.input}}var Qp0=/^camera_[a-zA-Z0-9][a-zA-Z0-9_-]*$/u;function t9($,_){if(typeof $!=="string"||$.length===0)throw new T2("INVALID_ARGUMENTS",`${_} must be a non-empty root-relative string.`);if(!$.toLowerCase().endsWith(".json"))throw new T2("INVALID_ARGUMENTS",`${_} must end in .json.`);return $}function jR($){if(typeof $!=="string"||$.length>128||!Qp0.test($))throw new T2("INVALID_ARGUMENTS","camera_id must be a scene camera identifier (camera_ followed by letters, digits, _ or -).");return $}function xF0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");return q_($,new Set(["path"])),{path:t9($.path,"path")}}function Zp0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");q_($,new Set(["path","camera_id","times_us","asset_bounds"]));let _;if($.times_us!==void 0){if(!Array.isArray($.times_us)||$.times_us.length===0||$.times_us.length>G$.samples||$.times_us.some((F)=>!Number.isSafeInteger(F)||F<0||F>w0.durationUs))throw new T2("INVALID_ARGUMENTS",`times_us must be an array of 1\u2013${G$.samples} integer microsecond times within the scene duration bound.`);_=[...$.times_us]}return{path:t9($.path,"path"),cameraId:jR($.camera_id),..._===void 0?{}:{timesUs:_},..."asset_bounds"in $?{assetBounds:$.asset_bounds}:{}}}function Jp0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");return q_($,new Set(["path","other"])),{path:t9($.path,"path"),other:t9($.other,"other")}}function Xp0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");q_($,new Set(["path","camera_id","time_us"]));let _=$.time_us;if(typeof _!=="number"||!Number.isSafeInteger(_)||_<0||_>w0.durationUs)throw new T2("INVALID_ARGUMENTS",`time_us must be an integer microsecond time from 0 through ${w0.durationUs}.`);return{path:t9($.path,"path"),cameraId:jR($.camera_id),timeUs:_}}function fh($,_){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");if(q_($,new Set(["scene","direction","camera_id","axis"])),_&&!jQ.safeParse($.axis).success)throw new T2("INVALID_ARGUMENTS",`axis must be one of ${jQ.options.join(", ")}.`);if(!_&&$.axis!==void 0)throw new T2("INVALID_ARGUMENTS","axis is only valid for plan_scene_gallery.");return{scene:t9($.scene,"scene"),direction:t9($.direction,"direction"),...$.camera_id===void 0?{}:{cameraId:jR($.camera_id)},...$.axis===void 0?{}:{axis:$.axis}}}function hF0($,_){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");return q_($,new Set(["scene",_])),{scene:t9($.scene,"scene"),effects:t9($[_],_)}}function Yp0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");return q_($,new Set(["scene","behavior"])),{scene:t9($.scene,"scene"),behavior:t9($.behavior,"behavior")}}function Hp0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");return q_($,new Set(["bake"])),{bake:t9($.bake,"bake")}}function Kp0($){if(!c8($))throw new T2("INVALID_ARGUMENTS","Tool arguments must be an object.");q_($,new Set(["path","camera_id","times_us","contacts","cut_before_us"]));let _=(Z,J)=>{let X=$[Z];if(X===void 0)return;if(!Array.isArray(X)||X.length===0||X.length>J||X.some((Y)=>!Number.isSafeInteger(Y)||Y<0||Y>w0.durationUs))throw new T2("INVALID_ARGUMENTS",`${Z} must be an array of 1\u2013${J} integer microsecond times within the scene duration bound.`);return[...X]},F=_("times_us",O9.samples),Q=_("cut_before_us",O9.cutBoundaries);if(F!==void 0&&F.length<2)throw new T2("INVALID_ARGUMENTS","times_us must contain at least 2 sample times.");return{path:t9($.path,"path"),cameraId:jR($.camera_id),...F===void 0?{}:{timesUs:F},...$.contacts===void 0?{}:{contacts:t9($.contacts,"contacts")},...Q===void 0?{}:{cutBeforeUs:Q}}}function jp0($){for(let _ of $.shapes)if((_.type==="rect"||_.type==="ellipse")&&_.icon!==void 0&&!Object.hasOwn(C9,_.icon))throw new T2("UNKNOWN_ICON",`Shape ${U9(_.id)} requests unavailable built-in icon ${U9(_.icon)}.`)}function Vp0($){let _=$.edges?.length??0;if($.shapes.length>AD||_>RD)throw new T2("COMPLEXITY_LIMIT",`Diagram may contain at most ${AD} shapes and ${RD} edges in MCP mode.`)}function Wp0($){if(!c8($))return;let _=Array.isArray($.shapes)?$.shapes.length:0,F=Array.isArray($.edges)?$.edges.length:0;if(_>AD||F>RD)throw new T2("COMPLEXITY_LIMIT",`Diagram may contain at most ${AD} shapes and ${RD} edges in MCP mode.`)}function Np0($,_){let F=$.canvas.width*_,Q=$.canvas.height*_,Z=Math.ceil(F)*Math.ceil(Q);if(!Number.isFinite(Z)||F<1||Q<1||Z>MD)throw new T2("RENDER_LIMIT",`Scaled canvas must be at least 1 pixel on each axis and no more than ${MD.toLocaleString("en-US")} pixels total.`)}function TZ($,_){return $.length>_?$.slice(0,_):$}function Op0($){return{code:U9($.code,64),message:U9($.message,240),shapeIds:$.shapeIds.slice(0,tc0).map((_)=>U9(_,120))}}function mF0($){return $.slice(0,EX).map(Op0)}function uF0($,_,F){return{shapeCount:$.shapes.length,edgeCount:$.edges?.length??0,findingCount:_,returnedFindingCount:F,findingsTruncated:F<_}}function A$($,_){return{content:[{type:"text",text:$}],structuredContent:_}}function Gp0($){let _="INTERNAL_ERROR",F="The tool failed safely.",Q;if($ instanceof T2)_=$.code,F=U9($.message,320),Q=$.issues;else if($ instanceof r2)_=$.code,F=U9($.message,320);else if($ instanceof h1)_=$.code,F=U9($.message.replace(/^\[[A-Z_]+\]\s*/u,""),320);else if($ instanceof z9)_=$.code,F=U9($.message.replace(/^\[[A-Z_]+\]\s*/u,""),320);else if($ instanceof F0)_=`VECTORIZE_${$.code.toUpperCase()}`,F="Local vectorization failed safely.";else if($ instanceof JK)_="INVALID_DIAGRAM",F="Diagram source did not pass validation.",Q=vF0($.issues);else if($ instanceof l0)_=$.code.toUpperCase().replace(/-/g,"_"),F=U9($.message,320);else if($ instanceof P2)_=`HOST_RESOURCE_${$.code}`,F="Host-resource admission failed safely.";else if(typeof $==="object"&&$!==null&&"issues"in $&&Array.isArray($.issues)&&$.issues.every((J)=>typeof J==="string"))_="INVALID_LAYOUT",F="Diagram layout could not be resolved.",Q=vF0($.issues);let Z=Q===void 0||Q.length===0?"":`
|
|
@@ -5553,7 +5553,7 @@ export default defineWorkflow({
|
|
|
5553
5553
|
`)}async function Sq($,_){let F=R1(gq($),`.replace-${yq()}`);await QY(F,_);try{await z51(F,$),await v_(gq($))}catch(Q){throw await Fj(F).catch(()=>{return}),Q}}async function hq($,_=hK0){if(!Number.isSafeInteger(_)||_<0||_>hK0)throw new N("invalid-data","Run artifact byte bound is invalid.");let F;try{F=await b$($)}catch(Z){if(vF(Z,"ENOENT"))throw new N("not-found",`Run artifact does not exist: ${$}`);throw Z}if(!zd(F)||!Number.isSafeInteger(F.size)||F.size<0||F.size>_)throw new N("unsafe-path",`Run artifact must be a bounded private physical file: ${$}`);let Q=await uq($,xF.O_NOFOLLOW|xF.O_RDONLY|xF.O_NONBLOCK);try{let Z=JY(F),J,X,Y=Buffer.alloc(F.size+1);for(let H of[1,2]){let K=JY(await Q.stat());if(!KN(Z,K)||J!==void 0&&!Qj(J,K))throw new N("conflict",`Run artifact changed before read: ${$}`);let j=0;while(j<Y.byteLength){let{bytesRead:D}=await Q.read(Y,j,Y.byteLength-j,j);if(D===0)break;j+=D}let V=JY(await Q.stat()),O=JY(await b$($)),W=hL("sha256").update(Y.subarray(0,j)).digest("hex");if(!KN(K,V)||!KN(V,O)||j!==K.size||X!==void 0&&X!==W)throw new N("conflict",`Run artifact changed during read: ${$}`);if(Qj(K,V)&&Qj(V,O)&&(H===2||Qj(Z,K)))return Y.subarray(0,j);if(H===2)throw new N("conflict",`Run artifact changed during read: ${$}`);J=O,X=W}throw new N("conflict",`Run artifact changed during read: ${$}`)}finally{await Q.close()}}function $j0($,_){try{return new TextDecoder("utf-8",{fatal:!0}).decode($)}catch(F){throw new N("invalid-data",`Run artifact is not UTF-8 (${_}): ${String(F)}`)}}async function d51($,_){let F=await hq($);return _?.set($,hL("sha256").update(F).digest("hex")),$j0(F,$)}async function _j0($,_){try{return JSON.parse(await d51($,_))}catch(F){if(F instanceof N)throw F;throw new N("invalid-data",`Run artifact is not JSON: ${$}`)}}async function Y$($,_,F){try{return _.parse(await _j0($,F))}catch(Q){if(Q instanceof N)throw Q;throw new N("invalid-data",`Run artifact failed validation (${$}): ${String(Q)}`)}}function Fj0($){let _=$.lastIndexOf(10);return _<0?$.subarray(0,0):$.subarray(0,_+1)}function Qj0($,_,F){let Q=Fj0($);if(Q.byteLength===0)return Object.freeze([]);let Z=$j0(Q,_).split(`
|
|
5554
5554
|
`);if(Z.pop(),Z.length>vq)throw new N("invalid-data",`Run journal exceeds ${String(vq)} entries: ${_}`);return Object.freeze(Z.map((J,X)=>{try{return F.parse(JSON.parse(J))}catch(Y){throw new N("invalid-data",`Invalid run journal entry ${String(X+1)} (${_}): ${String(Y)}`)}}))}async function Ld($,_){return Qj0(await hq($,fq),$,_)}async function iK0($,_,F,Q,Z,J){let X=await b$($);if(!zd(X)||X.size>fq)throw new N("unsafe-path",`Run journal must be a bounded private physical file: ${$}`);let Y=await uq($,xF.O_NOFOLLOW|xF.O_RDWR);try{let H=await Y.stat();if(!ZY(q9(X),q9(H)))throw new N("conflict",`Run journal changed before append: ${$}`);let K=J!==void 0&&Qj(J.snapshot,JY(X))&&Qj(J.snapshot,JY(H)),j,V,O;if(K)j=H.size,V=J.cursor,O=J.entryCount;else{let C=new Uint8Array(await Y.readFile());if(C.byteLength>fq)throw new N("invalid-data",`Run journal exceeds its byte limit: ${$}`);let B=Fj0(C),z=Qj0(C,$,_);if(V=F(z),O=z.length,j=B.byteLength,C.byteLength!==j)await Y.truncate(j),await Y.sync()}if(O>=vq)throw new N("conflict",`Run journal already contains ${String(vq)} entries.`);let W=Q({cursor:V,entryCount:O}),G=_.parse(W.entry),D=new TextEncoder().encode(`${R(G)}
|
|
5555
5555
|
`);if(D.byteLength>M51)throw new N("invalid-data","Run journal entry exceeds its byte limit.");if(j+D.byteLength>fq)throw new N("conflict","Run journal has reached its byte limit.");let w=0;while(w<D.byteLength){let C=await Y.write(D,w,D.byteLength-w,j+w);if(C.bytesWritten<1)throw new N("unavailable",`Run journal append made no progress: ${$}`);w+=C.bytesWritten}await Y.sync();let L=await Y.stat();if(!g51(q9(H),q9(L))||L.size!==j+D.byteLength)throw new N("conflict",`Run journal changed during append: ${$}`);return{result:W.result,state:{cursor:Z(V,G),entryCount:O+1,snapshot:JY(L)}}}finally{await Y.close()}}function aK0($,_){let F=0;for(let[Q,Z]of $.entries()){if(Z.runId!==_||Z.sequence!==Q+1)throw new N("invalid-data",`Run event sequence is inconsistent for ${_}.`);if(Z.fenceGeneration<F)throw new N("invalid-data",`Run event fence generation regressed for ${_}.`);F=Z.fenceGeneration}return{lastFenceGeneration:F,lastSequence:$.at(-1)?.sequence??0}}function Cd($,_,F){let Q=new Set;for(let Z of $){if(Z.runId!==_||Z.graphPlanSha256!==F)throw new N("invalid-data",`Run grant identity is inconsistent for ${_}.`);if(Q.has(Z.grantId))throw new N("invalid-data",`Run grant ID is duplicated: ${Z.grantId}`);Q.add(Z.grantId)}return{grantIds:Q}}function Bd($){return{cancelled:$.filter((_)=>_.status==="cancelled").length,completed:$.filter((_)=>_.status==="completed").length,failed:$.filter((_)=>_.status==="failed"||_.status==="incompatible"||_.status==="ambiguous").length,pending:$.filter((_)=>_.status==="pending"||_.status==="ready"||_.status==="preparing"||_.status==="running"||_.status==="approval-required"||_.status==="ambiguous-code").length,skipped:$.filter((_)=>_.status==="skipped").length}}function c51($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.hasOwn($,"$ref")}function p51($){return Array.isArray($)}function mq($,_,F){if(c51($)){let Z=_.get($.$ref.nodeKey);if(Z?.status!=="completed"||Z.output===void 0)return;return F[Z.nodeKey]=Z.output.digestSha256,vL($,Z.output.value)}if(p51($)){let Z=[];for(let J of $){let X=mq(J,_,F);if(X===void 0)return;Z.push(X)}return Z}let Q={};for(let[Z,J]of Object.entries($).sort(([X],[Y])=>X.localeCompare(Y))){let X=mq(J,_,F);if(X===void 0)return;Q[Z]=X}return Q}function tK0($){if($.some((F)=>F.status==="approval-required"))return"approval-required";if($.some((F)=>F.status==="ambiguous-code"))return"ambiguous-code";if($.some((F)=>F.status==="pending"||F.status==="ready"||F.status==="preparing"||F.status==="running"))return"running";let _=Bd($);if(_.cancelled>0)return"cancelled";if(_.failed===0&&_.skipped===0&&_.completed===$.length)return"completed";if($.some((F)=>F.status==="incompatible")&&_.completed===0)return"incompatible";if(_.completed>0)return"partial";return"failed"}class Ud{#$=new Map;#_=0;#Q;#J;constructor($){let _=$.claimSessionCacheBudgetBytes??Gd;if(!Number.isSafeInteger(_)||_<0||_>Gd)throw new N("usage",`Run claim-session cache budget must be a safe integer from 0 through ${String(Gd)}.`);this.#Q=_,this.#J=k51($.root)}async#Z(){let $=this.#J,_=U51($),F=$.slice(_.root.length).split("/").filter(Boolean),Q=_.root;for(let J of F){Q=R1(Q,J);let X;try{X=await b$(Q)}catch(Y){if(!vF(Y,"ENOENT"))throw Y;try{await xL(Q,{mode:448})}catch(H){if(!vF(H,"EEXIST"))throw H}X=await b$(Q)}if(X.isSymbolicLink()||!X.isDirectory())throw new N("unsafe-path",`Run root crosses a non-physical directory component: ${Q}`)}let Z=await b$($);if(!Iq(Z))throw new N("unsafe-path",`Run root must be an owner-only physical directory (0700): ${$}`);if(await Vd($)!==$)throw new N("unsafe-path",`Run root crosses a symbolic link: ${$}`);return $}async#X($,_=!0){let F=Q_.shape.runId.parse($),Q=await this.#Z(),Z=R1(Q,F);if(_){let J=await b$(Z).catch((X)=>{if(vF(X,"ENOENT"))throw new N("not-found",`Workflow run does not exist: ${F}`);throw X});if(!Iq(J)||await Vd(Z)!==Z)throw new N("unsafe-path",`Workflow run must be an owner-only physical directory (0700): ${F}`)}return Z}async#H($){return await this.#j($,"nodes")}async#j($,_){let F=R1($,_),Q=await b$(F);if(!Iq(Q)||await Vd(F)!==F)throw new N("unsafe-path",`Run ${_} storage must be a physical 0700 directory.`);return F}async#Y($,_){let F=R1($,_);try{await xL(F,{mode:448})}catch(Q){if(!vF(Q,"EEXIST"))throw Q}return await this.#j($,_)}async#V($,_){let F=await this.#X($),Q=R1(F,b51),Z=wd.parse({acquiredAt:new Date().toISOString(),hostname:Eq(),pid:process.pid,token:yq(),version:F_}),J=Date.now()+A51,X;while(X===void 0)try{await bq(Q,Z),X=q9(await b$(Q))}catch(Y){if(!vF(Y,"EEXIST"))throw Y;let H,K;try{K=await b$(Q),H=await Y$(Q,wd)}catch(j){let V=await b$(Q).catch(()=>{return});if(K===void 0||V===void 0||!ZY(q9(K),q9(V))){if(Date.now()>=J)throw new N("conflict",`Timed out waiting for run serialization: ${$}`);await Wd(Od);continue}if(vF(j,"ENOENT")||j instanceof N&&(j.code==="not-found"||j.code==="conflict")){if(Date.now()>=J)throw new N("conflict",`Timed out waiting for run serialization: ${$}`);await Wd(Od);continue}throw new N("unsafe-path",`Run serialization lock is malformed: ${String(j)}`)}if(H.hostname===Eq()&&!sK0(H.pid)){let j=await b$(Q).catch(()=>{return});if(j!==void 0&&ZY(q9(K),q9(j))){await Fj(Q),await v_(F);continue}}if(Date.now()>=J)throw new N("conflict",`Timed out waiting for run serialization: ${$}`);await Wd(Od)}try{return await _(F)}finally{let Y=await b$(Q).catch(()=>{return});if(Y!==void 0&&ZY(X,q9(Y))){if((await Y$(Q,wd).catch(()=>{return}))?.token===Z.token)await Fj(Q).catch(()=>{return}),await v_(F).catch(()=>{return})}}}async#O($,_,F){await this.#j($,"staging");let Q;try{Q=Rl(await _j0(R1($,"graph-plan.json"),F))}catch(j){if(j instanceof N)throw j;throw new N("invalid-data",`Persisted graph plan is invalid: ${String(j)}`)}let Z=await Y$(R1($,Pq),pK0,F);if(Z.runId!==_||Z.graphPlanSha256!==Q.graphPlanSha256)throw new N("invalid-data","Run initialization identity is inconsistent.");let J=await Y$(R1($,"graph.json"),u_,F);if(!k4(J,Q.graph))throw new N("invalid-data","Persisted authored graph differs from its graph plan.");let X=await Y$(R1($,"workflow.json"),Hd,F);if(!k4(X.bundle,Q.bundle)||!k4(X.workflow,Q.graph.workflow))throw new N("invalid-data","Persisted workflow identity differs from its graph plan.");let Y=await Y$(R1($,"runtime.json"),Bq,F);if(!k4(Y.runtime,Q.runtime)||!k4(Y.computes,rK0(Q))||!k4(Y.operations,nK0(Q)))throw new N("invalid-data","Persisted runtime identity differs from its graph plan.");let H=await hq(R1($,"workflow.bundle.js"),Nd),K=hL("sha256").update(H).digest("hex");if(F?.set(R1($,"workflow.bundle.js"),K),H.byteLength!==Q.bundle.bytes||K!==Q.bundle.bundleSha256)throw new N("invalid-data","Persisted workflow bundle bytes changed.");return{bundleBytes:H,directory:$,graphPlan:Q,runtime:Y,workflow:X}}#M($){return[R1($,"graph-plan.json"),R1($,Pq),R1($,"graph.json"),R1($,"workflow.json"),R1($,"runtime.json"),R1($,"workflow.bundle.js")]}async#F($){let _=await Promise.all(this.#M($).map(async(F)=>{let Q=await b$(F);if(!zd(Q))throw new N("unsafe-path",`Run identity must be stored in a private physical file: ${F}`);return[F,JY(Q)]}));return new Map(_)}#B($,_){if($.size!==_.size)return!1;for(let[F,Q]of $){let Z=_.get(F);if(Z===void 0||!Qj(Q,Z))return!1}return!0}async#G($){let _=new Map;for(let[F,Q]of $){let Z=await hq(F,Q.size);_.set(F,hL("sha256").update(Z).digest("hex"))}return _}async#w($,_){let F=await this.#F($),Q=new Map,Z=await this.#O($,_,Q),J=await this.#F($);if(!this.#B(F,J)){for(let[K,j]of F){let V=J.get(K);if(V===void 0||!KN(j,V))throw new N("conflict",`Run identity changed while it was validated: ${_}`)}let Y=await this.#G(J),H=await this.#F($);if(!this.#B(J,H)||[...Q].some(([K,j])=>Y.get(K)!==j))throw new N("conflict",`Run identity changed while it was validated: ${_}`);J=H}let X={directory:Z.directory,graphPlan:Z.graphPlan,runtime:Z.runtime,workflow:Z.workflow};return{identity:X,retainedBytes:x51(X,J),sha256ByPath:Q,snapshots:J}}#K($){let _=this.#$.get($.runId);if(_===void 0||_.fenceGeneration!==$.generation||_.fenceToken!==$.token)return;return this.#$.delete($.runId),this.#$.set($.runId,_),_}#N($){let _=this.#$.get($);if(_===void 0)return;this.#$.delete($),this.#_=Math.max(0,this.#_-_.retainedBytes)}#L($,_){let F=this.#K($),Q={...F?.eventJournal===void 0?{}:{eventJournal:F.eventJournal},...F?.grantJournal===void 0?{}:{grantJournal:F.grantJournal},...F?.identity===void 0?{}:{identity:F.identity},..._,fenceGeneration:$.generation,fenceToken:$.token},Z=h51($.runId,Q);if(this.#N($.runId),Z>T51||Z>this.#Q)return;this.#$.set($.runId,{...Q,retainedBytes:Z}),this.#_=XY(this.#_,Z);while(this.#$.size>R51||this.#_>this.#Q){let J=this.#$.keys().next().value;if(J===void 0)break;this.#N(J)}}#q($){let _=this.#$.get($.runId);if(_?.fenceGeneration===$.generation&&_.fenceToken===$.token)this.#N($.runId)}async#k($,_){let F=this.#K(_)?.identity;if(F!==void 0)try{let Z=await this.#F($);if(this.#B(F.snapshots,Z))return F.identity;for(let[Y,H]of F.snapshots){let K=Z.get(Y);if(K===void 0||!KN(H,K))throw new N("conflict",`Run identity metadata changed: ${Y}`)}let J=await this.#G(Z),X=await this.#F($);if(!this.#B(Z,X))throw new N("conflict","Run identity changed during revalidation.");for(let[Y,H]of F.sha256ByPath)if(J.get(Y)!==H)throw new N("conflict",`Run identity bytes changed: ${Y}`);return this.#L(_,{identity:{...F,snapshots:X}}),F.identity}catch(Z){throw this.#q(_),new N("conflict",`Run identity changed while its claim was active: ${_.runId} (${String(Z)})`)}let Q=await this.#w($,_.runId);return this.#L(_,{identity:Q}),Q.identity}async#D($){let _=await this.#X($);return await this.#O(_,$)}async create($){let _=vK0.parse($),F=Rl(_.graphPlan);if(_.bundleBytes.byteLength>Nd)throw new N("invalid-data",`Workflow bundle exceeds ${String(Nd)} bytes.`);let Q=hL("sha256").update(_.bundleBytes).digest("hex");if(_.bundleBytes.byteLength!==F.bundle.bytes||Q!==F.bundle.bundleSha256||!k4(_.workflow.bundle,F.bundle))throw new N("invalid-data","Workflow bundle identity or bytes do not match.");if(!k4(_.workflow.workflow,F.graph.workflow)||_.workflow.sourceLocator!==_.sourceLocator)throw new N("invalid-data","Workflow source identity does not match the graph plan.");if(!k4(_.runtime.runtime,F.runtime)||!k4(_.runtime.computes,rK0(F))||!k4(_.runtime.operations,nK0(F)))throw new N("invalid-data","Workflow runtime or operation identities do not match.");let Z=await this.#X(_.runId,!1),J=gq(Z);try{await xL(Z,{mode:448})}catch(K){if(vF(K,"EEXIST"))throw new N("conflict",`Workflow run already exists: ${_.runId}`);throw K}if(await v_(J),!Iq(await b$(Z)))throw new N("unsafe-path","New workflow run directory is not private.");await xL(R1(Z,"nodes"),{mode:448}),await xL(R1(Z,"staging"),{mode:448}),await QY(R1(Z,"runtime.json"),_.runtime),await QY(R1(Z,"workflow.json"),_.workflow),await uL(R1(Z,"workflow.bundle.js"),_.bundleBytes),await QY(R1(Z,"graph.json"),F.graph),await QY(R1(Z,"graph-plan.json"),F),await uL(R1(Z,"events.jsonl"),""),await uL(R1(Z,"grants.jsonl"),"");let X=await this.#H(Z);for(let K of F.graph.nodes){let j=Z_.parse({attempt:0,dependencies:K.dependencies,executor:K.executor,nodeKey:K.key,status:K.dependencies.length===0?"ready":"pending",version:$Y});await QY(R1(X,_Y(K.key)),j)}let Y=new Date().toISOString(),H=hZ.parse({counts:{cancelled:0,completed:0,failed:0,pending:F.graph.nodes.length,skipped:0},graphPlanSha256:F.graphPlanSha256,runId:_.runId,status:"planned",updatedAt:Y,version:F_});return await QY(R1(Z,"summary.json"),H),await QY(R1(Z,Pq),{graphPlanSha256:F.graphPlanSha256,runId:_.runId,version:F_}),await v_(X),await v_(R1(Z,"staging")),await v_(Z),H}async list(){let $=await this.#Z(),_=await B51($,{withFileTypes:!0}),F=[];for(let Q of _.sort((Z,J)=>Z.name.localeCompare(J.name))){if(!Q.isDirectory()||!Q.name.startsWith("run_"))continue;try{let Z=await this.#X(Q.name),J=await Y$(R1(Z,Pq),pK0),X=await Y$(R1(Z,"summary.json"),hZ);if(J.runId!==X.runId||J.graphPlanSha256!==X.graphPlanSha256)continue;F.push(X)}catch{}}return Object.freeze(F.sort((Q,Z)=>Z.updatedAt.localeCompare(Q.updatedAt)))}async graphPlan($){return(await this.#D($)).graphPlan}async graph($){return(await this.#D($)).graphPlan.graph}async workflow($){return(await this.#D($)).workflow}async runtime($){return(await this.#D($)).runtime}async bundle($){return new Uint8Array((await this.#D($)).bundleBytes)}async stagingDirectory($,_,F){let Q=Q_.parse($),Z=m4.parse(_),J=W2.parse(F);return await this.#V(Q.runId,async(X)=>{await this.#U(X,Q);let Y=await this.#k(X,Q),H=await Y$(R1(await this.#H(X),_Y(Z)),Z_);if(H.nodeKey!==Z||H.executionPlan?.nodePlanSha256!==J)throw new N("conflict",`Node staging identity does not match its exact execution plan: ${Z}`);let K=await this.#j(Y.directory,"staging"),j=_Y(Z).slice(0,-5),V=await this.#Y(K,j),O=await this.#Y(V,J);return await v_(V),await v_(K),O})}async summary($){let _=await this.#D($),F=await Y$(R1(_.directory,"summary.json"),hZ);if(F.runId!==$||F.graphPlanSha256!==_.graphPlan.graphPlanSha256)throw new N("invalid-data","Run summary identity is inconsistent.");if(F.outputs!==void 0){let Q=await this.outputs($);if(Q===void 0||!k4(Q.outputs,F.outputs))throw new N("invalid-data","Run summary output identity is inconsistent.")}if(Dd.has(F.status)){let Q=await this.#z(_);if(!k4(F.counts,Bd(Q))||F.status!==tK0(Q)||F.finishedAt===void 0)throw new N("invalid-data","Terminal run summary is inconsistent with node state.")}return F}async#z($){let _=await this.#H($.directory),F=await Promise.all($.graphPlan.graph.nodes.map(async(Z)=>await Y$(R1(_,_Y(Z.key)),Z_))),Q=new Map(F.map((Z)=>[Z.nodeKey,Z]));if(Q.size!==$.graphPlan.graph.nodes.length)throw new N("invalid-data","Run node identities are duplicated or missing.");for(let Z of $.graphPlan.graph.nodes){let J=Q.get(Z.key);if(J===void 0)throw new N("invalid-data",`Run is missing authored node ${Z.key}.`);this.#A($.graphPlan,Z,J,Q)}return Object.freeze(F)}async#P($,_){let F=$.graphPlan.graph.nodes.find((V)=>V.key===_);if(F===void 0)throw new N("not-found",`Workflow run node does not exist: ${_}`);let Q=await this.#H($.directory),Z=new Map($.graphPlan.graph.nodes.map((V)=>[V.key,V])),J=new Set,X=[F.key];while(X.length>0){let V=X.pop();if(V===void 0||J.has(V))continue;let O=Z.get(V);if(O===void 0)throw new N("invalid-data",`Run graph is missing dependency ${V}.`);J.add(V),X.push(...O.dependencies)}let Y=[...J],H=await Promise.all(Y.map(async(V)=>await Y$(R1(Q,_Y(V)),Z_))),K=new Map(H.map((V)=>[V.nodeKey,V]));if(K.size!==Y.length)throw new N("invalid-data",`Run node context contains duplicated or missing identities: ${_}`);for(let V of Y){let O=K.get(V),W=Z.get(V);if(O===void 0||W===void 0)throw new N("invalid-data",`Run is missing authored node ${V}.`);this.#A($.graphPlan,W,O,K)}let j=K.get(F.key);if(j===void 0)throw new N("invalid-data",`Run is missing authored node ${F.key}.`);return{authored:F,record:j,recordsByKey:K}}#A($,_,F,Q){if(F.nodeKey!==_.key||!k4(F.dependencies,_.dependencies)||!k4(F.executor,_.executor))throw new N("invalid-data",`Persisted node identity changed: ${_.key}`);let Z=oK0($,_);if(F.executionPlan!==void 0&&F.preparationPlan===void 0)throw new N("invalid-data",`Execution plan has no preparation plan for node ${_.key}.`);if(F.preparationPlan!==void 0){let{preparationPlanSha256:J,...X}=F.preparationPlan;if(F.preparationPlan.version!==IL||J!==SL(X)||F.preparationPlan.graphPlanSha256!==$.graphPlanSha256||F.preparationPlan.nodeKey!==_.key||!k4(F.preparationPlan.executor,_.executor)||!k4(F.preparationPlan.requestedPreparation,[...Z.preparation].sort((Y,H)=>Y.localeCompare(H)))||F.preparationPlan.upperDurationMs>Z.maxDurationMs||F.preparationPlan.upperInputBytes>Z.maxInputBytes)throw new N("invalid-data",`Preparation plan digest or identity is invalid for node ${_.key}.`)}if(F.executionPlan!==void 0){let{nodePlanSha256:J,...X}=F.executionPlan,Y=Object.fromEntries([..._.dependencies].sort((K,j)=>K.localeCompare(j)).map((K)=>{let j=Q.get(K);if(j?.status!=="completed"||j.output===void 0)throw new N("invalid-data",`Execution plan for ${_.key} references incomplete dependency ${K}.`);return[K,j.output.digestSha256]})),H=[...F.executionPlan.publicationKeys].sort((K,j)=>K.localeCompare(j));if(F.executionPlan.version!==bL||J!==fL(X)||F.executionPlan.inputSha256!==yK0(F.executionPlan.exactInput)||F.executionPlan.graphPlanSha256!==$.graphPlanSha256||F.executionPlan.nodeKey!==_.key||F.executionPlan.preparationPlanSha256!==F.preparationPlan?.preparationPlanSha256||!k4(F.executionPlan.executor,_.executor)||!k4(F.executionPlan.policy,m51(Z))||!k4(F.executionPlan.dependencyOutputDigests,Y)||!k4(F.executionPlan.publicationKeys,H)||new Set(H).size!==H.length)throw new N("invalid-data",`Execution plan digest or identity is invalid for node ${_.key}.`)}if(F.output!==void 0&&F.output.digestSha256!==gK0(F.output.value))throw new N("invalid-data",`Output digest is invalid for node ${_.key}.`)}async node($,_){let F=m4.parse(_),Q=await this.#D($);return(await this.#P(Q,F)).record}async nodes($){let _=await this.#D($);return await this.#z(_)}async events($){let _=await this.#X($),F=await Ld(R1(_,"events.jsonl"),Tq);return aK0(F,$),F}async grants($){let _=await this.#D($),F=await Ld(R1(_.directory,"grants.jsonl"),yL);return Cd(F,$,_.graphPlan.graphPlanSha256),F}async outputs($){let _=await this.#D($),F=R1(_.directory,"outputs.json"),Q=await Y$(F,qq).catch((H)=>{if(H instanceof N&&H.code==="not-found")return;throw H});if(Q===void 0)return;if(Q.runId!==$||Q.graphPlanSha256!==_.graphPlan.graphPlanSha256||Q.outputsSha256!==jd(Q.outputs))throw new N("invalid-data","Persisted run outputs have an invalid identity.");let Z=await this.#z(_),J=new Map(Z.map((H)=>[H.nodeKey,H])),X={},Y=mq(_.graphPlan.graph.outputs,J,X);if(Y===void 0||!k4(Q.outputs,Y)||!k4(Q.nodeOutputDigests,X))throw new N("invalid-data","Persisted run outputs differ from completed nodes.");return Q}async#R($){let _=R1($,FY),F;try{F=await b$(_)}catch(Z){if(vF(Z,"ENOENT"))return;throw Z}return{fence:await Y$(_,Q_),snapshot:q9(F)}}async#U($,_){let F=Q_.parse(_),Q=await this.#R($);if(Q===void 0||Q.fence.generation!==F.generation||Q.fence.token!==F.token||Q.fence.owner!==F.owner||Q.fence.runId!==F.runId)throw this.#q(F),new N("conflict",`Workflow run fence is stale: ${F.runId}`);return F}async#E($,_,F){let Q=this.#K(_)?.eventJournal,Z=await iK0(R1($,"events.jsonl"),Tq,(J)=>aK0(J,_.runId),({cursor:J})=>{if(_.generation<J.lastFenceGeneration)throw new N("invalid-data",`Run event fence generation regressed for ${_.runId}.`);let X=Tq.parse({...F,fenceGeneration:_.generation,runId:_.runId,sequence:J.lastSequence+1,version:Qd});return{entry:X,result:X}},(J,X)=>({lastFenceGeneration:X.fenceGeneration,lastSequence:X.sequence}),Q);return this.#L(_,{eventJournal:Z.state}),Z.result}async acquireClaim($,_){return await this.#V($,async(F)=>{let Q=await this.#w(F,$),Z=(_.now??(()=>new Date))(),J=_.staleAfterMs??30000;if(!Number.isSafeInteger(J)||J<0)throw new N("usage","Run claim stale interval must be a nonnegative safe integer.");let X=await this.#R(F),Y=X?.fence.generation??0;if(X!==void 0){let V=Z.getTime()-Date.parse(X.fence.acquiredAt),O=X.fence.hostname!==Eq()||(_.processAlive??sK0)(X.fence.pid);if(V<J||O)throw new N("conflict",`Workflow run is already claimed: ${$}`,{acquiredAt:X.fence.acquiredAt,owner:X.fence.owner,pid:X.fence.pid});let W=await b$(R1(F,FY)).catch(()=>{return});if(W===void 0||!ZY(X.snapshot,q9(W)))throw new N("conflict",`Workflow run claim changed during reclaim: ${$}`);await Fj(R1(F,FY)),await v_(F)}this.#N($);let H=await Y$(R1(F,cK0),S51).catch((V)=>{if(V instanceof N&&V.code==="not-found")return;throw V});Y=Math.max(Y,H?.generation??0);let K=Y+1,j=Q_.parse({acquiredAt:Z.toISOString(),generation:K,hostname:Eq(),owner:_.owner,pid:process.pid,runId:$,token:yq(),version:Jd});await Sq(R1(F,cK0),{generation:K,version:F_});try{return await bq(R1(F,FY),j),await this.#E(F,j,{details:{owner:j.owner},kind:"run-claimed",timestamp:j.acquiredAt}),this.#L(j,{identity:Q}),j}catch(V){this.#q(j);let O=await this.#R(F).catch(()=>{return});if(O?.fence.token===j.token&&O.fence.generation===j.generation){let W=await b$(R1(F,FY)).catch(()=>{return});if(W!==void 0&&ZY(O.snapshot,q9(W)))await Fj(R1(F,FY)).catch(()=>{return}),await v_(F).catch(()=>{return})}throw V}})}async assertFence($){let _=Q_.parse($);await this.#U(await this.#X(_.runId),_)}async releaseClaim($){let _=Q_.parse($);await this.#V(_.runId,async(F)=>{await this.#U(F,_);let Q=await this.#R(F);if(Q===void 0)throw new N("conflict",`Workflow run fence is stale: ${_.runId}`);let Z=await b$(R1(F,FY));if(!ZY(Q.snapshot,q9(Z)))throw new N("conflict",`Workflow run claim changed during release: ${_.runId}`);await Fj(R1(F,FY)),await v_(F),this.#q(_)})}async appendEvent($,_){let F=Q_.parse($);return await this.#V(F.runId,async(Q)=>{if(await this.#U(Q,F),_.nodeKey!==void 0){if(!(await this.#k(Q,F)).graphPlan.graph.nodes.some((J)=>J.key===_.nodeKey))throw new N("invalid-data",`Run event names an unknown node: ${_.nodeKey}`)}return await this.#E(Q,F,_)})}#C($,_,F,Q,Z){if(f51.has(F.status)){if(!k4(F,Q))throw new N("conflict",`Terminal run node ${F.nodeKey} is immutable.`);return}if(!y51[F.status].has(Q.status))throw new N("invalid-data",`Illegal run node transition ${F.status} -> ${Q.status} for ${F.nodeKey}.`);let J=F.status==="ready"&&Q.status==="running"?F.attempt+1:F.attempt;if(Q.attempt!==J)throw new N("invalid-data",`Run node attempt changed outside ready -> running for ${F.nodeKey}.`);if(F.preparationPlan!==void 0&&!k4(F.preparationPlan,Q.preparationPlan))throw new N("conflict",`Preparation plan changed for ${F.nodeKey}.`);if(F.executionPlan!==void 0&&!k4(F.executionPlan,Q.executionPlan))throw new N("conflict",`Execution plan changed for ${F.nodeKey}.`);if(!(F.status==="ready"&&Q.status==="running")&&F.startedAt!==Q.startedAt)throw new N("invalid-data",`Run node startedAt changed illegally: ${F.nodeKey}`);if(F.status==="ready"&&Q.status==="running"&&F.startedAt!==void 0&&Date.parse(Q.startedAt)<Date.parse(F.startedAt))throw new N("invalid-data",`Run node startedAt regressed: ${F.nodeKey}`);if(F.status==="pending"&&Q.status==="ready"&&_.dependencies.some((X)=>Z.get(X)?.status!=="completed"))throw new N("invalid-data",`Run node ${F.nodeKey} became ready before all dependencies completed.`);if(F.status==="running"&&Q.status==="ready"){let X=oK0($,_).resume;if(X!=="deterministic"&&X!=="verified-receipt"&&X!=="recoverable-transaction")throw new N("conflict",`Interrupted node ${F.nodeKey} cannot be retried under ${X}.`)}}async writeNode($,_){let F=Q_.parse($);await this.#V(F.runId,async(Q)=>{await this.#U(Q,F);let Z=Z_.parse(_),J=await this.#k(Q,F),X=await this.#P(J,Z.nodeKey),Y=new Map(X.recordsByKey);Y.set(Z.nodeKey,Z),this.#C(J.graphPlan,X.authored,X.record,Z,Y),this.#A(J.graphPlan,X.authored,Z,Y);let H=await this.#H(Q);await Sq(R1(H,_Y(Z.nodeKey)),Z)})}async writeSummary($,_){let F=Q_.parse($);await this.#V(F.runId,async(Q)=>{await this.#U(Q,F);let Z=hZ.parse(_),J=await this.#k(Q,F);if(Z.runId!==F.runId||Z.graphPlanSha256!==J.graphPlan.graphPlanSha256)throw new N("invalid-data","Run summary identity is inconsistent.");let X=await Y$(R1(Q,"summary.json"),hZ);if(Dd.has(X.status)){if(!k4(X,Z))throw new N("conflict","Terminal run summary is immutable.");return}if(Date.parse(Z.updatedAt)<Date.parse(X.updatedAt))throw new N("invalid-data","Run summary updatedAt regressed.");if(X.startedAt!==void 0&&Z.startedAt!==X.startedAt)throw new N("invalid-data","Run summary startedAt changed.");if(Z.status!=="planned"&&Z.startedAt===void 0)throw new N("invalid-data","Started run summaries require startedAt.");if(Dd.has(Z.status)!==(Z.finishedAt!==void 0))throw new N("invalid-data","Only terminal run summaries require finishedAt.");let H=await this.#z(J);if(!k4(Z.counts,Bd(H)))throw new N("invalid-data","Run summary counts do not match node state.");let K=tK0(H);if(Z.status!==K)throw new N("invalid-data",`Run summary status ${Z.status} does not match ${K}.`);if(Z.status==="completed"){let j={},V=new Map(H.map((G)=>[G.nodeKey,G])),O=mq(J.graphPlan.graph.outputs,V,j);if(O===void 0||Z.outputs===void 0||!k4(Z.outputs,O))throw new N("invalid-data","Completed run outputs do not match the authored output bindings.");let W=qq.parse({graphPlanSha256:J.graphPlan.graphPlanSha256,nodeOutputDigests:j,outputs:O,outputsSha256:jd(O),runId:F.runId,version:Xd});try{await bq(R1(Q,"outputs.json"),W)}catch(G){if(!vF(G,"EEXIST"))throw G;let D=await Y$(R1(Q,"outputs.json"),qq);if(!k4(D,W))throw new N("conflict","Run outputs were already published differently.")}}else if(Z.outputs!==void 0)throw new N("invalid-data","Only completed runs may publish outputs.");await Sq(R1(Q,"summary.json"),Z)})}async appendGrant($,_){let F=Q_.parse($);return await this.#V(F.runId,async(Q)=>{await this.#U(Q,F);let Z=await this.#k(Q,F),J=yL.parse({..._,runId:F.runId,version:Zd});if(J.graphPlanSha256!==Z.graphPlan.graphPlanSha256)throw new N("invalid-data","Run grant targets a different graph plan.");if("nodeKey"in J&&!Z.graphPlan.graph.nodes.some((H)=>H.key===J.nodeKey))throw new N("invalid-data",`Run grant targets unknown node ${J.nodeKey}.`);if(J.kind==="compute-replay"&&J.bundleSha256!==Z.graphPlan.bundle.bundleSha256)throw new N("invalid-data","Compute replay grant targets a different bundle.");if(J.kind==="compute-replay"){let H=Z.graphPlan.graph.nodes.find((V)=>V.key===J.nodeKey);if(H===void 0||!F8(H))throw new N("invalid-data",`Compute replay grant targets a non-compute node: ${J.nodeKey}`);let j=(await this.#z(Z)).find((V)=>V.nodeKey===J.nodeKey);if(j?.status!=="ambiguous-code"||j.executionPlan===void 0||J.computeKey!==H.executor.compute.key||J.nodePlanSha256!==j.executionPlan.nodePlanSha256||J.attempt!==j.attempt+1)throw new N("conflict",`Compute replay grant does not match the exact next attempt for ${J.nodeKey}.`)}let X=this.#K(F)?.grantJournal,Y=await iK0(R1(Q,"grants.jsonl"),yL,(H)=>Cd(H,F.runId,Z.graphPlan.graphPlanSha256),({cursor:H})=>{if(H.grantIds.has(J.grantId))throw new N("conflict",`Run grant already exists: ${J.grantId}`);return{entry:J,result:J}},(H,K)=>{return H.grantIds.add(K.grantId),H},X);return this.#L(F,{grantJournal:Y.state}),Y.result})}async reopenComputeNode($,_){let F=Q_.parse($),Q=m4.parse(_);return await this.#V(F.runId,async(Z)=>{await this.#U(Z,F);let J=await this.#k(Z,F),X=J.graphPlan.graph.nodes.find((G)=>G.key===Q);if(X===void 0||!F8(X))throw new N("invalid-data",`Only a trusted compute node may be reopened: ${Q}`);let Y=await this.#z(J),H=Y.find((G)=>G.nodeKey===Q);if(H?.status!=="ambiguous-code"||H.executionPlan===void 0)throw new N("conflict",`Compute node is not awaiting an explicit replay: ${Q}`);let K=await Ld(R1(Z,"grants.jsonl"),yL);if(Cd(K,F.runId,J.graphPlan.graphPlanSha256),!K.some((G)=>G.kind==="compute-replay"&&G.nodeKey===Q&&G.attempt===H.attempt+1&&G.bundleSha256===J.graphPlan.bundle.bundleSha256&&G.computeKey===X.executor.compute.key&&G.nodePlanSha256===H.executionPlan?.nodePlanSha256))throw new N("authorization-required",`Compute node ${Q} requires an exact replay grant for attempt ${String(H.attempt+1)}.`);let V={...H};delete V.failure,delete V.finishedAt;let O=Z_.parse({...V,status:"ready"}),W=new Map(Y.map((G)=>[G.nodeKey,G.nodeKey===Q?O:G]));return this.#A(J.graphPlan,X,O,W),await Sq(R1(await this.#H(Z),_Y(Q)),O),O})}async requestCancellation($,_,F=new Date){return await this.#V($,async(Q)=>{await this.#O(Q,$);let Z=R1(Q,"cancel-request.json"),J=await Y$(Z,gL).catch((Y)=>{if(Y instanceof N&&Y.code==="not-found")return;throw Y});if(J!==void 0)return J;let X=gL.parse({requestedAt:F.toISOString(),requestedBy:_,runId:$,version:F_});try{return await bq(Z,X),X}catch(Y){let H=await Y$(Z,gL).catch(()=>{return});if(H!==void 0)return H;throw Y}})}async cancellation($){let _=await this.#X($);return await Y$(R1(_,"cancel-request.json"),gL).then((F)=>{if(F.runId!==$)throw new N("invalid-data","Cancellation request targets a different run.");return F}).catch((F)=>{if(F instanceof N&&F.code==="not-found")return;throw F})}}import{Deferred as cq,Effect as d1,Either as lL,Exit as Zj0,Fiber as s51,Queue as kd}from"effect";import{randomUUID as Md}from"crypto";import{performance as YY}from"perf_hooks";var n51=32,r51=128,o51=2000,i51=4000,a51=100,t51=Object.freeze({browser:1,"capture-device":1,cpu:4,ffmpeg:2,"local-io":4,network:4,"output-publication":4,"paid-call":1,"project-render":1,"project-publication":1,vision:1,whisper:1});function Jj0($,_){return _>Number.MAX_SAFE_INTEGER-$?Number.MAX_SAFE_INTEGER:$+_}function qd($){return d1.suspend(()=>{let _=$-YY.now();return _<=0?d1.void:d1.zipRight(d1.sleep(Math.min(_,2147483647)),qd($))})}class Vj0{#$=new AbortController;deadlineMonotonicMs;#_;#Q;#J;#Z;#X;constructor($,_,F){this.#J=$,this.deadlineMonotonicMs=_,this.#Q=F,this.#_=$.deferred(),this.#Z=$.watch(d1.zipRight(qd(_),d1.sync(()=>{this.interrupt("deadline",new N("cancelled","Workflow exceeded the host wall-clock bound."))})))}get interruption(){return this.#X}get signal(){return this.#$.signal}interrupt($,_){if(this.#X!==void 0)return;let F={error:_,kind:$};this.#X=F,this.#$.abort(_),this.#Q(F),cq.unsafeDone(this.#_,d1.fail($3(_,"monitor")))}assertActive(){if(this.#X!==void 0)throw this.#X.error}async race($){return this.assertActive(),await this.#J.run(d1.raceFirst(A1("authority",$),cq.await(this.#_)))}async custody($){return await this.#J.custody($)}async runNative($){return await this.#J.run($)}async stop(){await this.#Z()}}function dL($,_){if(!Number.isSafeInteger($)||$<1)throw new N("usage",`${_} must be a positive safe integer.`);return $}function e51($,_){if(!Number.isSafeInteger($)||$<0)throw new N("usage",`${_} must be a nonnegative safe integer.`);return $}function $$1($){let _=dL($.hostLimits?.maxJobs??4,"Host job limit"),F=$.jobs===void 0?_:dL($.jobs,"Requested job limit"),Q=$.hostLimits?.resources??{},Z=Object.fromEntries(Yw.map((J)=>[J,e51(Q[J]??t51[J],`Host ${J} limit`)]));return{cancellationPollMs:dL($.cancellationPollMs??a51,"Cancellation poll interval"),jobs:Math.min(_,F),maxNodes:dL($.hostLimits?.maxNodes??4096,"Host node limit"),maxWallClockMs:dL($.hostLimits?.maxWallClockMs??86400000,"Host workflow wall-clock limit"),resources:Z}}function _$1($){return Rq($).sha256}function Wj0($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.hasOwn($,"$ref")}function F$1($){return Array.isArray($)}function Q$1($){return Array.isArray($)}function Ed($){if($.status!=="completed"||$.output===void 0)throw new N("invalid-data",`Dependency ${$.nodeKey} does not have a completed output.`);let _=L1.parse($.output.value);if(_$1(_)!==$.output.digestSha256)throw new N("invalid-data",`Completed output digest does not match for node ${$.nodeKey}.`);return $.output}function Rd($,_){if(Wj0($)){let F=_.get($.$ref.nodeKey);if(F===void 0)throw new N("invalid-data",`Node input references unavailable output ${$.$ref.nodeKey}.`);return vL($,F.value)}if(F$1($))return $.map((F)=>Rd(F,_));if(typeof $==="object"&&$!==null)return Object.fromEntries(Object.entries($).sort(([F],[Q])=>F.localeCompare(Q)).map(([F,Q])=>[F,Rd(Q,_)]));return $}function Xj0($,_){let F=new Map,Q={};for(let Z of[...$.dependencies].sort((J,X)=>J.localeCompare(X))){let J=_.get(Z);if(J===void 0)throw new N("invalid-data",`Missing dependency node ${Z}.`);let X=Ed(J);F.set(Z,X),Q[Z]=X}return{dependencyOutputs:Q,input:L1.parse(Rd($.input,F))}}function Pd($){return jj.parse({...$,preparation:[...$.preparation].sort((_,F)=>_.localeCompare(F)),resources:[...$.resources].sort((_,F)=>_.resource.localeCompare(F.resource))})}function Yj0($){return{...$,inputSchemaId:$.inputSchemaId.replace(/^studio\./u,"slopcamera."),outputSchemaId:$.outputSchemaId.replace(/^studio\./u,"slopcamera."),policy:Kj.parse(Pd($.policy))}}function cL($,_,F){let Q=_.executor.operation,Z=F.get(Q.kind,Q.version),J=$.registry.discovery.find((X)=>X.kind===Q.kind&&X.version===Q.version);if(J===void 0)throw new N("incompatible",`Graph plan omits operation ${Q.kind}@${String(Q.version)}.`);if(R(Yj0(Z.discovery))!==R(Yj0(J)))throw new N("incompatible",`Registered operation changed after planning: ${Q.kind}@${String(Q.version)}.`);return Z}function Hj0($,_,F){if(M4(_)){let Q=cL($,_,F);return{kind:"operation",operation:Q,policy:Q.discovery.policy}}if(F8(_))return{compute:_.executor.compute,kind:"compute",policy:Vj(_.executor.compute)};throw new N("internal",`Unknown node executor for ${_.key}.`)}function Nj0($){if($.length>64)throw new N("invalid-data","A node may claim at most 64 publication keys.");let _=[...$].map((F)=>{if(F.length<1||F.length>512)throw new N("invalid-data","Publication keys must contain between 1 and 512 characters.");return F}).sort((F,Q)=>F.localeCompare(Q));if(new Set(_).size!==_.length)throw new N("invalid-data","A node cannot claim a publication key twice.");return _}function Z$1($){let _=J3($.input,"studio.workflow.compute-input-descriptor/v1\x00");return{inputDescriptors:L1.parse({bytes:_.bytes,inputSha256:_.sha256}),upperInputBytes:_.bytes}}function J$1($,_,F,Q){let Z=Q.upperDurationMs??F.maxDurationMs,J=Q.upperInputBytes??F.maxInputBytes;if(!Number.isSafeInteger(Z)||Z<0||Z>F.maxDurationMs)throw new N("invalid-data",`Preparation duration bound exceeds policy for node ${_.key}.`);if(!Number.isSafeInteger(J)||J<0||J>F.maxInputBytes)throw new N("invalid-data",`Preparation input bound exceeds policy for node ${_.key}.`);let X=zq.parse({exactInputBound:!0,executor:_.executor,graphPlanSha256:$.graphPlanSha256,inputDescriptors:L1.parse(Q.inputDescriptors),nodeKey:_.key,requestedPreparation:[...F.preparation].sort((Y,H)=>Y.localeCompare(H)),upperDurationMs:Z,upperInputBytes:J,version:IL});return Uq.parse({...X,preparationPlanSha256:SL(X)})}function X$1($,_,F,Q,Z,J){let X=L1.parse(J.exactInput),Y=Aq(X),H=Y.bytes,K=Q.exactInputBound===!0?Q.upperInputBytes:F.maxInputBytes;if(H>K)throw new N("invalid-data",`Exact input for node ${_.key} uses ${String(H)} canonical JSON bytes; the ${Q.exactInputBound===!0?"prepared upper bound":"operation input limit"} is ${String(K)}.`);let j=Object.fromEntries(Object.entries(Z.dependencyOutputs).sort(([O],[W])=>O.localeCompare(W)).map(([O,W])=>[O,W.digestSha256])),V=kq.parse({dependencyOutputDigests:j,executor:_.executor,exactInput:X,...J.expectedProjectGeneration===void 0?{}:{expectedProjectGeneration:J.expectedProjectGeneration},graphPlanSha256:$.graphPlanSha256,inputSha256:Y.sha256,nodeKey:_.key,policy:Pd(F),preparationPlanSha256:Q.preparationPlanSha256,publicationKeys:Nj0(J.publicationKeys),version:bL});return Mq.parse({...V,nodePlanSha256:fL(V)})}function Y$1($,_,F,Q){let Z=Uq.parse($),{preparationPlanSha256:J,...X}=Z;if(J!==SL(X)||Z.graphPlanSha256!==_.graphPlanSha256||Z.nodeKey!==F.key||R(Z.executor)!==R(F.executor)||Z.upperDurationMs>Q.maxDurationMs||Z.upperInputBytes>Q.maxInputBytes||R(Z.requestedPreparation)!==R([...Q.preparation].sort((Y,H)=>Y.localeCompare(H))))throw new N("invalid-data",`Persisted preparation plan no longer matches node ${F.key}.`)}function H$1($,_,F,Q,Z,J){let X=Mq.parse($),{nodePlanSha256:Y,...H}=X,K=Aq(X.exactInput),j=K.bytes,V=Z.exactInputBound===!0?Z.upperInputBytes:Q.maxInputBytes,O=Object.fromEntries(Object.entries(J.dependencyOutputs).sort(([W],[G])=>W.localeCompare(G)).map(([W,G])=>[W,G.digestSha256]));if(Y!==fL(H)||j>V||X.inputSha256!==K.sha256||X.graphPlanSha256!==_.graphPlanSha256||X.nodeKey!==F.key||X.preparationPlanSha256!==Z.preparationPlanSha256||R(X.executor)!==R(F.executor)||R(X.policy)!==R(Pd(Q))||R(X.dependencyOutputDigests)!==R(O)||R(X.publicationKeys)!==R(Nj0(X.publicationKeys)))throw new N("invalid-data",`Persisted execution plan no longer matches node ${F.key}.`)}function Kj0($){return typeof $==="boolean"?$:$.allowed}function K$1($,_,F,Q){return $.some((Z)=>Z.kind==="preparation"&&Z.graphPlanSha256===_&&Z.nodeKey===F&&Z.preparationPlanSha256===Q)}function j$1($,_,F,Q){return $.some((Z)=>Z.kind==="effect"&&Z.graphPlanSha256===_&&Z.nodeKey===F&&Z.nodePlanSha256===Q)}function V$1($){return($.length===0?"Unknown scheduler failure.":$).slice(0,i51)}function t8($,_=!1){let F=UY($),Q=W8.safeParse(F.details?.spatialPublication);return{code:(()=>{switch(F.code){case"authorization-required":case"cancelled":case"conflict":case"incompatible":case"invalid-data":case"subprocess":case"unavailable":case"unsupported-plan":case"ambiguous":case"internal":return F.code;case"not-found":case"unsafe-path":case"usage":return"invalid-data"}})(),message:V$1(F.message),retryable:_,...Q.success?{spatialPublication:Q.data}:{}}}function W$1($){let _=Object.entries($).sort(([F],[Q])=>F.localeCompare(Q));if(_.length>n51)throw new N("internal","Operation summary exceeds the scheduler field limit.");return Object.fromEntries(_.map(([F,Q])=>{if(F.length<1||F.length>r51)throw new N("internal","Operation summary contains an invalid field name.");if(typeof Q==="number"&&!Number.isFinite(Q))throw new N("internal","Operation summary contains a non-finite number.");if(typeof Q==="string"&&Q.length>o51)throw new N("internal","Operation summary contains an oversized string.");return[F,Q]}))}function Ad($,_,F,Q){let Z=L1.parse($),J=Rq(Z),X=J.bytes;if(X>F)throw new N("invalid-data",`Operation output uses ${String(X)} bytes; the limit is ${String(F)}.`);return{digestSha256:J.sha256,...Q===void 0?{}:{receiptReference:Q},summary:W$1(_),value:Z}}function N$1($){return["ambiguous","cancelled","failed","incompatible","skipped"].includes($.status)}function O$1($){return $.status==="pending"||$.status==="ready"||$.status==="preparing"||$.status==="approval-required"}class Oj0{#$;#_;#Q=new Set;#J;#Z=0;constructor($){this.#$=$.jobs,this.#_=$.resources,this.#J=Object.fromEntries(Yw.map((_)=>[_,0]))}impossible($){return $.some((_)=>_.amount>this.#_[_.resource])}acquire($,_){if(this.#Z>=this.#$)return!1;if(_.some((F)=>this.#Q.has(F)))return!1;if($.some((F)=>this.#J[F.resource]+F.amount>this.#_[F.resource]))return!1;this.#Z+=1;for(let F of $)this.#J[F.resource]+=F.amount;for(let F of _)this.#Q.add(F);return!0}release($,_){this.#Z-=1;for(let F of $)this.#J[F.resource]-=F.amount;for(let F of _)this.#Q.delete(F)}}function lq($,_){return{...$,hostResourceLease:{assertOwned:async()=>await _.assertOwned(),claims:_.claims,inheritedFileDescriptor:_.inheritedFileDescriptor,inheritedFileDescriptors:[_.inheritedFileDescriptor],profile:_.profile,ticket:_.ticket},runner:{run:async(F,Q={})=>{await _.assertOwned();let Z=[...Q.inheritedFileDescriptors??[],_.inheritedFileDescriptor].filter((J,X,Y)=>Y.indexOf(J)===X);if(Z.length>16)throw new N("incompatible","A workflow subprocess cannot inherit more than 16 file descriptors.");return await $.runner.run(F,{...Q,inheritedFileDescriptors:Z})}}}}function G$1($){if(!($ instanceof P2))return UY($);switch($.code){case"WAIT_ABORTED":return new N("cancelled",$.message);case"WAIT_TIMEOUT":return new N("unavailable",$.message);case"OWNERSHIP_LOST":return new N("conflict",$.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":return new N("incompatible",$.message);default:return $.code}}function Gj0($){return{cancelled:$.filter((_)=>_.status==="cancelled").length,completed:$.filter((_)=>_.status==="completed").length,failed:$.filter((_)=>_.status==="failed"||_.status==="incompatible"||_.status==="ambiguous").length,pending:$.filter((_)=>_.status==="pending"||_.status==="ready"||_.status==="preparing"||_.status==="running"||_.status==="approval-required"||_.status==="ambiguous-code").length,skipped:$.filter((_)=>_.status==="skipped").length}}function jj0($,_,F){if(_.pause!==void 0)return"approval-required";if($.some((Z)=>Z.status==="approval-required"))return"approval-required";if($.some((Z)=>Z.status==="ambiguous-code"))return"ambiguous-code";if(F>0||$.some((Z)=>Z.status==="running")||$.some(O$1))return"running";let Q=Gj0($);if(Q.cancelled>0)return"cancelled";if(Q.failed===0&&Q.skipped===0&&Q.completed===$.length)return"completed";if(_.cancelled)return"cancelled";if($.some((Z)=>Z.status==="incompatible")&&Q.completed===0)return"incompatible";if(Q.completed>0)return"partial";return"failed"}function dq($){return $==="cancelled"||$==="completed"||$==="failed"||$==="incompatible"||$==="partial"}function Td($,_){if(Wj0($)){let Q=_.get($.$ref.nodeKey);if(Q===void 0||Q.status!=="completed")return;return vL($,Ed(Q).value)}if(Q$1($)){let Q=[];for(let Z of $){let J=Td(Z,_);if(J===void 0)return;Q.push(J)}return Q}let F={};for(let[Q,Z]of Object.entries($).sort(([J],[X])=>J.localeCompare(X))){let J=Td(Z,_);if(J===void 0)return;F[Q]=J}return F}class Id{#$;#_;#Q;#J;#Z;#X;#H;#j;#Y;#V;#O;#M=new Set;#F;constructor($){if($.owner.length<1||$.owner.length>256)throw new N("usage","Scheduler owner must contain between 1 and 256 characters.");if($.authorization.grantedBy.length<1||$.authorization.grantedBy.length>256)throw new N("usage","Authorization owner must contain between 1 and 256 characters.");if(this.#$=$.application,this.#_=$.authorization,this.#Q=$.compute,this.#J=$.compute?.kind==="fresh"?$.compute.executor:void 0,$.currentApplicationBuild.length<1||$.currentApplicationBuild.length>160)throw new N("usage","Current application build must contain between 1 and 160 characters.");this.#Z=$.currentApplicationBuild,this.#X=$.hostResourceCoordinator,this.#H=$$1($),this.#j=$.nodePlanner,this.#Y=$.now??(()=>new Date),this.#V=$.owner,this.#O=$.registry,this.#F=$.store}async run($){let _=new Fd;try{return await _.run(this.#B($,_))}finally{await _.stop()}}#B($,_){return TK0(d1.gen(this,function*(){let F=yield*A1("authority",()=>this.#F.graphPlan($));if(F.graph.nodes.length>this.#H.maxNodes)return yield*d1.fail($3(new N("incompatible",`Workflow has ${String(F.graph.nodes.length)} nodes; the host limit is ${String(this.#H.maxNodes)}.`)));let Q=!0,Z=yield*_d(A1("admission",()=>this.#F.acquireClaim($,{owner:this.#V})),(L)=>Q?this.#G(L):d1.void),J;yield*_d(d1.void,()=>A1("cleanup",()=>J?.release()));let X=Jj0(YY.now(),this.#H.maxWallClockMs),H={cancelled:!1,monitorError:void 0,pause:void 0,reconciliationDeferred:!1,startedAt:(yield*A1("authority",()=>this.#w($))).startedAt??this.#Y().toISOString()},K=new Map,j=yield*kd.unbounded(),V=new Map,O=new Oj0(this.#H),W=new Vj0(_,X,(L)=>{if(L.kind==="monitor")H.monitorError=L.error;else H.cancelled=!0;if(L.kind!=="deadline"){for(let C of K.values())if(C.admissionAbortController.abort(),C.cancellable)C.abortController.abort()}}),G=_.watch(d1.forever(d1.gen(this,function*(){yield*d1.sleep(this.#H.cancellationPollMs);let L=yield*d1.either(A1("monitor",()=>this.#K($)));if(lL.isLeft(L))W.interrupt("monitor",UY(L.left.cause));else if(L.right!==void 0)W.interrupt("cancellation",new N("cancelled","Workflow cancellation requested."))}))),D=yield*d1.exit(d1.catchAll(d1.gen(this,function*(){yield*A1("authority",()=>this.#F.assertFence(Z)),yield*A1("authority",()=>this.#F.appendEvent(Z,{details:{status:"running"},kind:"run-status",timestamp:this.#Y().toISOString()}));let L=yield*d1.either(d1.gen(this,function*(){yield*A1("authority",()=>this.#q($,F)),J=yield*A1("authority",()=>this.#k(Z,F,H,W))}));if(lL.isLeft(L)){let C=L.left.cause,B=UY(C);if(B.code!=="incompatible"&&B.code!=="unsupported-plan")return yield*d1.fail($3(C));yield*A1("authority",()=>this.#g(Z,F,H,B));let z=yield*A1("authority",()=>this.#T(Z,F,H,0));return yield*A1("authority",()=>this.#F.appendEvent(Z,{details:{status:z.status},kind:"run-finalized",timestamp:this.#Y().toISOString()})),yield*A1("authority",()=>this.#F.releaseClaim(Z)),Q=!1,{summary:z}}if(yield*A1("authority",()=>this.#D(Z,F,H,W)),yield*A1("authority",()=>this.#T(Z,F,H,K.size)),H.reconciliationDeferred){let C=yield*A1("authority",()=>this.#T(Z,F,H,0));return yield*A1("authority",()=>this.#F.appendEvent(Z,{details:{status:C.status},kind:"run-status",timestamp:this.#Y().toISOString()})),yield*A1("authority",()=>this.#F.releaseClaim(Z)),Q=!1,{summary:C}}while(!0){if(H.monitorError!==void 0)return yield*d1.fail($3(H.monitorError));if(yield*A1("authority",()=>this.#F.assertFence(Z)),(yield*A1("authority",()=>this.#K($)))!==void 0){H.cancelled=!0;for(let U of K.values())if(U.admissionAbortController.abort(),U.cancellable)U.abortController.abort()}if(YY.now()>=X){H.cancelled=!0;for(let U of K.values())if(U.admissionAbortController.abort(),U.cancellable)U.abortController.abort()}if(yield*A1("authority",()=>this.#A(Z,F,H)),H.cancelled)yield*A1("authority",()=>this.#I(Z,F));else if(H.pause===void 0){if(yield*A1("authority",()=>this.#R(Z,F,H,W,V)),H.pause===void 0){if(yield*A1("authority",()=>this.#C(Z,V,K,O,X,W,_,j)),H.cancelled)yield*A1("authority",()=>this.#I(Z,F))}}if(K.size>0){let U=yield*kd.take(j),k=K.get(U.nodeKey);if(k===void 0)continue;let A={item:k,outcome:yield*U.outcome};K.delete(A.item.nodeKey),O.release(A.item.resources,A.item.publicationKeys);let q=yield*A1("authority",()=>this.#S(Z,F,A.item,A.outcome,W));if(yield*A1("authority",()=>this.#T(Z,F,H,K.size)),q){H.reconciliationDeferred=!0;let E=yield*A1("authority",()=>this.#T(Z,F,H,K.size));return yield*A1("authority",()=>this.#F.appendEvent(Z,{details:{status:E.status},kind:"run-status",timestamp:this.#Y().toISOString()})),yield*A1("authority",()=>this.#F.releaseClaim(Z)),Q=!1,{summary:E}}continue}let C=yield*A1("authority",()=>this.#F.nodes($));if(jj0(C,H,0)==="running"){if(yield*A1("authority",()=>this.#b(Z,F,O)))continue;return yield*d1.fail($3(new N("internal","Workflow scheduler reached a nonterminal state without runnable work.")))}let z=yield*A1("authority",()=>this.#T(Z,F,H,0));return yield*A1("authority",()=>this.#F.appendEvent(Z,{details:{status:z.status},kind:dq(z.status)?"run-finalized":"run-status",timestamp:this.#Y().toISOString()})),yield*A1("authority",()=>this.#F.releaseClaim(Z)),Q=!1,{...H.pause===void 0?{}:{pause:H.pause},summary:z}}}),(L)=>d1.gen(this,function*(){let C=L.cause;if(Q&&(W.interruption?.kind==="cancellation"||W.interruption?.kind==="deadline")){let B=[...K.values()].sort((U,k)=>U.nodeKey.localeCompare(k.nodeKey));if(B.length>0){let U=yield*d1.forEach(B,(k)=>d1.flatMap(s51.join(k.fiber),(A)=>d1.map(A,(q)=>({item:k,outcome:q}))),{concurrency:"unbounded"});K.clear();for(let k of U){O.release(k.item.resources,k.item.publicationKeys);let A=yield*A1("authority",()=>this.#S(Z,F,k.item,k.outcome,W));H.reconciliationDeferred||=A}}yield*A1("authority",()=>this.#I(Z,F));let z=yield*A1("authority",()=>this.#T(Z,F,H,K.size));return yield*A1("authority",()=>this.#F.appendEvent(Z,{details:{status:z.status},kind:dq(z.status)?"run-finalized":"run-status",timestamp:this.#Y().toISOString()})),yield*A1("authority",()=>this.#F.releaseClaim(Z)),Q=!1,{summary:z}}if(Q){let B=UY(C);if(B.code!=="conflict")yield*A1("authority",()=>this.#y(Z,F,H,B).catch(()=>{return}))}return yield*d1.fail($3(C))}))),w=yield*d1.exit(d1.gen(this,function*(){yield*A1("authority",()=>G()),yield*A1("authority",()=>W.stop())}));return yield*Zj0.zipLeft(D,w)}))}#G($){return d1.gen(this,function*(){let _=yield*d1.either(A1("cleanup",()=>this.#F.assertFence($)));if(lL.isLeft(_)){if(_.left.cause instanceof N&&_.left.cause.code==="conflict")return;return yield*d1.fail(_.left)}let F=yield*d1.either(A1("cleanup",()=>this.#F.releaseClaim($)));if(lL.isRight(F))return;if(F.left.cause instanceof N&&F.left.cause.code==="conflict"){let Q=yield*d1.either(A1("cleanup",()=>this.#F.assertFence($)));if(lL.isLeft(Q)&&Q.left.cause instanceof N&&Q.left.cause.code==="conflict")return}return yield*d1.fail(F.left)})}async#w($){return await this.#F.summary($)}async#K($){let _;for(let F=0;F<4;F+=1)try{return await this.#F.cancellation($)}catch(Q){let Z=UY(Q);if(Z.code!=="conflict")throw Q;_=Z,await Promise.resolve()}throw _??new N("conflict",`Could not read a stable cancellation marker for ${$}.`)}async#N($,_){if(_.assertActive(),await _.race(async()=>await this.#K($.runId))!==void 0)_.interrupt("cancellation",new N("cancelled","Workflow cancellation requested.")),_.assertActive()}async#L($,_,F){await this.#N($,_);let Q=await _.race(F);return _.assertActive(),Q}async#q($,_){if(_.runtime.applicationBuild!==this.#Z)throw new N("incompatible","Persisted workflow application build differs from the current host build.");let F=await this.#F.runtime($);if(R(F.runtime)!==R(_.runtime))throw new N("incompatible","Persisted workflow runtime identity changed.");let Q=[...new Set(_.graph.nodes.filter(M4).map((X)=>`${X.executor.operation.kind}@${String(X.executor.operation.version)}`))].sort((X,Y)=>X.localeCompare(Y)),Z=F.operations.map((X)=>`${X.kind}@${String(X.version)}`).sort((X,Y)=>X.localeCompare(Y));if(R(Q)!==R(Z))throw new N("incompatible","Persisted operation runtime set changed.");let J=[...new Map(_.graph.nodes.filter(F8).map((X)=>[X.executor.compute.key,X.executor.compute])).values()].sort((X,Y)=>X.key.localeCompare(Y.key));if(R(J)!==R(F.computes))throw new N("incompatible","Persisted compute runtime set changed.");for(let X of _.graph.nodes)if(M4(X))cL(_,X,this.#O)}async#k($,_,F,Q){let Z=this.#Q;if(Z===void 0)return;if(Z.kind==="fresh"){if(Z.executor.bundleSha256!==_.bundle.bundleSha256)throw new N("incompatible","Fresh code worker bundle does not match the persisted graph plan.");this.#J=Z.executor;return}let J=[...new Set(Z.nodeKeys.map((O)=>m4.parse(O)))].sort((O,W)=>O.localeCompare(W));if(J.length===0)throw new N("usage","A compute replay requires at least one exact node key.");if(await this.#K($.runId)!==void 0){F.cancelled=!0;return}let X=await this.#F.nodes($.runId),Y=new Map(_.graph.nodes.map((O)=>[O.key,O])),H=[];for(let O of J){let W=Y.get(O),G=X.find((D)=>D.nodeKey===O);if(W===void 0||!F8(W)||G?.status!=="ambiguous-code"||G.executionPlan===void 0)throw new N("conflict",`Compute node is not awaiting exact replay: ${O}`);H.push({attempt:G.attempt+1,bundleSha256:_.bundle.bundleSha256,computeKey:W.executor.compute.key,createdAt:this.#Y().toISOString(),graphPlanSha256:_.graphPlanSha256,grantedBy:this.#_.grantedBy,grantId:Md(),kind:"compute-replay",nodeKey:O,nodePlanSha256:G.executionPlan.nodePlanSha256})}for(let O of H){if(await this.#K($.runId)!==void 0){F.cancelled=!0;return}await this.#F.appendGrant($,O)}if(await this.#K($.runId)!==void 0){F.cancelled=!0;return}await this.#N($,Q);let K=Q.deadlineMonotonicMs-YY.now();if(K<=0)Q.interrupt("deadline",new N("cancelled","Workflow exceeded the host wall-clock bound.")),Q.assertActive();let j=Z.load({signal:Q.signal,waitTimeoutMilliseconds:Math.min(A6,Math.max(1,Math.ceil(K)))}),V;try{V=await Q.race(async()=>await j)}catch(O){throw j.then(async(W)=>await W.release(),()=>{return}).catch(()=>{return}),O}try{if(Q.assertActive(),V.executor.bundleSha256!==_.bundle.bundleSha256)throw new N("incompatible","Replay code worker bundle does not match the persisted graph plan.");this.#J=V.executor;for(let O of J)this.#M.add(O);for(let O of J)await this.#F.reopenComputeNode($,O);return V}catch(O){throw await V.release().catch(()=>{return}),O}}async#D($,_,F,Q){let Z=await this.#F.nodes($.runId),J=new Map(Z.map((X)=>[X.nodeKey,X]));for(let X of[..._.graph.nodes].sort((Y,H)=>Y.key.localeCompare(H.key))){let Y=J.get(X.key);if(Y===void 0)throw new N("invalid-data",`Run is missing node ${X.key}.`);if(Y.status==="completed"){Ed(Y),await this.#F.appendEvent($,{details:{digestSha256:Y.output?.digestSha256??""},kind:"node-reused",nodeKey:X.key,timestamp:this.#Y().toISOString()});continue}if(Y.status==="approval-required")continue;if(Y.status==="preparing"){await this.#W($,{...Y,status:"ready"});continue}if(Y.status!=="running")continue;if(F8(X)){await this.#W($,{...Y,failure:t8(new N("ambiguous","Interrupted trusted compute requires an explicit exact-bundle replay.")),finishedAt:this.#Y().toISOString(),status:"ambiguous-code"});continue}if(!M4(X))throw new N("internal",`Unknown node executor for ${X.key}.`);let H=cL(_,X,this.#O).discovery.policy.resume;if(H==="deterministic"){await this.#W($,{...Y,failure:void 0,finishedAt:void 0,status:"ready"});continue}let K=await this.#z($,_,X,Y,J,Q);if(K.deferred){if(F.reconciliationDeferred=!0,Q.interruption!==void 0)break;continue}if(K.reconciliation?.kind==="ambiguous"&&H==="non-resumable-live")F.cancelled=!1}}async#z($,_,F,Q,Z,J){let X=cL(_,F,this.#O),Y=Xj0(F,Z),H=X.discovery.policy.resume;await this.#F.assertFence($);let K=Q.executionPlan===void 0?void 0:await this.#F.stagingDirectory($,F.key,Q.executionPlan.nodePlanSha256),j;try{let V=this.#j.reconcile,O=this.#j.reconcileEffect;j=V===void 0&&O===void 0?void 0:await this.#L($,J,async()=>{let W=async()=>await this.#X.withLease(rQ(X.discovery.policy.resources,this.#X),async(G)=>{await G.assertOwned();let D=async()=>{if(await G.assertOwned(),J.assertActive(),J.signal.aborted)throw new N("cancelled","Workflow reconciliation was cancelled before publication.");await this.#F.assertFence($),await this.#N($,J),await this.#F.assertFence($),J.assertActive(),await G.assertOwned()},w={abortSignal:J.signal,application:lq(this.#$,G),beforePublication:D,dependencyOutputs:Y.dependencyOutputs,executionPlan:Q.executionPlan,graphPlan:_,node:F,operation:X.discovery,preparationPlan:Q.preparationPlan,previous:Q,resolvedInput:Y.input,resumeClass:H,runId:$.runId,...K===void 0?{}:{workspaceDirectory:K}};return O===void 0?await V.call(this.#j,w):await J.runNative(O.call(this.#j,w))},{signal:J.signal,waitTimeoutMilliseconds:A6});return O===void 0?await W():await J.custody(A1("authority",W))})}catch{return await this.#F.assertFence($),{deferred:!0,reconciliation:void 0}}return await this.#F.assertFence($),await this.#P($,Q,X,H,j),{deferred:!1,reconciliation:j}}async#P($,_,F,Q,Z){if(Z?.kind==="completed"){let H=Ad(Z.output,Z.summary,F.discovery.policy.maxOutputBytes,Z.receiptReference);await this.#W($,{..._,failure:void 0,finishedAt:this.#Y().toISOString(),output:H,status:"completed"});return}let J=Q==="verified-receipt"||Q==="recoverable-transaction";if(Z?.kind==="retry"&&J){await this.#W($,{..._,failure:void 0,finishedAt:void 0,status:"ready"});return}if(Z?.kind==="incompatible"){await this.#W($,{..._,failure:t8(new N("incompatible",Z.message)),finishedAt:this.#Y().toISOString(),status:"incompatible"});return}let X=Z?.kind==="ambiguous"?Z.message:Q==="non-resumable-live"?"Interrupted live operation requires explicit operator reconciliation.":Q==="ambiguous-after-dispatch"?"Interrupted paid operation has an ambiguous dispatch outcome.":"Interrupted operation has no compatible reconciliation implementation.",Y=Q==="verified-receipt"||Q==="recoverable-transaction"?"incompatible":"ambiguous";await this.#W($,{..._,failure:t8(new N(Y==="incompatible"?"incompatible":"ambiguous",X)),finishedAt:this.#Y().toISOString(),status:Y})}async#A($,_,F){let Q=!0;while(Q){Q=!1;let Z=await this.#F.nodes($.runId),J=new Map(Z.map((X)=>[X.nodeKey,X]));for(let X of[..._.graph.nodes].sort((Y,H)=>Y.key.localeCompare(H.key))){let Y=J.get(X.key);if(Y===void 0||Y.status!=="pending")continue;let H=X.dependencies.map((K)=>J.get(K));if(H.some((K)=>K===void 0))throw new N("invalid-data",`Node ${X.key} has a missing dependency.`);if(H.some((K)=>K!==void 0&&N$1(K))){let K={...Y,finishedAt:this.#Y().toISOString(),status:F.cancelled?"cancelled":"skipped"};await this.#W($,K),J.set(X.key,K),Q=!0;continue}if(H.every((K)=>K?.status==="completed")){let K={...Y,status:"ready"};await this.#W($,K),J.set(X.key,K),Q=!0}}}}async#R($,_,F,Q,Z){let J=await this.#F.nodes($.runId),X=new Map(J.map((H)=>[H.nodeKey,H])),Y=new Map(_.graph.nodes.map((H)=>[H.key,H]));for(let H of J.filter((K)=>K.status==="ready"||K.status==="approval-required").sort((K,j)=>K.nodeKey.localeCompare(j.nodeKey))){if(F.pause!==void 0||F.cancelled)break;if(Z.has(H.nodeKey))continue;await this.#N($,Q);let K=Y.get(H.nodeKey);if(K===void 0)throw new N("invalid-data",`Run contains unknown node ${H.nodeKey}.`);let j=Hj0(_,K,this.#O),V=Xj0(K,X),O;if(j.kind==="operation"){if(!M4(K))throw new N("internal",`Node executor classification changed for ${K.key}.`);O={dependencyOutputs:V.dependencyOutputs,graphPlan:_,node:K,operation:j.operation.discovery,resolvedInput:V.input,runId:$.runId}}let W=H.preparationPlan;if(W===void 0){await this.#W($,{...H,status:"preparing"}),await this.#F.assertFence($);let C=O===void 0?Z$1(V):await this.#L($,Q,async()=>await this.#j.prepare(O));W=J$1(_,K,j.policy,C)}else Y$1(W,_,K,j.policy);if(!await this.#U($,_,K,j,W,Q)){let C=Z_.parse({...H,preparationPlan:W,status:"approval-required",version:$Y});await this.#W($,C),F.pause={nodeKey:K.key,phase:"preparation",planSha256:W.preparationPlanSha256},await this.#F.appendEvent($,{details:{phase:"preparation",planSha256:W.preparationPlanSha256},kind:"approval-required",nodeKey:K.key,timestamp:this.#Y().toISOString()});break}let D=H.executionPlan;if(D===void 0){await this.#F.assertFence($);let C=O===void 0?{exactInput:V.input,publicationKeys:[]}:await this.#L($,Q,async()=>{if(O.operation.kind!=="slopcamera.studio.run")return await this.#j.plan({...O,preparationPlan:W});return await this.#X.withLease(rQ(O.operation.policy.resources,this.#X),async(B)=>{let z=async()=>{await B.assertOwned(),await this.#F.assertFence($),await this.#N($,Q),await this.#F.assertFence($),await B.assertOwned()};return await z(),await this.#j.plan({...O,preparationPlan:W,application:lq(this.#$,B),abortSignal:Q.signal,beforePublication:z})},{signal:Q.signal})});D=X$1(_,K,j.policy,W,V,C)}else H$1(D,_,K,j.policy,W,V);if(!await this.#E($,_,K,j,D,Q)){let C=Z_.parse({...H,executionPlan:D,preparationPlan:W,status:"approval-required",version:$Y});await this.#W($,C),F.pause={nodeKey:K.key,phase:"effect",planSha256:D.nodePlanSha256},await this.#F.appendEvent($,{details:{phase:"effect",planSha256:D.nodePlanSha256},kind:"approval-required",nodeKey:K.key,timestamp:this.#Y().toISOString()});break}let L=Z_.parse({...H,executionPlan:D,failure:void 0,preparationPlan:W,status:"ready",version:$Y});if(H.status!=="ready"||H.preparationPlan===void 0||H.executionPlan===void 0||H.failure!==void 0)await this.#W($,L);X.set(K.key,L),Z.set(K.key,{executionPlan:D,executor:j,record:L,resolved:V})}}async#U($,_,F,Q,Z,J){if(Z.requestedPreparation.length===0)return!0;let X=await this.#F.grants($.runId);if(K$1(X,_.graphPlanSha256,Z.nodeKey,Z.preparationPlanSha256))return!0;if(!Kj0(await this.#L($,J,async()=>await this.#_.authorizePreparation({executor:F.executor,graphPlanSha256:_.graphPlanSha256,nodeKey:Z.nodeKey,...Q.kind==="operation"?{operation:Q.operation.discovery}:{},policy:Q.policy,preparationPlan:Z,runId:$.runId}))))return!1;let H={createdAt:this.#Y().toISOString(),graphPlanSha256:_.graphPlanSha256,grantedBy:this.#_.grantedBy,grantId:Md(),kind:"preparation",nodeKey:Z.nodeKey,preparationPlanSha256:Z.preparationPlanSha256};return await this.#N($,J),await this.#F.appendGrant($,H),!0}async#E($,_,F,Q,Z,J){if(Q.kind==="operation"&&Q.operation.discovery.kind==="slopcamera.studio.run"){let K=this.#$.studioAuthorization;if(K===void 0||!await this.#L($,J,async()=>await K.authorize(zm(Z.exactInput))))return!1}let X=await this.#F.grants($.runId);if(j$1(X,_.graphPlanSha256,Z.nodeKey,Z.nodePlanSha256))return!0;if(!Kj0(await this.#L($,J,async()=>await this.#_.authorizeEffect({executor:F.executor,executionPlan:Z,graphPlanSha256:_.graphPlanSha256,nodeKey:Z.nodeKey,...Q.kind==="operation"?{operation:Q.operation.discovery}:{},policy:Q.policy,runId:$.runId}))))return!1;let H={createdAt:this.#Y().toISOString(),graphPlanSha256:_.graphPlanSha256,grantedBy:this.#_.grantedBy,grantId:Md(),kind:"effect",nodeKey:Z.nodeKey,nodePlanSha256:Z.nodePlanSha256};return await this.#N($,J),await this.#F.appendGrant($,H),!0}async#C($,_,F,Q,Z,J,X,Y){for(let H of[..._.values()].sort((K,j)=>K.record.nodeKey.localeCompare(j.record.nodeKey))){if(YY.now()>=Z){J.interrupt("deadline",new N("cancelled","Workflow exceeded the host wall-clock bound."));break}let K=H.executor.policy.resources;if(Q.impossible(K)){await this.#W($,{...H.record,failure:t8(new N("incompatible",`Node ${H.record.nodeKey} exceeds the host resource ceiling.`)),finishedAt:this.#Y().toISOString(),status:"incompatible"}),_.delete(H.record.nodeKey);continue}if(!Q.acquire(K,H.executionPlan.publicationKeys))continue;try{if(await this.#F.assertFence($),await this.#K($.runId)!==void 0){Q.release(K,H.executionPlan.publicationKeys),J.interrupt("cancellation",new N("cancelled","Workflow cancellation requested."));break}let j=new AbortController,V=new AbortController,O=Z_.parse({...H.record,attempt:H.record.attempt+1,startedAt:this.#Y().toISOString(),status:"running",version:$Y});await this.#W($,O),_.delete(H.record.nodeKey);let W={admissionAbortController:j,abortController:V,cancellable:H.executor.policy.cancellable,executionPlan:H.executionPlan,nodeKey:H.record.nodeKey,fiber:X.fork(d1.exit(this.#f($,H,j,V,Z,X)).pipe(d1.tap((G)=>kd.offer(Y,{nodeKey:H.record.nodeKey,outcome:G})))),publicationKeys:H.executionPlan.publicationKeys,resources:K};F.set(H.record.nodeKey,W)}catch(j){throw Q.release(K,H.executionPlan.publicationKeys),j}}}#f($,_,F,Q,Z,J){return d1.gen(this,function*(){let X=!1,Y,H=!1,K=!1,j=Jj0(YY.now(),_.executor.policy.maxDurationMs),V=Math.min(j,Z),O=Z<=j?"workflow":"node",W=J.deferred(),G=()=>new N("unavailable",O==="workflow"?"Workflow exceeded the host wall-clock bound.":"Operation exceeded its registered duration bound."),D=J.watch(d1.zipRight(qd(V),d1.sync(()=>{if(X=!0,Y=O,cq.unsafeDone(W,d1.fail($3(G(),"admission"))),F.abort(),_.executor.policy.cancellable)Q.abort()})),!0),w=async(z)=>{if(X)throw G();return await J.run(d1.raceFirst(A1("authority",z),cq.await(W)))},L=()=>{if(X)throw new N("cancelled","Workflow node deadline expired before publication.")},C=yield*d1.exit(d1.catchAll(d1.gen(this,function*(){if(yield*A1("operation",()=>w(async()=>await this.#F.assertFence($))),(yield*A1("operation",()=>w(async()=>await this.#K($.runId))))!==void 0)return yield*d1.fail($3(new N("cancelled","Workflow cancellation requested."),"operation"));if(_.executor.policy.effect==="paid-cloud"||_.executionPlan.publicationKeys.length>0){if(yield*A1("operation",()=>w(async()=>await this.#F.assertFence($))),(yield*A1("operation",()=>w(async()=>await this.#K($.runId))))!==void 0)return yield*d1.fail($3(new N("cancelled","Workflow cancellation requested before dispatch or publication."),"operation"))}let z=this.#$,U=async(E,M=z)=>{if(_.executor.kind!=="operation")throw new N("internal",`Compute node ${_.record.nodeKey} entered operation execution.`);if(await w(async()=>await this.#F.assertFence($)),await w(async()=>await this.#F.cancellation($.runId))!==void 0)throw new N("cancelled","Workflow cancellation requested before project publication.");let T=await w(async()=>await this.#F.stagingDirectory($,_.record.nodeKey,_.executionPlan.nodePlanSha256));await E.assertOwned();let P=lq(M,E),I=_.executor.operation,g={abortSignal:Q.signal,application:P,..._.executionPlan.expectedProjectGeneration===void 0?{}:{expectedProjectGeneration:_.executionPlan.expectedProjectGeneration},runFence:{generation:$.generation,owner:$.owner,token:$.token},workflow:{beforePublication:async()=>{if(L(),await E.assertOwned(),await w(async()=>await this.#F.assertFence($)),L(),await w(async()=>await this.#K($.runId))!==void 0)throw new N("cancelled","Workflow cancellation requested before publication.");L(),H=!0},nodeKey:_.record.nodeKey,nodePlanSha256:_.executionPlan.nodePlanSha256,runId:$.runId,workspaceDirectory:T}},b=I.executeEffect===void 0?await I.execute(g,_.executionPlan.exactInput):kO(await J.run(d1.exit(I.executeEffect(g,_.executionPlan.exactInput))));if(I.discovery.kind.startsWith("spatial.project.")&&I.discovery.kind!=="spatial.project.snapshot"){let y=b.output;if(y.kind!=="completed")throw new N(y.kind==="ambiguous"?"ambiguous":"conflict",y.message??"Spatial publication did not complete.",{spatialPublication:b.output})}return b},k=rQ(_.executor.policy.resources,this.#X),A={signal:F.signal,waitTimeoutMilliseconds:Math.min(A6,Math.max(1,Math.floor(V-YY.now())))},q;if(_.executor.kind==="compute"){let E=_.executor.compute,M=this.#J,T=this.#Q?.kind!=="replay"||this.#M.has(_.record.nodeKey);if(M===void 0||!T)return{failure:t8(new N("ambiguous","Trusted compute requires explicit authorization to reload its exact persisted bundle.")),kind:"ambiguous-code"};let P=J.custody(A1("admission",()=>this.#X.withLease(k,async(g)=>{return await g.assertOwned(),K=!0,await M.execute({abortSignal:Q.signal,computeKey:E.key,...g.inheritedFileDescriptor<3?{}:{inheritedHostResourceFileDescriptor:g.inheritedFileDescriptor},input:_.executionPlan.exactInput,nodeKey:_.record.nodeKey,replayAcknowledged:this.#Q?.kind==="replay",timeoutMs:Math.max(1,Math.floor(V-YY.now()))})},A))),I=yield*A1("operation",()=>w(async()=>await P));yield*A1("operation",()=>w(async()=>await this.#F.assertFence($))),q=yield*XN("operation",()=>Ad(I,{computeKey:E.key,trustedCode:!0},_.executor.policy.maxOutputBytes))}else{let E=_.executor.operation,M=_.executionPlan.publicationKeys.some((I)=>I.startsWith("project:")),T=J.custody(A1("admission",()=>this.#X.withLease(k,async(I)=>E.discovery.kind.startsWith("spatial.project.")?await fK(lq(this.#$,I),String(_.executionPlan.exactInput.project),async(g)=>await U(I,g),async()=>{if(L(),await I.assertOwned(),Q.signal.aborted)throw new N("cancelled","Spatial project custody was cancelled before publication.");if(await w(async()=>await this.#F.assertFence($)),await w(async()=>await this.#K($.runId))!==void 0)throw new N("cancelled","Workflow cancellation requested before spatial publication.");if(L(),Q.signal.aborted)throw new N("cancelled","Spatial project custody was cancelled before publication.");await I.assertOwned()},E.discovery.kind==="spatial.project.migrate"?"mutation":"read"):M?await m7(this.#$,E.discovery.kind,_.executionPlan.exactInput,async()=>await U(I)):await U(I),A))),P=yield*A1("operation",()=>w(async()=>await T));yield*A1("operation",()=>w(async()=>await this.#F.assertFence($))),q=yield*XN("operation",()=>Ad(P.output,P.summary.fields,_.executor.policy.maxOutputBytes,P.receiptReference))}return{kind:"completed",output:q}}),(z)=>XN("operation",()=>{let U=z.cause,k=G$1(U);if(_.executor.kind==="compute"){if(k.code==="cancelled"&&!K)return{failure:t8(new N("cancelled","Workflow node was cancelled.")),kind:"cancelled"};if(k.code==="invalid-data"||k.code==="unsupported-plan"||k.code==="incompatible")return{failure:t8(k),kind:"failed"};return{failure:t8(new N("ambiguous",X?Y==="workflow"?"Trusted compute exceeded the workflow wall-clock bound and requires explicit replay.":"Trusted compute exceeded its duration bound and requires explicit replay.":`Trusted compute was interrupted and requires explicit replay: ${k.message}`)),kind:"ambiguous-code"}}let A=k.details?.spatialPublication;if(_.executor.operation.discovery.kind.startsWith("spatial.project.")&&A!==void 0){let E=W8.safeParse(A);if(E.success&&E.data.kind!=="completed")return{failure:t8(k),kind:E.data.kind==="ambiguous"?"ambiguous":"failed"}}if(H&&(_.executor.policy.resume==="verified-receipt"||_.executor.policy.resume==="recoverable-transaction"))return{failure:t8(new N("ambiguous",X?Y==="workflow"?"Recoverable publication exceeded the workflow wall-clock bound.":"Recoverable publication exceeded its duration bound.":`Recoverable publication requires reconciliation: ${k.message}`,k.details)),kind:"interrupted"};if(k.code==="cancelled"||Q.signal.aborted&&!X)return{failure:t8(new N("cancelled","Workflow node was cancelled.")),kind:"cancelled"};if(_.executor.policy.resume==="ambiguous-after-dispatch"||_.executor.policy.resume==="non-resumable-live")return{failure:t8(new N("ambiguous",X?Y==="workflow"?"Operation exceeded the workflow wall-clock bound after dispatch.":"Operation exceeded its duration bound after dispatch.":k.message,k.details)),kind:"ambiguous"};return{failure:t8(X?new N("unavailable",Y==="workflow"?"Operation exceeded the workflow wall-clock bound.":"Operation exceeded its registered duration bound."):k,k.code==="unavailable"||k.code==="subprocess"),kind:"failed"}}))),B=yield*d1.exit(d1.gen(this,function*(){yield*A1("operation",()=>D())}));return yield*Zj0.zipLeft(C,B)})}async#S($,_,F,Q,Z){await this.#F.assertFence($);let J=await this.#F.node($.runId,F.nodeKey);if(Q.kind==="completed")return await this.#W($,{...J,failure:void 0,finishedAt:this.#Y().toISOString(),output:Q.output,status:"completed"}),!1;if(Q.kind==="interrupted"){let X=_.graph.nodes.find((j)=>j.key===F.nodeKey);if(X===void 0||!M4(X))throw new N("invalid-data",`Missing recoverable operation node ${F.nodeKey}.`);let Y=await this.#F.nodes($.runId),H=new Map(Y.map((j)=>[j.nodeKey,j]));return(await this.#z($,_,X,J,H,Z)).deferred}if(await this.#W($,{...J,failure:Q.failure,finishedAt:this.#Y().toISOString(),status:Q.kind}),Q.kind==="ambiguous"){if(_.graph.nodes.find((Y)=>Y.key===F.nodeKey)===void 0)throw new N("invalid-data",`Missing graph node ${F.nodeKey}.`)}return!1}async#I($,_){let F=await this.#F.nodes($.runId),Q=new Set(_.graph.nodes.map((Z)=>Z.key));for(let Z of F.filter((J)=>J.status==="pending"||J.status==="ready"||J.status==="preparing"||J.status==="approval-required"||J.status==="ambiguous-code").sort((J,X)=>J.nodeKey.localeCompare(X.nodeKey))){if(!Q.has(Z.nodeKey))continue;await this.#W($,{...Z,finishedAt:this.#Y().toISOString(),status:"cancelled"})}}async#b($,_,F){let Q=await this.#F.nodes($.runId),Z=new Map(_.graph.nodes.map((X)=>[X.key,X])),J=!1;for(let X of Q.filter((Y)=>Y.status==="ready").sort((Y,H)=>Y.nodeKey.localeCompare(H.nodeKey))){let Y=Z.get(X.nodeKey);if(Y===void 0)continue;let H=Hj0(_,Y,this.#O);if(!F.impossible(H.policy.resources))continue;await this.#W($,{...X,failure:t8(new N("incompatible",`Node ${Y.key} exceeds the host resource ceiling.`)),finishedAt:this.#Y().toISOString(),status:"incompatible"}),J=!0}return J}async#W($,_){let F=Z_.parse(_),Q=Z_.parse({attempt:F.attempt,dependencies:F.dependencies,...F.executionPlan===void 0?{}:{executionPlan:F.executionPlan},...F.failure===void 0?{}:{failure:F.failure},...F.finishedAt===void 0?{}:{finishedAt:F.finishedAt},executor:F.executor,nodeKey:F.nodeKey,...F.output===void 0?{}:{output:F.output},...F.preparationPlan===void 0?{}:{preparationPlan:F.preparationPlan},...F.startedAt===void 0?{}:{startedAt:F.startedAt},status:F.status,version:F.version});await this.#F.assertFence($),await this.#F.writeNode($,Q),await this.#F.appendEvent($,{details:{status:Q.status},kind:"node-status",nodeKey:Q.nodeKey,timestamp:this.#Y().toISOString()})}async#T($,_,F,Q){let Z=await this.#F.summary($.runId);if(dq(Z.status))return Z;let J=await this.#F.nodes($.runId),X=new Map(J.map((V)=>[V.nodeKey,V])),Y=jj0(J,F,Q),H=this.#Y().toISOString(),K=Y==="completed"?Td(_.graph.outputs,X):void 0,j=hZ.parse({counts:Gj0(J),...dq(Y)?{finishedAt:H}:{},graphPlanSha256:_.graphPlanSha256,...K===void 0?{}:{outputs:K},runId:$.runId,startedAt:F.startedAt,status:Y,updatedAt:H,version:F_});return await this.#F.writeSummary($,j),j}async#y($,_,F,Q){let J=(await this.#F.nodes($.runId)).filter((X)=>X.status==="ready"||X.status==="preparing"||X.status==="running").sort((X,Y)=>X.nodeKey.localeCompare(Y.nodeKey))[0];if(J!==void 0){let X=_.graph.nodes.find((K)=>K.key===J.nodeKey),Y=X!==void 0&&M4(X)?cL(_,X,this.#O).discovery.policy.resume:void 0;if(J.status==="running"&&(Y==="verified-receipt"||Y==="recoverable-transaction")){await this.#T($,_,F,0);return}await this.#W($,{...J,failure:t8(Q),finishedAt:this.#Y().toISOString(),status:Q.code==="incompatible"?"incompatible":"failed"})}await this.#T($,_,F,0)}async#g($,_,F,Q){let Z=await this.#F.nodes($.runId);for(let J of[...Z].sort((X,Y)=>X.nodeKey.localeCompare(Y.nodeKey))){if(J.status==="approval-required")await this.#W($,{...J,status:"ready"});let X=J.status==="approval-required"?await this.#F.node($.runId,J.nodeKey):J;if(X.status!=="ready"&&X.status!=="preparing"&&X.status!=="running"&&X.status!=="ambiguous-code")continue;await this.#W($,{...X,failure:t8(new N("incompatible",Q.message)),finishedAt:this.#Y().toISOString(),status:"incompatible"})}await this.#A($,_,F)}}var D$1="workflow-runs",L$1=100;async function wj0($,_,F={}){try{return await $.withLease(uW($),async(Q)=>{return await Q.assertOwned(),await _(Q)},{...F.signal===void 0?{}:{signal:F.signal},waitTimeoutMilliseconds:F.waitTimeoutMilliseconds??A6})}catch(Q){if(!(Q instanceof P2))throw Q;switch(Q.code){case"WAIT_ABORTED":throw new N("cancelled",Q.message);case"OWNERSHIP_LOST":throw new N("conflict",Q.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":case"WAIT_TIMEOUT":throw new N("unavailable",Q.message,{hostResourceCode:Q.code})}}}async function C$1($){let[_,F]=await Promise.all([$.store.graphPlan($.runId),$.store.bundle($.runId)]);if(_.runtime.externals.kind==="deny-all"&&_.runtime.externals.modules.length!==0)throw new N("incompatible","A deny-all trusted-code runtime cannot contain external modules.");let Q=yH0({bundle:_.bundle,bytes:F,externalModules:_.runtime.externals.modules}),Z=await TL({applicationBuild:$.currentApplicationBuild,bundle:Q});if(R(Z)!==R(_.runtime))throw new N("incompatible","The trusted-code runtime changed since this run was planned.",{current:Z,planned:_.runtime});let J=tX({bundle:_.bundle,graph:_.graph,limits:_.limits,registry:$.registry,runtime:Z,staticBindings:_.staticBindings,workflowInput:_.workflowInput});if(R(J)!==R(_))throw new N("incompatible","Persisted trusted code no longer compiles to the exact authorized graph plan.");return await wq({bundle:Q,expectedBuild:{graph:_.graph,input:_.workflowInput},...$.inheritedHostResourceFileDescriptor===void 0?{}:{inheritedHostResourceFileDescriptor:$.inheritedHostResourceFileDescriptor},maximumWorkers:$.maximumWorkers,registry:$.registry,temporaryRoot:$.application.paths.privateRoot,workflowInput:_.workflowInput,workflowInputMode:"parsed"})}function Dj0(){return`slopcamera-cli:${String(process.pid)}:${bd()}`}function B$1(){return`run_${bd().replaceAll("-","")}`}function z$1($){let _=new Map;for(let F of $.graph.nodes){if(!M4(F))continue;let Q=F.executor.operation;_.set(`${Q.kind}@${String(Q.version)}`,Q)}return[..._.entries()].sort(([F],[Q])=>F.localeCompare(Q)).map(([,F])=>F)}function U$1($){let _=new Map;for(let F of $.graph.nodes)if(F8(F))_.set(F.executor.compute.key,F.executor.compute);return[..._.entries()].sort(([F],[Q])=>F.localeCompare(Q)).map(([,F])=>F)}function HY($){return new Ud({root:w$1($.paths.privateRoot,D$1)})}async function Sd($){let _=HY($.application),F=B$1(),Q=await _.create({bundleBytes:new Uint8Array($.bundleBytes),graphPlan:$.graphPlan,runId:F,runtime:{computes:U$1($.graphPlan),operations:z$1($.graphPlan),runtime:$.graphPlan.runtime,version:F_},sourceLocator:$.sourceLocator,workflow:{bundle:$.graphPlan.bundle,sourceLocator:$.sourceLocator,workflow:$.graphPlan.graph.workflow}});return{runId:F,store:_,summary:Q}}function k$1($){let _=new Set(["local-media","project-state"]);return $.preparation.every((F)=>_.has(F))}function M$1($){return $.effect!=="paid-cloud"&&$.effect!=="live-control"}function A$1(){return{authorizeEffect:($)=>Promise.resolve(M$1($.policy)),authorizePreparation:($)=>Promise.resolve(k$1($.policy)),grantedBy:"slopcamera-local-cli"}}async function R$1($,_,F,Q){let Z;try{Z=await $.events(_)}catch(X){if(X instanceof N&&X.code==="conflict")return F;throw X}let J=F;for(let X of Z){if(X.sequence<=F)continue;Q(X),J=Math.max(J,X.sequence)}return J}async function pq($){let _=$.store??HY($.application),F=$.hostResourceCoordinator??dQ(),Q=await wj0(F,async(j)=>await RL($.application,j.inheritedFileDescriptor<3?{}:{inheritedFileDescriptors:[j.inheritedFileDescriptor]})),Z=$.replayAmbiguousCode??[];if($.compute!==void 0&&Z.length>0)throw new N("usage","A workflow run cannot use a fresh code worker and persisted compute replay together.");let J=!1,X=Z.length===0?$.compute:{kind:"replay",load:async({signal:j,waitTimeoutMilliseconds:V})=>{if(J)throw new N("conflict","The persisted trusted-code worker pool was already loaded.");J=!0;let O=await wj0(F,async(W)=>await C$1({application:$.application,currentApplicationBuild:Q,inheritedHostResourceFileDescriptor:W.inheritedFileDescriptor,maximumWorkers:YX0($.jobs,Z,F),registry:$.registry,runId:$.runId,store:_}),{signal:j,waitTimeoutMilliseconds:V});return{executor:O,release:async()=>await O.close()}},nodeKeys:Z},Y=new Id({application:$.application,authorization:A$1(),currentApplicationBuild:Q,...X===void 0?{}:{compute:X},hostLimits:{maxJobs:$.jobs},hostResourceCoordinator:F,jobs:$.jobs,nodePlanner:bK0($.application),owner:Dj0(),registry:$.registry,store:_});if($.onEvent===void 0)return await Y.run($.runId);let H=Y.run($.runId).then((j)=>({kind:"result",result:j}),(j)=>({error:j,kind:"error"})),K=0;while(!0){let j=await Promise.race([H,new Promise((V)=>{setTimeout(V,L$1)})]);if(K=await R$1(_,$.runId,K,$.onEvent),j===void 0)continue;if(j.kind==="error")throw j.error;return j.result}}async function Lj0($){let _=HY($.application),F=Dj0(),Q=await _.acquireClaim($.runId,{owner:F});try{let[Z,J]=await Promise.all([_.graphPlan($.runId),_.node($.runId,$.nodeKey)]);if(J.status!=="approval-required")throw new N("conflict",`Node ${$.nodeKey} is not awaiting approval.`);let X={createdAt:new Date().toISOString(),graphPlanSha256:Z.graphPlanSha256,grantedBy:"slopcamera-local-cli",grantId:bd(),nodeKey:$.nodeKey},Y;if($.planKind==="preparation"){let H=J.preparationPlan?.preparationPlanSha256;if(H!==$.planHash)throw new N("conflict","The preparation approval hash does not match the pending node plan.",{actual:H,requested:$.planHash});Y={...X,kind:"preparation",preparationPlanSha256:$.planHash}}else{let H=J.executionPlan?.nodePlanSha256;if(H!==$.planHash)throw new N("conflict","The effect approval hash does not match the pending node plan.",{actual:H,requested:$.planHash});Y={...X,kind:"effect",nodePlanSha256:$.planHash}}return await _.appendGrant(Q,Y)}finally{await _.releaseClaim(Q).catch(()=>{return})}}async function Cj0($){return await HY($.application).requestCancellation($.runId,"slopcamera-local-cli")}async function Bj0($,_){return(await HY($).list()).slice(0,_)}async function zj0($){let _=HY($.application),[F,Q,Z,J]=await Promise.all([_.summary($.runId),_.workflow($.runId),_.nodes($.runId),_.outputs($.runId)]),X=$.nodes==="all"?Z:Z.filter((Y)=>["ambiguous","ambiguous-code","approval-required","failed","incompatible"].includes(Y.status));return{graphPlanSha256:F.graphPlanSha256,nodes:X,outputs:J?.outputs??null,summary:F,workflow:Q.workflow}}function sq($){let _=$.summary,F=[`${_.runId} ${_.status} ${_.graphPlanSha256}`,`nodes completed=${String(_.counts.completed)} failed=${String(_.counts.failed)} skipped=${String(_.counts.skipped)} pending=${String(_.counts.pending)} cancelled=${String(_.counts.cancelled)}`];if($.pause!==void 0){let Q=$.pause.phase==="effect"?"--node-plan":"--preparation-plan";F.push(`next slopcamera runs approve ${_.runId} ${$.pause.nodeKey} ${Q} ${$.pause.planSha256}`,`then slopcamera runs resume ${_.runId}`)}else if(_.status!=="completed"&&_.status!=="cancelled")F.push(`next slopcamera runs show ${_.runId} --nodes failed`);return F.join(`
|
|
5556
|
-
`)}var pL="3.3.
|
|
5556
|
+
`)}var pL="3.3.6",P$1=34359738368,fj0=34359738368;function I$1($,_){return yd($,{assertOwned:async()=>await _.assertOwned(),claims:_.claims,inheritedFileDescriptor:_.inheritedFileDescriptor,inheritedFileDescriptors:[_.inheritedFileDescriptor],profile:_.profile,ticket:_.ticket})}function yd($,_){let F=$.hostResourceLease,Q=F?.inheritedFileDescriptors??[],Z=_.inheritedFileDescriptors.every((K)=>Q.includes(K)),J=Q.every((K)=>_.inheritedFileDescriptors.includes(K));if(F!==void 0&&(F.profile.id!==_.profile.id||F.profile.capacities.length!==_.profile.capacities.length||F.profile.capacities.some((K)=>{return _.profile.capacities.find((V)=>V.resource===K.resource)?.limit!==K.limit})))throw new N("unavailable","Nested host-resource phases must use the same machine profile.");let X=[...Q,..._.inheritedFileDescriptors].filter((K,j,V)=>V.indexOf(K)===j);if(X.length>16)throw new N("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");let Y=F===void 0||J?_:Z?F:{assertOwned:async()=>{await F.assertOwned(),await _.assertOwned()},claims:XX0(F.claims,_.claims),inheritedFileDescriptor:_.inheritedFileDescriptor,inheritedFileDescriptors:X,profile:_.profile,ticket:_.ticket},H=(K=[])=>[...K,...Y.inheritedFileDescriptors].filter((j,V,O)=>O.indexOf(j)===V);return{...$,capabilities:async(K)=>await $.capabilities(H(K)),capability:async(K,j,V)=>await $.capability(K,j,H(V)),hostResourceLease:Y,runner:{run:async(K,j={})=>{await Y.assertOwned();let V=H(j.inheritedFileDescriptors);if(V.length>16)throw new N("unavailable","A direct Slopcamera subprocess cannot inherit more than 16 file descriptors.");return await $.runner.run(K,{...j,inheritedFileDescriptors:V})}}}}function b$1($){switch($.code){case"WAIT_ABORTED":return new N("cancelled",$.message);case"OWNERSHIP_LOST":return new N("conflict",$.message);case"INVALID_CLAIMS":case"INVALID_PROFILE":case"PROFILE_MISMATCH":case"UNSAFE_STATE":case"UNSUPPORTED_PLATFORM":case"WAIT_TIMEOUT":return new N("unavailable",$.message,{hostResourceCode:$.code})}}async function S$1($,_,F){let Q=HX0(_,$.hostResourceCoordinator);await WY($,Q,F,$.abortSignal)}async function WY($,_,F,Q){if(_.length===0)return await F($);try{return await $.hostResourceCoordinator.withLease(_,async(Z)=>{return await Z.assertOwned(),await F(I$1($,Z))},{...Q===void 0?{}:{signal:Q},waitTimeoutMilliseconds:A6})}catch(Z){if(Z instanceof P2)throw b$1(Z);throw Z}}async function fd($,_,F){let Q=rQ([{amount:1,resource:"cpu"},{amount:1,resource:"ffmpeg"},{amount:1,resource:"local-io"}],$.hostResourceCoordinator);if($.hostResourceLease!==void 0){if(await $.hostResourceLease.assertOwned(),lu($.hostResourceLease.claims,Q))return await F(J4($))}return await WY($,BT($.hostResourceLease?.claims??[],Q),async(Z)=>await F(J4(Z)),_)}function J4($,_){let F=(Z)=>({available:Z.available,...Z.command===void 0?{}:{command:Z.command},name:Z.name,...Z.reason===void 0?{}:{reason:Z.reason},...Z.version===void 0?{}:{version:Z.version}}),Q={capabilities:async(Z)=>(await $.capabilities(Z)).map(F),capability:async(Z)=>F(await $.capability(Z)),clock:{now:()=>new Date($.clock()),timestampMilliseconds:$.clock},htmlOverlayRenderer:new Eu({cacheRoot:V5($.paths.privateRoot,"html-overlay-modules-v1"),fetch:$.fetch}),...$.hostResourceLease===void 0?{}:{hostResourceLease:$.hostResourceLease},machineStateRoot:$.stateRoot,paths:$.paths,runner:$.runner,spatialReviewProvider:$.spatialReviewProviderFactory({credential:()=>Zz($.io.env),fetch:$.fetch,transport:$.gatewayCatalogTransport})};return{...Q,gatewayPort:eY0({application:Q,createService:async(Z,J)=>await _70(J===void 0?$:yd($,J),Z),inspectMedia:async(Z,J,X)=>{let Y=X===void 0?$:yd($,X);return(await ON(Y,Z.map((K)=>({data:K.data,mediaType:K.mediaType,path:K.path})),J)).map((K)=>{if(K.url!==void 0)throw new N("internal","Gateway workflow preparation unexpectedly produced a remote media input.");let j=K.facts;return{...j?.durationSeconds===void 0?{}:{durationSeconds:j.durationSeconds},...j?.height===void 0?{}:{height:j.height},...j?.width===void 0?{}:{width:j.width}}})},now:$.io.now,resolveProviderOptions:(Z,J)=>{if(J.aborted)throw new N("cancelled","Gateway provider-options resolution was cancelled.");return Promise.resolve(_)}})}}function x_($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(1).replace(/\.0$/u,"")}ms`;return`${($/1e6).toFixed(3).replace(/0+$/u,"").replace(/\.$/u,"")}s`}function U8($,_){let F=xX($,_);if(!F.available||F.command===void 0)throw new N("unavailable",`${_} is unavailable${F.reason===void 0?".":`: ${F.reason}`}`,{capability:_});return F.command}async function Jj($,_){return await Promise.all(_.map(async(F)=>await $.capability(F)))}async function wY($,_){return U8([await $.capability(_)],_)}function u0($,_,F,Q){if(_)g9($,F);else v9($,Q())}function yj0($,_,F){let Q=MJ0(Y5({toolVersion:F}),F);u0($,_,Q,()=>Q.modules.map((Z)=>`${Z.moduleId}@${Z.version} ${Z.trust} operations=${Z.operations.length} workflows=${Z.workflows.length} tools=${Z.tools.length} ${Z.title}`).join(`
|
|
5557
5557
|
`))}function _3($,_){let F=uZ($,_);return F===""||!F.startsWith("..")&&!eq(F)}async function gd($,_){let F=await h$($.directory.path,_);if(!Ok($,F).startsWith("renders/"))throw new N("unsafe-path","Render outputs must remain under the bundle's renders/ directory so raw capture files stay immutable.");let Z=await h$($.directory.path,"renders");await l1(Z),await l1(P6(F));let[J,X]=await Promise.all([E6(Z),E6(P6(F))]);if(!_3(J,X))throw new N("unsafe-path",`Render output crosses a symlink outside renders/: ${_}`);try{if((await F3(F)).isSymbolicLink())throw new N("unsafe-path",`Render output may not be a symlink: ${_}`)}catch(Y){if(Y instanceof N)throw Y;if(!(Y instanceof Error&&("code"in Y)&&Y.code==="ENOENT"))throw Y}return F}async function f$1($,_,F){let Q=await gd($,_),Z=Ok($,Q),J=Z.toLowerCase();if(GY(Z).toLowerCase()!==".json")throw new N("usage","A resolved render plan output must use a .json path under renders/.");if(J.endsWith(".mp4.plan.json"))throw new N("unsafe-path",`A render plan alias may not overwrite a video receipt: ${_}`);if(/^renders\/resolved-[a-f0-9]{64}\.json$/u.test(J)&&Z!==F)throw new N("unsafe-path",`A render plan alias may not use the canonical resolved-plan namespace: ${_}`);return{absolute:Q,relative:Z}}async function sL($,_,F={}){let Q=await h$($,_),Z=uZ($,Q);if(!Z.startsWith("renders/")||eq(Z))throw new N("unsafe-path","Project render artifacts must remain under the project's renders/ directory.");if(F.videoOutput){let H=Z.split("/"),K=H.at(-1),j=new Set([".filter-graphs",".overlay-cache","derived","plans"]);if(H[0]!=="renders"||j.has(H[1]?.toLowerCase()??""))throw new N("unsafe-path",`Project video output may not use a reserved render-artifact subtree: ${_}`);if(K===void 0||K.toLowerCase()===".mp4"||GY(K).toLowerCase()!==".mp4")throw new N("usage","Project render output must be a final .mp4 file under renders/.")}let J=V5($,"renders");await l1(J),await l1(P6(Q));let[X,Y]=await Promise.all([E6(J),E6(P6(Q))]);if(!_3(X,Y))throw new N("unsafe-path",`Project render path crosses a symlink outside renders/: ${_}`);try{let H=await F3(Q);if(H.isSymbolicLink()||!H.isFile())throw new N("unsafe-path",`Project render leaf must be a physical regular file: ${_}`)}catch(H){if(H instanceof N)throw H;if(!(H instanceof Error&&("code"in H)&&H.code==="ENOENT"))throw H}return{absolute:Q,relative:Z}}async function $E($){return await i3($)}function gj0($,_,F){return{operation:_,planHash:c3(F),planId:F.planId,planPath:oJ,recordingId:$.manifest.recordingId}}async function Uj0($,_,F,Q,Z){let J=R2(F);await l1(V5($.directory.path,"edits")),await GO($.fileSystem,J,oJ);let X=gj0($,_,J);u0(Z,Q,X,()=>`${_} ${F.planId} ${String(X.planHash)}`)}function NY($){if($!=="linear"&&$!=="ease-in"&&$!=="ease-out"&&$!=="ease-in-out"&&$!=="spring")throw new N("usage",`Unsupported easing: ${$}`);return{kind:$}}function kj0($,_,F,Q,Z,J){let X=$??"none";if(X==="none")return{kind:"none"};let Y=E4(_??F);if(X==="fade")return{durationUs:Y,easing:NY(Q),kind:X};if(X==="scale")return{durationUs:Y,easing:NY(Q),fromScale:Z,kind:X};let H=/^slide-(up|down|left|right)$/u.exec(X);if(H?.[1]==="up"||H?.[1]==="down"||H?.[1]==="left"||H?.[1]==="right")return{direction:H[1],distancePx:J,durationUs:Y,easing:NY(Q),kind:"slide"};throw new N("usage",`Unsupported overlay animation: ${X}`)}function y$1($){let _=$.trim().toLocaleLowerCase().replaceAll("u+","").replaceAll(/[_\s]+/gu,"-");if(/^[a-f0-9]+(?:-[a-f0-9]+)*$/u.test(_))return{kind:"id",value:_};if([...$].length<=16&&/[^\p{L}\p{N}\p{P}\p{Z}]/u.test($))return{kind:"unicode",value:$};return{kind:"name",value:$}}function mZ($,_,F){let Q=E4($,F),Z=E4(_,F);if(Z<=Q)throw new N("usage",`Time range must increase: ${$}..${_}`);return{endUs:Z,startUs:Q}}function g$1($){let _=$.length+1;while($.some(({overlayId:F})=>F===`overlay_manual${String(_).padStart(4,"0")}`))_+=1;return`overlay_manual${String(_).padStart(4,"0")}`}function v$1($){let _=$.length+1;while($.includes(`zoom_manual${String(_).padStart(4,"0")}`))_+=1;return`zoom_manual${String(_).padStart(4,"0")}`}async function vj0($,_,F,Q,Z,J){let{startUs:X,endUs:Y}=mZ(Q.from,Q.to,Z),H=J?.({endUs:Y,startUs:X})??Y-X;if(H<=0)throw new N("conflict","Overlay range has no visible kept output time.");let K=Q.overlayKind==="emoji"?await wV($.paths.repositoryRoot,Q.source,Q.variant,Q.provider):void 0,j=Q.overlayKind==="emoji"?await KM(_,K):await HM(_,Q.source,Q.overlayKind),{created:V,...O}=j,W=async()=>{let G=F.some((D)=>D.source.asset.path===O.path);if(V&&!G)await NN(V5(_,O.path),{force:!0})};try{let G=await h$(_,O.path),D=O.mediaType==="image/svg+xml"?{...await HX(G),audioEndUs:null,audioStartUs:0,audioStreamIndex:null,durationUs:null,hasAudio:!1,videoStartUs:0,videoStreamIndex:null}:await UQ(await wY($,"ffprobe"),$.runner,G),w={height:"pixelHeight"in D?D.pixelHeight:D.height,width:"pixelWidth"in D?D.pixelWidth:D.width},L;if(Q.overlayKind==="image"||Q.overlayKind==="svg")L={asset:O,kind:Q.overlayKind};else if(Q.overlayKind==="emoji")L={asset:O,kind:"emoji",provider:K.provider,selector:y$1(Q.source)};else{if(Q.loop&&Q.freezeEnd)throw new N("usage","Use only one of --loop and --freeze-end.");let B=E4(Q.sourceIn??"0us",Z),z=Q.sourceOut===void 0?void 0:E4(Q.sourceOut,Z);if(D.durationUs===null||D.durationUs<=0)throw new N("invalid-data","Animated overlay media must report a positive finite duration.");if(Q.overlayKind==="video"&&Q.animatedAudio!=="mute"&&!D.hasAudio)throw new N("conflict",`Video overlay audio policy ${Q.animatedAudio} requires an audio stream in the source media.`);let U=DV({mediaDurationUs:D.durationUs,outputDurationUs:H,playbackRate:Q.playbackRate,sourceInUs:B,sourceOutUs:z}),k={audioEndUs:D.audioEndUs,audioStartUs:D.audioStartUs,audioStreamIndex:D.audioStreamIndex,endBehavior:Q.loop?"loop":Q.freezeEnd?"freeze-end":"hide",playbackRate:Q.playbackRate,streamStartUs:D.videoStartUs,videoStreamIndex:D.videoStreamIndex,...U};if(Q.overlayKind==="gif")L={asset:O,audioPolicy:{kind:"mute"},kind:"gif",playback:k};else{let A=Q.animatedAudio==="mute"?{kind:"mute"}:Q.animatedAudio==="mix"?{kind:"mix",volume:Q.audioVolume}:{duckPrimaryTo:Q.duckPrimaryTo,kind:"duck-primary",volume:Q.audioVolume};L={asset:O,audioPolicy:A,kind:"video",playback:k}}}if(Q.width===void 0!==(Q.height===void 0))throw new N("usage","Overlay pixel size requires both --width and --height.");let C=C5.safeParse({anchor:Q.anchor,blendMode:Q.blendMode,coordinateSpace:"output-pixels",crop:Q.crop===void 0?{kind:"none"}:{bottom:Q.crop[3],kind:"normalized-insets",left:Q.crop[0],right:Q.crop[2],top:Q.crop[1]},entrance:kj0(Q.entrance,Q.entranceDuration,"250ms",Q.easing,Q.entranceFromScale,Q.slideDistance),exit:kj0(Q.exit,Q.exitDuration,"250ms",Q.easing,Q.exitToScale,Q.slideDistance),fit:Q.fit,intrinsicSize:w,mask:Q.cornerRadius===void 0?{kind:"none"}:{kind:"rounded-rectangle",radiusPx:Q.cornerRadius},motion:Q.motionKeyframes.length===0?{kind:"none"}:{keyframes:Q.motionKeyframes.map((B)=>({easing:NY(Q.easing),offset:B.offset,opacityMultiplier:B.opacity,positionOffset:{x:B.position[0],y:B.position[1]},rotationOffsetDegrees:B.rotation,scaleMultiplier:B.scale})),kind:"keyframes",timeline:"visible-output"},opacity:Q.opacity,overlayId:g$1(F),position:{x:Q.position[0],y:Q.position[1]},range:{endUs:Y,startUs:X},rotationDegrees:Q.rotation,scale:Q.scale,size:Q.width===void 0||Q.height===void 0?{kind:"intrinsic"}:{height:Q.height,kind:"pixels",width:Q.width},source:L,zIndex:Q.zIndex});if(!C.success)throw new N("usage",`Invalid overlay: ${C.error.issues[0]?.message??"unknown error"}`);return{operation:C.data,rollback:W}}catch(G){throw await W(),G}}function x$1($,_,F,Q){let Z=xj0($,_,void 0,Q),J=Z.displayId??F.sources.displays.find(({isPrimary:X})=>X)?.displayId;if(J===void 0)throw new N("not-found","Manual zoom requires a selected or primary display.");return D3.parse({...Z,displayId:J,kind:"manual"})}function xj0($,_,F,Q){let{startUs:Z,endUs:J}=mZ($.from,$.to,Q),X=$.target==="rect"?{kind:"rect",rect:{height:$.rect[3],width:$.rect[2],x:$.rect[0],y:$.rect[1]}}:$.target==="point"?{kind:"point",point:{x:$.point[0],y:$.point[1]}}:$.target==="cursor"?{kind:"cursor",sampling:"interpolated"}:$.target==="focused-input"?{kind:"focused-input",paddingPx:24}:$.window==="frontmost"?{kind:"window",paddingPx:24,selector:{kind:"frontmost"}}:$.window.startsWith("bundle:")?{kind:"window",paddingPx:24,selector:{applicationBundleId:$.window.slice(7),kind:"application"}}:{kind:"window",paddingPx:24,selector:{kind:"window-id",windowId:$.window}},Y=J-Z,H=Math.min(300000,Math.max(0,Math.floor(Y/2))),K=$.enterDuration===void 0?H:E4($.enterDuration,Q),j=$.exitDuration===void 0?H:E4($.exitDuration,Q),V=Qy.safeParse({...$.display===void 0?{}:{displayId:$.display},easing:NY($.easing),enterDurationUs:K,exitDurationUs:j,...F===void 0?{}:{placementId:F},range:{endUs:J,startUs:Z},scale:$.scale,target:X,zoomId:v$1(_)});if(!V.success)throw new N("usage",`Invalid zoom: ${V.error.issues[0]?.message??"unknown error"}`);return V.data}async function h$1($,_){let F=await U$($.paths.artifactRoot,_.recording);if(F.manifest.state!=="stopped")throw new N("conflict","Editing requires a stopped recording with an immutable timeline, media, and events.");if(_.edit.operation==="init"){let Y=await of(F),H=Y??at(F.manifest,P10(F.manifest),$.io.now().toISOString());await Uj0(F,Y===null?"init":"init-existing",H,_.json,$.io);return}let Q=await gG(F);if(_.edit.operation==="show"){u0($.io,_.json,Q,()=>`${Q.planId} ${c3(Q)} keep=${Q.keep.length} speed=${Q.speed.length} zooms=${Q.zooms.length} overlays=${Q.overlays.length}`);return}let Z=$.io.now().toISOString(),J,X=_.edit;switch(X.operation){case"trim":J=tt(Q,mZ(X.from,X.to,_.fps),Z);break;case"cut":J=TU(Q,mZ(X.from,X.to,_.fps),Z);break;case"speed":J=oS(Q,mZ(X.from,X.to,_.fps),X.rate,Z);break;case"zoom-add":J=et(Q,x$1(X,Q.zooms.map((Y)=>Y.zoomId),F.manifest,_.fps),Z);break;case"zoom-remove":J=$e(Q,X.id,Z);break;case"overlay-add":{let Y=await vj0($,F.directory.path,Q.overlays,X,_.fps,(K)=>AH(lU(Q),K).reduce((j,V)=>j+V.output.endUs-V.output.startUs,0));try{J=R2(_e(Q,Y.operation,Z)),await l1(V5(F.directory.path,"edits")),await GO(F.fileSystem,J,oJ)}catch(K){throw await Y.rollback(),K}let H=gj0(F,X.operation,J);u0($.io,_.json,H,()=>`${X.operation} ${J.planId} ${String(H.planHash)}`);return}case"overlay-remove":J=Fe(Q,X.id,Z);break;case"cursor":J=gJ({...Q,effects:{...Q.effects,...X.clickHighlight===void 0?{}:{clicks:X.clickHighlight?{color:"#ffcc00cc",durationUs:350000,enabled:!0,radiusPx:28,style:"pulse"}:{enabled:!1}},cursor:X.enabled?{enabled:!0,scale:1,smoothing:{algorithm:"exponential",strength:X.smoothing??0.7},style:"captured"}:{enabled:!1}},updatedAt:Z});break;case"clicks":J=gJ({...Q,effects:{...Q.effects,clicks:X.enabled?{color:X.color,durationUs:E4(X.duration,_.fps),enabled:!0,radiusPx:X.radius,style:X.style}:{enabled:!1}},updatedAt:Z});break;case"keystrokes":J=gJ({...Q,effects:{...Q.effects,keystrokes:X.enabled?{enabled:!0,holdUs:E4(X.stopAfter??"1200ms",_.fps),maxKeys:8,position:"bottom-right",secureText:"hide"}:{enabled:!1}},updatedAt:Z});break;case"typed-text":if(X.enabled&&F.manifest.capture.typedText!=="enabled")throw new N("conflict","Typed-text rendering cannot be enabled because typed-text capture was disabled for this recording.");J=gJ({...Q,effects:{...Q.effects,typedText:X.enabled?{enabled:!0,idleTimeoutUs:E4(X.idleTimeout,_.fps),maxCharacters:X.maxCharacters,placement:X.placement,secureText:"hide"}:{enabled:!1}},updatedAt:Z});break}await Uj0(F,X.operation,J,_.json,$.io)}async function hj0($,_,F){if(_.manifest.state!=="stopped")throw new N("conflict","Inactivity analysis requires a stopped recording with immutable media and events.");let Q=await Jj($,["ffmpeg","ffprobe"]),Z=U8(Q,"ffmpeg"),J=U8(Q,"ffprobe"),X=new vG({ffmpeg:Z,ffprobe:J,runner:$.runner}),Y=_.manifest.tracks.filter((D)=>D.enabled&&D.kind==="display-video");if(Y.length===0)throw new N("invalid-data","Recording has no enabled display tracks to analyze.");let H=await wQ(Y,4,async(D)=>{let w=[];for(let L of D.segments){if(L.integrity.state!=="verified"||L.integrity.bytes<=0)throw new N("invalid-data",`Inactivity media ${L.path} does not have verified integrity.`);let C=await a1({expected:L.integrity,label:`Inactivity media ${L.path}:${L.streamIndex}`,path:L.path,repositoryRoot:_.directory.path}),B=await X.freeze(C,L.streamIndex,F.minDurationUs,F.motionThreshold,L.startUs);w.push(...B.filter(({startUs:z,endUs:U})=>z<L.endUs&&U>L.startUs).map(({startUs:z,endUs:U})=>({confidence:1,meanFrameDifference:F.motionThreshold,range:{startUs:Math.max(z,L.startUs),endUs:Math.min(U,L.endUs)}})))}return{intervals:w,trackId:D.trackId}}),K=F.protectAudio?_.manifest.tracks.filter((D)=>D.enabled&&(D.kind==="system-audio"||D.kind==="microphone-audio")):[],j=await wQ(K,4,async(D)=>{let w=[];for(let L of D.segments){if(L.integrity.state!=="verified"||L.integrity.bytes<=0)throw new N("invalid-data",`Inactivity media ${L.path} does not have verified integrity.`);let C=await a1({expected:L.integrity,label:`Inactivity media ${L.path}:${L.streamIndex}`,path:L.path,repositoryRoot:_.directory.path}),B=await X.silence(C,L.streamIndex,F.minDurationUs,L.startUs);w.push(...B.filter(({startUs:z,endUs:U})=>z<L.endUs&&U>L.startUs).map(({startUs:z,endUs:U})=>({peakDb:-45,range:{startUs:Math.max(z,L.startUs),endUs:Math.min(U,L.endUs)}})))}return{intervals:w,trackId:D.trackId}}),V=xX(Q,"ffmpeg").version??"unknown",O=nC.parse({audio:j,displays:H,kind:"slopcamera.analyzer-evidence",schemaVersion:1,sourceDurationUs:_.manifest.timeline.durationUs,tool:{name:"ffmpeg-freezedetect-silencedetect",version:V.slice(0,128)}});await l1(V5(_.directory.path,"analysis")),await _.fileSystem.writeTextAtomic("analysis/inactivity-v1.json",`${R(O)}
|
|
5558
5558
|
`);let W=await $E(_),G=st(O,W,{edgeHandleUs:250000,interactionHandleUs:750000,minimumCutUs:F.minDurationUs,cursorMovementThresholdPx:2,requireAudioSilence:F.protectAudio});return{evidence:O,result:G}}async function m$1($,_){let F=await U$($.paths.artifactRoot,_.recording);if(F.manifest.state!=="stopped")throw new N("conflict","Inactivity analysis requires a stopped recording with immutable media and events.");let Q=await gG(F),Z=await hj0($,F,{minDurationUs:E4(_.minDuration),motionThreshold:_.motionThreshold,protectAudio:_.protectAudio}),J=Q;if(_.apply&&_.handle!=="keep"){for(let Y of Z.result.cuts)J=_.handle==="cut"?TU(J,Y,$.io.now().toISOString()):oS(J,Y,_.speedRate,$.io.now().toISOString());J=R2(J),await l1(V5(F.directory.path,"edits")),await GO(F.fileSystem,J,oJ)}let X={applied:_.apply&&_.handle!=="keep",candidateCount:Z.result.candidateCount,cuts:Z.result.cuts,evidencePath:"analysis/inactivity-v1.json",handle:_.handle,planHash:c3(J),protectedInteractionCount:Z.result.protectedInteractionCount,recordingId:F.manifest.recordingId};u0($.io,_.json,X,()=>`${X.cuts.length} inactivity range(s), ${X.applied?"applied":"dry-run"}; plan ${X.planHash}`)}async function u$1($,_){let F=await o4($.paths.projectRoot,_.recording);if(_.apply&&_.handle!=="keep")uj0(F.project,"Automated project inactivity edits");let Q=await Jj($,["ffmpeg","ffprobe"]),Z=U8(Q,"ffmpeg"),J=U8(Q,"ffprobe"),X=xX(Q,"ffmpeg").version??"unknown",Y=await d10({artifactRoot:$.paths.artifactRoot,config:{...iJ,minimumCutUs:E4(_.minDuration),motionThreshold:_.motionThreshold,requireAudioSilence:_.protectAudio},ffmpeg:Z,ffmpegVersion:X,ffprobe:J,now:$.io.now(),project:F,repositoryRoot:$.paths.repositoryRoot,runner:$.runner,toolVersion:$.version}),H=await h8(F),K=_.apply&&_.handle!=="keep"&&Y.analysis.result.recommendedRanges.length>0;if(K){let V=$.io.now().toISOString(),O=qe({analysis:Y.analysis,decisionIds:Y.analysis.result.recommendedRanges.map(()=>`decision_${hF().replaceAll("-","")}`),operation:_.handle==="cut"?"cut":"speed",plan:H,project:Y.project,speedRate:_.speedRate,updatedAt:V});if(O.status==="rejected")throw new N("conflict",`Inactivity application was rejected: ${O.reason}`,O);H=R2(O.plan),await d6(F.fileSystem,H)}let j={analysisId:Y.analysis.analysisId,applied:K,candidateCount:Y.analysis.result.candidateCount,cuts:Y.analysis.result.recommendedRanges,evidencePath:Y.analysisPath,handle:_.handle,planHash:x2(H),projectId:Y.project.projectId,protectedInteractionCount:Y.analysis.result.protectedInteractionCount,referenceRecording:Y.analysis.referenceRecording?.recordingId??null};u0($.io,_.json,j,()=>`${j.cuts.length} project inactivity range(s), ${j.applied?"applied":"evidence only"}; analysis ${j.analysisId}; plan ${j.planHash}`)}async function l$1($,_){if(_.recording.startsWith("project_")){await u$1($,_);return}await m$1($,_)}async function d$1($,_){let F=await U$($.paths.artifactRoot,_.recording);if(F.manifest.state!=="stopped")throw new N("conflict","Automatic zoom analysis requires a stopped recording with immutable events.");let Q=await gG(F);if(_.plan!==void 0&&_.plan!=="current"&&_.plan!==Q.planId)throw new N("not-found",`Only current (${Q.planId}) is available; requested ${_.plan}.`);let Z=LU(await $E(F),Q.sourceDurationUs,{enterDurationUs:300000,exitDurationUs:300000,intentMergeGapUs:750000,maxDurationUs:8000000,maxScale:3,minDurationUs:1500000,postHandleUs:1e6,preHandleUs:500000,scale:2}),J=Q;if(_.apply)J=gJ({...Q,updatedAt:$.io.now().toISOString(),zooms:[...Q.zooms.filter(({kind:Y})=>Y!=="automatic"),...Z]}),J=R2(J),await l1(V5(F.directory.path,"edits")),await GO(F.fileSystem,J,oJ);let X={applied:_.apply,planHash:c3(J),recordingId:F.manifest.recordingId,suggestions:Z.map((Y)=>({confidence:Y.confidence,range:Y.range,reason:Y.reason,scale:Y.scale,target:Y.target,zoomId:Y.zoomId}))};u0($.io,_.json,X,()=>`${Z.length} automatic zoom suggestion(s), ${_.apply?"applied":"dry-run"}; plan ${X.planHash}`)}function c$1($,_){let F=$.tracks.filter((Z)=>Z.enabled&&Z.kind==="display-video"),Q=_==="primary"?F.find((Z)=>$.sources.displays.some((J)=>J.isPrimary&&J.displayId===Z.source.displayId)):F.find((Z)=>Z.source.displayId===_||Z.trackId===_);if(Q===void 0)throw new N("not-found",`No enabled display track matches ${_}.`);return Q}async function p$1($,_,F,Q,Z){let J=F;if(Q){let j=await hj0($,_,{minDurationUs:3000000,motionThreshold:0.003,protectAudio:!0});for(let V of j.result.cuts)J=TU(J,V,F.updatedAt)}let X=c$1(_.manifest,Z),Y=_.manifest.sources.displays.find(({displayId:j})=>j===X.source.displayId),H=await $E(_),K=_.manifest.tracks.filter((j)=>j.enabled&&(j.kind==="system-audio"||j.kind==="microphone-audio")).map(({trackId:j})=>j);return{effectivePlan:J,renderPlan:$00(_.manifest,J,H,{audioTrackIds:K,camera:{kind:"none"},displayTrackId:X.trackId,frameRate:Math.min(60,Y.refreshRateHz),pixelHeight:Y.pixelSize.height,pixelWidth:Y.pixelSize.width})}}async function s$1($,_){let F=await U$($.paths.artifactRoot,_.recording);if(F.manifest.state!=="stopped")throw new N("conflict","Rendering requires a stopped recording with immutable media and events.");let Q=await gG(F),Z=await p$1($,F,Q,_.autoInactivity,_.display),J=X0(R(Z.renderPlan)),X=`renders/resolved-${J}.json`,Y=`renders/${J}.mp4`;await l1(V5(F.directory.path,"renders"));let H=_.kind==="render-plan"&&_.output!==void 0?await f$1(F,_.output,X):void 0;if(await F.fileSystem.writeTextAtomic(X,`${R(Z.renderPlan)}
|
|
5559
5559
|
`),_.kind==="render-plan"){if(H!==void 0&&H.relative!==X)await F.fileSystem.writeTextAtomic(H.relative,`${R(Z.renderPlan)}
|
|
@@ -5588,8 +5588,8 @@ plan=${X}`);return}if(w===null)throw new N("internal","Recording render receipt
|
|
|
5588
5588
|
`))}async function T81($,_){let F=new aX($.stateRoot),Q=QE($),Z=await ML($.io.env,F);if(Z!==void 0){let j;try{j=await Q.balance(Z.token)}catch(O){throw oW(O)}let V=j.topup;if(V!==null){let O={balance:j.balance,packs:rq(V.packs),suggestedPackId:V.suggestedPackId,url:V.url,walletBound:!0,next:["slopcamera credits status"]};u0($.io,_.json,O,()=>[`pay ${V.url}`,`balance ${j.balance.usd} USD (${j.balance.credits} credits)`,"","Open the URL, pay, then check:"," slopcamera credits status"].join(`
|
|
5589
5589
|
`));return}}if(Z!==void 0)throw new N("unavailable","The configured wallet does not expose a bound top-up right now. Run `slopcamera credits forget` to abandon this wallet, or retry `slopcamera credits topup` later.");let J=$.clock(),X=await F.readPendingClaim();if(X!==void 0&&Date.parse(X.expiresAt)>J+60000){let j={claimId:X.claimId,expiresAt:X.expiresAt,packs:rq(X.packs),suggestedPackId:X.suggestedPackId,url:X.url,walletBound:!1,reused:!0,next:["slopcamera credits wait"]};u0($.io,_.json,j,()=>[`pay ${X.url}`,`claim ${X.claimId} (existing, expires ${X.expiresAt})`,"","Open the URL to pay, then run:"," slopcamera credits wait"].join(`
|
|
5590
5590
|
`));return}let Y=await F.deviceIdentity(),H;try{H=await Q.createClaim({deviceId:Y.deviceId,deviceLabel:Y.label,..._.email===void 0?{}:{email:_.email},..._.pack===void 0?{}:{packId:_.pack},resumeArgv:["slopcamera","credits","wait"]})}catch(j){throw oW(j)}await F.writePendingClaim({claimId:H.claimId,claimSecret:H.claimSecret,url:H.url,expiresAt:H.expiresAt,packs:H.packs,suggestedPackId:H.suggestedPackId,createdAt:new Date(J).toISOString()});let K={claimId:H.claimId,expiresAt:H.expiresAt,packs:rq(H.packs),suggestedPackId:H.suggestedPackId,url:H.url,walletBound:!1,reused:!1,next:["slopcamera credits wait"]};u0($.io,_.json,K,()=>[`pay ${H.url}`,`claim ${H.claimId} (expires ${H.expiresAt})`,...H.packs.length===0?[]:["","packs:",...H.packs.map((j)=>` ${j.id} ${j.label}`)],"","Open the URL to pay, then run:"," slopcamera credits wait"].join(`
|
|
5591
|
-
`))}async function q81($,_){let F=new aX($.stateRoot),Q=QE($),Z=await F.readPendingClaim();if(Z===void 0)throw new N("usage","No pending credits top-up. Run `slopcamera credits topup` first.");let J=Z.claimSecret,X=$.clock()+GN(_.timeout),Y=Date.parse(Z.expiresAt),H=Number.isFinite(Y)?Math.min(X,Y+300000):X;for(;;){let K;try{K=await Q.claimStatus(Z.claimId,J)}catch(j){throw oW(j)}if(K.
|
|
5592
|
-
`));return}await F.clearPendingClaim();let j={claimId:Z.claimId,configured:!0,state:"paid",walletBound:!0,next:["slopcamera credits status"]};u0($.io,_.json,j,()=>["paid\ttop-up applied to the configured wallet",""," slopcamera credits status"].join(`
|
|
5591
|
+
`))}async function q81($,_){let F=new aX($.stateRoot),Q=QE($),Z=await F.readPendingClaim();if(Z===void 0)throw new N("usage","No pending credits top-up. Run `slopcamera credits topup` first.");let J=Z.claimSecret,X=$.clock()+GN(_.timeout),Y=Date.parse(Z.expiresAt),H=Number.isFinite(Y)?Math.min(X,Y+300000):X;for(;;){let K;try{K=await Q.claimStatus(Z.claimId,J)}catch(j){throw oW(j)}if(K.deviceToken!==void 0){await F.writeDeviceToken(K.deviceToken),await F.clearPendingClaim();let j={claimId:Z.claimId,configured:!0,state:"paid",next:["slopcamera credits status","slopcamera ai image generate --hosted --model <id> --prompt <text>"]};u0($.io,_.json,j,()=>["paid\tcredits wallet is configured on this device","","Next:"," slopcamera credits status"," slopcamera ai image generate --hosted --model <id> --prompt <text>"].join(`
|
|
5592
|
+
`));return}if(K.state==="paid"){await F.clearPendingClaim();let j={claimId:Z.claimId,configured:!0,state:"paid",walletBound:!0,next:["slopcamera credits status"]};u0($.io,_.json,j,()=>["paid\ttop-up applied to the configured wallet",""," slopcamera credits status"].join(`
|
|
5593
5593
|
`));return}if(K.state==="consumed"){if(await F.clearPendingClaim(),await F.readDeviceToken()!==void 0){let V={claimId:Z.claimId,configured:!0,state:"consumed",next:["slopcamera credits status"]};u0($.io,_.json,V,()=>`paid credits wallet is configured on this device
|
|
5594
5594
|
|
|
5595
5595
|
slopcamera credits status`);return}throw new N("conflict","The claim was consumed elsewhere and no device token is stored locally. Run `slopcamera credits topup` to start a new top-up.")}if(K.state==="expired")throw await F.clearPendingClaim(),new N("cancelled","The checkout expired before payment. Run `slopcamera credits topup` for a fresh link.");if($.clock()>=H){let j={claimId:Z.claimId,configured:!1,expiresAt:Z.expiresAt,state:"pending",url:Z.url,next:["slopcamera credits wait"]};u0($.io,_.json,j,()=>[`pending ${Z.url}`,`claim expires ${Z.expiresAt}`,"","Payment is not complete yet. Re-run:"," slopcamera credits wait"].join(`
|
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{SLOPCAMERA_VERSION,artifactSummary,checkDiagramFile,checkDrawingFile,renderDiagramFile,renderDrawingFile,runMcpServer,starterDrawingSource}from"./index-
|
|
3
|
+
import{SLOPCAMERA_VERSION,artifactSummary,checkDiagramFile,checkDrawingFile,renderDiagramFile,renderDrawingFile,runMcpServer,starterDrawingSource}from"./index-10bz03js.js";import{installSkill,pathExists}from"./index-grk47tgs.js";import"./index-z1kd1x8j.js";import"./index-3cxf2c58.js";import"./index-qtn3s421.js";import{executeSlopcameraOperation,generateSlopcameraIcon,generateSlopcameraImageGallery,isSlopcameraOperationCode,parseSlopcameraGalleryVary,searchSlopcameraOperations,slopcameraGalleryKinds,slopcameraGalleryLimits,slopcameraIconMaximumRounds,slopcameraOperationCodes,withSlopcameraOperationHostAdmission}from"./index-sy1n4zfy.js";import{vectorizeImage}from"./index-qry58nj2.js";import{generateSlopcameraImageFile,slopcameraGatewayCredentialStatus,slopcameraImageModels}from"./index-77fjfg9f.js";import"./index-b3geqczn.js";import{__require}from"./index-80a36bc0.js";import{readFile,writeFile}from"fs/promises";import{resolve}from"path";function reportUsefulResult(observer){try{if(observer!==undefined)Promise.resolve(observer()).catch(()=>{return})}catch{}}import{maybeShowSupportInvitation,runSupportCommand}from"@hraness/support-foundation/node";var supportProfile={id:"slopcamera",name:"Slopcamera",valueProposition:"Support ongoing development of local visual tools for agents.",updates:false};function standaloneSupportEnvironment(){const env={...process.env};process.env.HRANESS_SUPPORT_AUDIENCE="off";process.env.HRANESS_SUPPORT_EMAIL="off";return env}async function runProductSupportCommand(args,options={}){const result=await runSupportCommand(supportProfile,args,{command:["slopcamera"],...options,gitEmail:false});if(result.stdout!=="")process.stdout.write(result.stdout);if(result.stderr!=="")process.stderr.write(result.stderr);return result.exitCode}async function showProductSupportInvitation(options={}){try{await maybeShowSupportInvitation(supportProfile,{usefulResult:true,command:["slopcamera"],...options,gitEmail:false})}catch{}}var slopcameraCliVersion=SLOPCAMERA_VERSION;var help=`slopcamera ${slopcameraCliVersion}
|
|
4
4
|
|
|
5
5
|
Turn source material into deterministic diagrams, images, and canvas assets.
|
|
6
6
|
|
|
@@ -20,7 +20,7 @@ ${freeEntry}${usedEntries}trailer
|
|
|
20
20
|
startxref
|
|
21
21
|
${offset}
|
|
22
22
|
%%EOF
|
|
23
|
-
`);const bytes=Buffer.from(chunks.join(""));if(bytes.length>32*1024*1024)throw new Error("Drawing PDF exceeds output byte limit");return bytes}var SLOPCAMERA_VERSION="3.3.5";var drawingProfile="patent-line-art-v1";var drawingSourceByteLimit=1024*1024;var drawingMinimumGlyphHeightPt=3.2*72/25.4;class DrawingValidationError extends Error{constructor(message){super(`Invalid drawing source: ${message}`);this.name="DrawingValidationError"}}function fail2(message){throw new DrawingValidationError(message)}var sha256=(value)=>createHash("sha256").update(value).digest("hex");var assetPath=(asset)=>isAbsolute2(asset)?asset:fileURLToPath(new URL(asset,import.meta.url));var fontFiles=[assetPath(NebulaSans_Book_default),assetPath(NebulaSans_Bold_default)];var monochrome={background:"#ffffff",foreground:"#000000",muted:"#000000",stroke:"#000000",tones:Object.fromEntries(["neutral","blue","orange","green","red","purple","yellow"].map((tone)=>[tone,{fill:"#ffffff",stroke:"#000000",text:"#000000"}]))};var config={font:{family:"Nebula Sans",files:[{path:fontFiles[0],weight:400},{path:fontFiles[1],weight:700}]},theme:{light:monochrome}};var escapeXml=(value)=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""");function drawingPageGeometry(paper){if(paper!=="us-letter"&&paper!=="a4")fail2("paper must be us-letter or a4");const width=paper==="us-letter"?612:210*72/25.4;const height=paper==="us-letter"?792:297*72/25.4;const margins={left:25*72/25.4,top:25*72/25.4,right:15*72/25.4,bottom:10*72/25.4};return{width,height,margins,numberingHeight:30,body:{x:margins.left,y:margins.top+30,width:width-margins.left-margins.right,height:height-margins.top-margins.bottom-60}}}function record(value,keys,at){if(typeof value!=="object"||value===null||Array.isArray(value))fail2(`${at} must be an object`);const result=value;for(const key of Object.keys(result))if(!keys.includes(key))fail2(`${at}.${key} is unsupported`);return result}function checkDiagramEnvelope(value){const diagram=record(value,["$schema","version","name","canvas","layout","shapes","edges"],"diagram");const bounded=(object)=>{for(const value2 of Object.values(object)){if(typeof value2==="number"&&(!Number.isFinite(value2)||Math.abs(value2)>1e4))fail2("numeric drawing values must be finite and within 10000 points");if(typeof value2==="string"&&value2.length>1024)fail2("drawing strings exceed the bounded text limit")}};bounded(diagram);bounded(record(diagram.canvas,["width","height","padding"],"canvas"));if(diagram.layout!==undefined)bounded(record(diagram.layout,["type","direction","gap","align"],"layout"));if(!Array.isArray(diagram.shapes)||diagram.shapes.length<1||diagram.shapes.length>100)fail2("each sheet needs 1 to 100 shapes");for(const value2 of diagram.shapes){const shape=record(value2,["id","type","x","y","tone","opacity","width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap","text","fontSize","fontFamily","weight","align","x2","y2"],"shape");bounded(shape);const common=["id","type","x","y","tone","opacity"];const extras=shape.type==="text"?["text","width","fontSize","fontFamily","weight","align"]:shape.type==="line"?["x2","y2","strokeWidth"]:["width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap"];record(value2,[...common,...extras],"shape");if(shape.labelRows!==undefined){if(!Array.isArray(shape.labelRows)||shape.labelRows.length>4)fail2("labelRows must be bounded");for(const row of shape.labelRows)bounded(record(row,["text","fontSize","fontFamily","weight"],"label row"))}for(const key of["label","text"])if(typeof shape[key]==="string"&&shape[key].length>500)fail2("label exceeds text limit")}if(diagram.edges!==undefined){if(!Array.isArray(diagram.edges)||diagram.edges.length>150)fail2("at most 150 edges are supported");for(const edge of diagram.edges)bounded(record(edge,["id","from","to","label","tone","start","end","bend","arrowhead","startPosition","endPosition","labelFontSize","labelFontFamily","labelWeight","labelPosition","labelOffset"],"edge"))}}function parseDrawingSource(value){const raw=record(value,["$schema","version","name","title","paper","sheets"],"drawing");if(raw.version!==1)fail2("version must be 1");if(typeof raw.name!=="string"||raw.name.length>100||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(raw.name))fail2("name must be a bounded lowercase hyphenated name");if(raw.paper!=="us-letter"&&raw.paper!=="a4")fail2("paper must be us-letter or a4");if(raw.title!==undefined&&(typeof raw.title!=="string"||raw.title.length<1||Buffer.byteLength(raw.title)>1024||/[\u0000-\u001f]/u.test(raw.title)))fail2("title must be a bounded metadata string");if(raw.$schema!==undefined&&typeof raw.$schema!=="string")fail2("$schema must be a string");if(!Array.isArray(raw.sheets)||raw.sheets.length<1||raw.sheets.length>20)fail2("sheets must contain 1 to 20 sheets");const sheets=raw.sheets.map((sheet,index)=>{const entry=record(sheet,["figure","diagram"],`sheets[${index}]`);if(entry.figure!==index+1)fail2("figure numbers must be consecutive beginning at 1");checkDiagramEnvelope(entry.diagram);const diagram=parseDiagramSource(entry.diagram);const spec=parseDiagramSpec(diagram);if(spec.shapes.length<1||spec.shapes.length>100||(spec.edges?.length??0)>150)fail2("each sheet needs 1 to 100 shapes and at most 150 edges");return{figure:index+1,diagram}});const source={version:1,name:raw.name,paper:raw.paper,sheets,...raw.title===undefined?{}:{title:raw.title},...raw.$schema===undefined?{}:{$schema:raw.$schema}};if(Buffer.byteLength(JSON.stringify(source))>drawingSourceByteLimit)fail2("source exceeds 1MiB byte limit");return source}function renderer(svg){return new Resvg(svg,{font:{fontFiles,loadSystemFonts:false,defaultFontFamily:"Nebula Sans"},logLevel:"off"})}function bounds(engine){const box=engine.getBBox();if(box===undefined)fail2("empty drawing ink");return{x:box.x,y:box.y,width:box.width,height:box.height}}function inside(ink,box,label){const epsilon=0.01;if(ink.x<box.x-epsilon||ink.y<box.y-epsilon||ink.x+ink.width>box.x+box.width+epsilon||ink.y+ink.height>box.y+box.height+epsilon)fail2(`${label} ink extends beyond its bounds`)}async function sceneSvg(spec){return(await renderSvg(spec,"light",config,{edgeStrokeWidth:1})).svg.replace('<rect width="100%" height="100%" fill="#ffffff"/>',"")}function glyphHeight(character,fontSize,weight){const svg=`<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><text x="100" y="500" font-family="Nebula Sans" font-size="${fontSize}" font-weight="${weight}">${escapeXml(character)}</text></svg>`;return bounds(renderer(svg)).height}function inspectLabels(spec,glyphCache){let minimum=Infinity;const inspect=(text,fontSize,weight,family)=>{if(text.length<1||text.length>500||!Array.from(text).every((character)=>/^[A-Z0-9 \n]$/u.test(character)||".,:;()[]/+=_*'!?%-".includes(character)))fail2("visible labels must be uppercase ASCII letters, numbers, spaces, or supported punctuation; labels are never rewritten");if(family!==undefined&&family!=="default")fail2("only the bundled default font is supported");if(!Number.isFinite(fontSize)||fontSize<=0||fontSize>18)fail2("authored font size must be positive and at most 18 points, below the 20 point sheet numbering");for(const character of new Set(text.match(/[A-Z0-9]/gu)??[])){const key=`${character}:${fontSize}:${weight}`;const measured=glyphCache.get(key)??glyphHeight(character,fontSize,weight);glyphCache.set(key,measured);if(glyphCache.size>4096)fail2("glyph measurement limit exceeded");minimum=Math.min(minimum,measured);if(measured+0.001<drawingMinimumGlyphHeightPt)fail2(`glyph ${character} has ${measured.toFixed(3)}pt ink height; minimum is ${drawingMinimumGlyphHeightPt.toFixed(3)}pt (3.2mm)`)}};for(const shape of spec.shapes){if(shape.tone!==undefined&&shape.tone!=="neutral")fail2("colored tones are unsupported; author monochrome relationships explicitly");if(shape.opacity!==undefined&&shape.opacity!==1)fail2("transparency is unsupported");if(shape.type==="rect"||shape.type==="ellipse"){if(shape.icon!==undefined)fail2("icons are unsupported");if((shape.strokeWidth??2)<0.5||(shape.strokeWidth??2)>4)fail2("stroke width must be 0.5 to 4 points");for(const row of layoutBoxContent(shape).rows)inspect(row.text,row.fontSize,row.weight,row.fontFamily)}else if(shape.type==="text")inspect(shape.text,shape.fontSize??24,shape.weight??500,shape.fontFamily);else if((shape.strokeWidth??3)<0.5||(shape.strokeWidth??3)>4)fail2("stroke width must be 0.5 to 4 points")}for(const edge of spec.edges??[]){if(edge.tone!==undefined&&edge.tone!=="neutral")fail2("colored edge tones are unsupported");if(edge.label!==undefined)inspect(edge.label,edge.labelFontSize??18,edge.labelWeight??600,edge.labelFontFamily)}return minimum}async function renderDrawing(input,sourceSha256){const source=parseDrawingSource(input);const sourceDigest=sourceSha256??sha256(JSON.stringify(source));if(!/^[a-f0-9]{64}$/u.test(sourceDigest))fail2("source SHA-256 is invalid");const geometry=drawingPageGeometry(source.paper);const sheets=[];const cache=new Map;let minGlyphHeightPt=Infinity;for(const sheet of source.sheets){const spec=parseDiagramSpec(sheet.diagram);if(spec.canvas.width>geometry.body.width+0.001||spec.canvas.height>geometry.body.height+0.001)fail2(`figure ${sheet.figure} canvas exceeds ${geometry.body.width.toFixed(3)} by ${geometry.body.height.toFixed(3)}pt body; no automatic scaling is performed`);minGlyphHeightPt=Math.min(minGlyphHeightPt,inspectLabels(spec,cache));const sourceSvg=await sceneSvg(spec);inside(bounds(renderer(sourceSvg)),{x:0,y:0,width:spec.canvas.width,height:spec.canvas.height},`figure ${sheet.figure}`);for(const shape of spec.shapes){if((shape.type==="rect"||shape.type==="ellipse")&&(shape.label!==undefined||shape.labelRows!==undefined)){const inset=(shape.strokeWidth??2)/2;const single=await sceneSvg({...spec,shapes:[shape],edges:[]});inside(bounds(renderer(single)),{x:shape.x-inset,y:shape.y-inset,width:shape.width+inset*2,height:shape.height+inset*2},`shape ${shape.id} label`)}}const diagramBody=sourceSvg.replace(/^<svg[^>]*>/u,"").replace(/<\/svg>$/u,"");const x=geometry.body.x+(geometry.body.width-spec.canvas.width)/2;const counter=`${sheet.figure}/${source.sheets.length}`;const figureLabel=source.sheets.length===1?"":`<text x="${geometry.width/2}" y="${geometry.height-geometry.margins.bottom-8}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">FIG. ${sheet.figure}</text>`;const page=`<svg xmlns="http://www.w3.org/2000/svg" width="${geometry.width}" height="${geometry.height}" viewBox="0 0 ${geometry.width} ${geometry.height}"><rect width="100%" height="100%" fill="#ffffff"/><text x="${geometry.width/2}" y="${geometry.margins.top+21}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">${counter}</text><g transform="translate(${x} ${geometry.body.y})">${diagramBody}</g>${figureLabel}</svg>`;const outlined=renderer(page).toString().replace(/width="[^"]+" height="[^"]+" viewBox="[^"]+"/u,`width="${geometry.width}pt" height="${geometry.height}pt" viewBox="0 0 ${geometry.width} ${geometry.height}"`);if(Buffer.byteLength(outlined)>2*1024*1024)fail2("sheet SVG exceeds output byte limit");sheets.push({svg:outlined,width:geometry.width,height:geometry.height,figure:sheet.figure})}for(const character of"FIG0123456789")minGlyphHeightPt=Math.min(minGlyphHeightPt,glyphHeight(character,20,400));if(minGlyphHeightPt+0.001<drawingMinimumGlyphHeightPt)fail2("sheet numbering falls below minimum glyph height");const checks={profile:drawingProfile,paper:source.paper,sheetCount:source.sheets.length,minGlyphHeightPt,findings:[]};return{sheets,checks,pdf:drawingSheetsPdf(sheets,{title:source.title??source.name,sourceSha256:sourceDigest,rendererVersion:SLOPCAMERA_VERSION})}}async function readDrawingFile(filePath){const absolutePath=resolve3(filePath);if(!absolutePath.endsWith(".drawing.json"))fail2("source filename must end in .drawing.json");const descriptor=await open(absolutePath,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);let bytes;try{const info=await descriptor.stat();if(!info.isFile())fail2("source must be a regular file");if(info.size>drawingSourceByteLimit)fail2("source exceeds 1MiB byte limit");const buffer=Buffer.alloc(drawingSourceByteLimit+1);let cursor=0;while(cursor<buffer.length){const result=await descriptor.read(buffer,cursor,buffer.length-cursor,cursor);if(result.bytesRead===0)break;cursor+=result.bytesRead}if(cursor>drawingSourceByteLimit)fail2("source exceeds 1MiB byte limit");bytes=buffer.subarray(0,cursor)}finally{await descriptor.close()}const raw=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));return{absolutePath,source:parseDrawingSource(raw),sourceSha256:sha256(bytes)}}async function checkDrawingFile(options){const{source,sourceSha256}=await readDrawingFile(options.filePath);return(await renderDrawing(source,sourceSha256)).checks}async function atomicWrite2(filePath,data){const temporary=`${filePath}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await writeFile2(temporary,data);await rename2(temporary,filePath)}catch(error){await rm2(temporary,{force:true});throw error}}async function renderDrawingFile(options){const{absolutePath,source,sourceSha256}=await readDrawingFile(options.filePath);const result=await renderDrawing(source,sourceSha256);const outDirectory=resolve3(options.outDirectory??dirname3(absolutePath));const artifacts={source:absolutePath,pdf:join2(outDirectory,`${source.name}.pdf`),sheets:result.sheets.map((_,index)=>join2(outDirectory,`${source.name}.sheet-${String(index+1).padStart(3,"0")}.svg`)),receipt:join2(outDirectory,`${source.name}.drawing-receipt.json`)};const receipt={version:1,profile:drawingProfile,rendererVersion:SLOPCAMERA_VERSION,sourceSha256,paper:source.paper,minGlyphHeightPt:result.checks.minGlyphHeightPt,sheets:result.sheets.map((sheet)=>({figure:sheet.figure,widthPt:sheet.width,heightPt:sheet.height,sha256:sha256(sheet.svg)})),pdfSha256:sha256(result.pdf)};await mkdir2(outDirectory,{recursive:true});for(const[index,sheet]of result.sheets.entries())await atomicWrite2(artifacts.sheets[index],sheet.svg);await atomicWrite2(artifacts.pdf,result.pdf);await atomicWrite2(artifacts.receipt,`${JSON.stringify(receipt,null,2)}
|
|
23
|
+
`);const bytes=Buffer.from(chunks.join(""));if(bytes.length>32*1024*1024)throw new Error("Drawing PDF exceeds output byte limit");return bytes}var SLOPCAMERA_VERSION="3.3.6";var drawingProfile="patent-line-art-v1";var drawingSourceByteLimit=1024*1024;var drawingMinimumGlyphHeightPt=3.2*72/25.4;class DrawingValidationError extends Error{constructor(message){super(`Invalid drawing source: ${message}`);this.name="DrawingValidationError"}}function fail2(message){throw new DrawingValidationError(message)}var sha256=(value)=>createHash("sha256").update(value).digest("hex");var assetPath=(asset)=>isAbsolute2(asset)?asset:fileURLToPath(new URL(asset,import.meta.url));var fontFiles=[assetPath(NebulaSans_Book_default),assetPath(NebulaSans_Bold_default)];var monochrome={background:"#ffffff",foreground:"#000000",muted:"#000000",stroke:"#000000",tones:Object.fromEntries(["neutral","blue","orange","green","red","purple","yellow"].map((tone)=>[tone,{fill:"#ffffff",stroke:"#000000",text:"#000000"}]))};var config={font:{family:"Nebula Sans",files:[{path:fontFiles[0],weight:400},{path:fontFiles[1],weight:700}]},theme:{light:monochrome}};var escapeXml=(value)=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""");function drawingPageGeometry(paper){if(paper!=="us-letter"&&paper!=="a4")fail2("paper must be us-letter or a4");const width=paper==="us-letter"?612:210*72/25.4;const height=paper==="us-letter"?792:297*72/25.4;const margins={left:25*72/25.4,top:25*72/25.4,right:15*72/25.4,bottom:10*72/25.4};return{width,height,margins,numberingHeight:30,body:{x:margins.left,y:margins.top+30,width:width-margins.left-margins.right,height:height-margins.top-margins.bottom-60}}}function record(value,keys,at){if(typeof value!=="object"||value===null||Array.isArray(value))fail2(`${at} must be an object`);const result=value;for(const key of Object.keys(result))if(!keys.includes(key))fail2(`${at}.${key} is unsupported`);return result}function checkDiagramEnvelope(value){const diagram=record(value,["$schema","version","name","canvas","layout","shapes","edges"],"diagram");const bounded=(object)=>{for(const value2 of Object.values(object)){if(typeof value2==="number"&&(!Number.isFinite(value2)||Math.abs(value2)>1e4))fail2("numeric drawing values must be finite and within 10000 points");if(typeof value2==="string"&&value2.length>1024)fail2("drawing strings exceed the bounded text limit")}};bounded(diagram);bounded(record(diagram.canvas,["width","height","padding"],"canvas"));if(diagram.layout!==undefined)bounded(record(diagram.layout,["type","direction","gap","align"],"layout"));if(!Array.isArray(diagram.shapes)||diagram.shapes.length<1||diagram.shapes.length>100)fail2("each sheet needs 1 to 100 shapes");for(const value2 of diagram.shapes){const shape=record(value2,["id","type","x","y","tone","opacity","width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap","text","fontSize","fontFamily","weight","align","x2","y2"],"shape");bounded(shape);const common=["id","type","x","y","tone","opacity"];const extras=shape.type==="text"?["text","width","fontSize","fontFamily","weight","align"]:shape.type==="line"?["x2","y2","strokeWidth"]:["width","height","radius","icon","iconSize","strokeWidth","fill","label","labelFontSize","labelFontFamily","labelWeight","labelRows","labelRowGap"];record(value2,[...common,...extras],"shape");if(shape.labelRows!==undefined){if(!Array.isArray(shape.labelRows)||shape.labelRows.length>4)fail2("labelRows must be bounded");for(const row of shape.labelRows)bounded(record(row,["text","fontSize","fontFamily","weight"],"label row"))}for(const key of["label","text"])if(typeof shape[key]==="string"&&shape[key].length>500)fail2("label exceeds text limit")}if(diagram.edges!==undefined){if(!Array.isArray(diagram.edges)||diagram.edges.length>150)fail2("at most 150 edges are supported");for(const edge of diagram.edges)bounded(record(edge,["id","from","to","label","tone","start","end","bend","arrowhead","startPosition","endPosition","labelFontSize","labelFontFamily","labelWeight","labelPosition","labelOffset"],"edge"))}}function parseDrawingSource(value){const raw=record(value,["$schema","version","name","title","paper","sheets"],"drawing");if(raw.version!==1)fail2("version must be 1");if(typeof raw.name!=="string"||raw.name.length>100||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(raw.name))fail2("name must be a bounded lowercase hyphenated name");if(raw.paper!=="us-letter"&&raw.paper!=="a4")fail2("paper must be us-letter or a4");if(raw.title!==undefined&&(typeof raw.title!=="string"||raw.title.length<1||Buffer.byteLength(raw.title)>1024||/[\u0000-\u001f]/u.test(raw.title)))fail2("title must be a bounded metadata string");if(raw.$schema!==undefined&&typeof raw.$schema!=="string")fail2("$schema must be a string");if(!Array.isArray(raw.sheets)||raw.sheets.length<1||raw.sheets.length>20)fail2("sheets must contain 1 to 20 sheets");const sheets=raw.sheets.map((sheet,index)=>{const entry=record(sheet,["figure","diagram"],`sheets[${index}]`);if(entry.figure!==index+1)fail2("figure numbers must be consecutive beginning at 1");checkDiagramEnvelope(entry.diagram);const diagram=parseDiagramSource(entry.diagram);const spec=parseDiagramSpec(diagram);if(spec.shapes.length<1||spec.shapes.length>100||(spec.edges?.length??0)>150)fail2("each sheet needs 1 to 100 shapes and at most 150 edges");return{figure:index+1,diagram}});const source={version:1,name:raw.name,paper:raw.paper,sheets,...raw.title===undefined?{}:{title:raw.title},...raw.$schema===undefined?{}:{$schema:raw.$schema}};if(Buffer.byteLength(JSON.stringify(source))>drawingSourceByteLimit)fail2("source exceeds 1MiB byte limit");return source}function renderer(svg){return new Resvg(svg,{font:{fontFiles,loadSystemFonts:false,defaultFontFamily:"Nebula Sans"},logLevel:"off"})}function bounds(engine){const box=engine.getBBox();if(box===undefined)fail2("empty drawing ink");return{x:box.x,y:box.y,width:box.width,height:box.height}}function inside(ink,box,label){const epsilon=0.01;if(ink.x<box.x-epsilon||ink.y<box.y-epsilon||ink.x+ink.width>box.x+box.width+epsilon||ink.y+ink.height>box.y+box.height+epsilon)fail2(`${label} ink extends beyond its bounds`)}async function sceneSvg(spec){return(await renderSvg(spec,"light",config,{edgeStrokeWidth:1})).svg.replace('<rect width="100%" height="100%" fill="#ffffff"/>',"")}function glyphHeight(character,fontSize,weight){const svg=`<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><text x="100" y="500" font-family="Nebula Sans" font-size="${fontSize}" font-weight="${weight}">${escapeXml(character)}</text></svg>`;return bounds(renderer(svg)).height}function inspectLabels(spec,glyphCache){let minimum=Infinity;const inspect=(text,fontSize,weight,family)=>{if(text.length<1||text.length>500||!Array.from(text).every((character)=>/^[A-Z0-9 \n]$/u.test(character)||".,:;()[]/+=_*'!?%-".includes(character)))fail2("visible labels must be uppercase ASCII letters, numbers, spaces, or supported punctuation; labels are never rewritten");if(family!==undefined&&family!=="default")fail2("only the bundled default font is supported");if(!Number.isFinite(fontSize)||fontSize<=0||fontSize>18)fail2("authored font size must be positive and at most 18 points, below the 20 point sheet numbering");for(const character of new Set(text.match(/[A-Z0-9]/gu)??[])){const key=`${character}:${fontSize}:${weight}`;const measured=glyphCache.get(key)??glyphHeight(character,fontSize,weight);glyphCache.set(key,measured);if(glyphCache.size>4096)fail2("glyph measurement limit exceeded");minimum=Math.min(minimum,measured);if(measured+0.001<drawingMinimumGlyphHeightPt)fail2(`glyph ${character} has ${measured.toFixed(3)}pt ink height; minimum is ${drawingMinimumGlyphHeightPt.toFixed(3)}pt (3.2mm)`)}};for(const shape of spec.shapes){if(shape.tone!==undefined&&shape.tone!=="neutral")fail2("colored tones are unsupported; author monochrome relationships explicitly");if(shape.opacity!==undefined&&shape.opacity!==1)fail2("transparency is unsupported");if(shape.type==="rect"||shape.type==="ellipse"){if(shape.icon!==undefined)fail2("icons are unsupported");if((shape.strokeWidth??2)<0.5||(shape.strokeWidth??2)>4)fail2("stroke width must be 0.5 to 4 points");for(const row of layoutBoxContent(shape).rows)inspect(row.text,row.fontSize,row.weight,row.fontFamily)}else if(shape.type==="text")inspect(shape.text,shape.fontSize??24,shape.weight??500,shape.fontFamily);else if((shape.strokeWidth??3)<0.5||(shape.strokeWidth??3)>4)fail2("stroke width must be 0.5 to 4 points")}for(const edge of spec.edges??[]){if(edge.tone!==undefined&&edge.tone!=="neutral")fail2("colored edge tones are unsupported");if(edge.label!==undefined)inspect(edge.label,edge.labelFontSize??18,edge.labelWeight??600,edge.labelFontFamily)}return minimum}async function renderDrawing(input,sourceSha256){const source=parseDrawingSource(input);const sourceDigest=sourceSha256??sha256(JSON.stringify(source));if(!/^[a-f0-9]{64}$/u.test(sourceDigest))fail2("source SHA-256 is invalid");const geometry=drawingPageGeometry(source.paper);const sheets=[];const cache=new Map;let minGlyphHeightPt=Infinity;for(const sheet of source.sheets){const spec=parseDiagramSpec(sheet.diagram);if(spec.canvas.width>geometry.body.width+0.001||spec.canvas.height>geometry.body.height+0.001)fail2(`figure ${sheet.figure} canvas exceeds ${geometry.body.width.toFixed(3)} by ${geometry.body.height.toFixed(3)}pt body; no automatic scaling is performed`);minGlyphHeightPt=Math.min(minGlyphHeightPt,inspectLabels(spec,cache));const sourceSvg=await sceneSvg(spec);inside(bounds(renderer(sourceSvg)),{x:0,y:0,width:spec.canvas.width,height:spec.canvas.height},`figure ${sheet.figure}`);for(const shape of spec.shapes){if((shape.type==="rect"||shape.type==="ellipse")&&(shape.label!==undefined||shape.labelRows!==undefined)){const inset=(shape.strokeWidth??2)/2;const single=await sceneSvg({...spec,shapes:[shape],edges:[]});inside(bounds(renderer(single)),{x:shape.x-inset,y:shape.y-inset,width:shape.width+inset*2,height:shape.height+inset*2},`shape ${shape.id} label`)}}const diagramBody=sourceSvg.replace(/^<svg[^>]*>/u,"").replace(/<\/svg>$/u,"");const x=geometry.body.x+(geometry.body.width-spec.canvas.width)/2;const counter=`${sheet.figure}/${source.sheets.length}`;const figureLabel=source.sheets.length===1?"":`<text x="${geometry.width/2}" y="${geometry.height-geometry.margins.bottom-8}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">FIG. ${sheet.figure}</text>`;const page=`<svg xmlns="http://www.w3.org/2000/svg" width="${geometry.width}" height="${geometry.height}" viewBox="0 0 ${geometry.width} ${geometry.height}"><rect width="100%" height="100%" fill="#ffffff"/><text x="${geometry.width/2}" y="${geometry.margins.top+21}" text-anchor="middle" font-size="20" font-family="Nebula Sans" font-weight="400">${counter}</text><g transform="translate(${x} ${geometry.body.y})">${diagramBody}</g>${figureLabel}</svg>`;const outlined=renderer(page).toString().replace(/width="[^"]+" height="[^"]+" viewBox="[^"]+"/u,`width="${geometry.width}pt" height="${geometry.height}pt" viewBox="0 0 ${geometry.width} ${geometry.height}"`);if(Buffer.byteLength(outlined)>2*1024*1024)fail2("sheet SVG exceeds output byte limit");sheets.push({svg:outlined,width:geometry.width,height:geometry.height,figure:sheet.figure})}for(const character of"FIG0123456789")minGlyphHeightPt=Math.min(minGlyphHeightPt,glyphHeight(character,20,400));if(minGlyphHeightPt+0.001<drawingMinimumGlyphHeightPt)fail2("sheet numbering falls below minimum glyph height");const checks={profile:drawingProfile,paper:source.paper,sheetCount:source.sheets.length,minGlyphHeightPt,findings:[]};return{sheets,checks,pdf:drawingSheetsPdf(sheets,{title:source.title??source.name,sourceSha256:sourceDigest,rendererVersion:SLOPCAMERA_VERSION})}}async function readDrawingFile(filePath){const absolutePath=resolve3(filePath);if(!absolutePath.endsWith(".drawing.json"))fail2("source filename must end in .drawing.json");const descriptor=await open(absolutePath,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);let bytes;try{const info=await descriptor.stat();if(!info.isFile())fail2("source must be a regular file");if(info.size>drawingSourceByteLimit)fail2("source exceeds 1MiB byte limit");const buffer=Buffer.alloc(drawingSourceByteLimit+1);let cursor=0;while(cursor<buffer.length){const result=await descriptor.read(buffer,cursor,buffer.length-cursor,cursor);if(result.bytesRead===0)break;cursor+=result.bytesRead}if(cursor>drawingSourceByteLimit)fail2("source exceeds 1MiB byte limit");bytes=buffer.subarray(0,cursor)}finally{await descriptor.close()}const raw=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));return{absolutePath,source:parseDrawingSource(raw),sourceSha256:sha256(bytes)}}async function checkDrawingFile(options){const{source,sourceSha256}=await readDrawingFile(options.filePath);return(await renderDrawing(source,sourceSha256)).checks}async function atomicWrite2(filePath,data){const temporary=`${filePath}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await writeFile2(temporary,data);await rename2(temporary,filePath)}catch(error){await rm2(temporary,{force:true});throw error}}async function renderDrawingFile(options){const{absolutePath,source,sourceSha256}=await readDrawingFile(options.filePath);const result=await renderDrawing(source,sourceSha256);const outDirectory=resolve3(options.outDirectory??dirname3(absolutePath));const artifacts={source:absolutePath,pdf:join2(outDirectory,`${source.name}.pdf`),sheets:result.sheets.map((_,index)=>join2(outDirectory,`${source.name}.sheet-${String(index+1).padStart(3,"0")}.svg`)),receipt:join2(outDirectory,`${source.name}.drawing-receipt.json`)};const receipt={version:1,profile:drawingProfile,rendererVersion:SLOPCAMERA_VERSION,sourceSha256,paper:source.paper,minGlyphHeightPt:result.checks.minGlyphHeightPt,sheets:result.sheets.map((sheet)=>({figure:sheet.figure,widthPt:sheet.width,heightPt:sheet.height,sha256:sha256(sheet.svg)})),pdfSha256:sha256(result.pdf)};await mkdir2(outDirectory,{recursive:true});for(const[index,sheet]of result.sheets.entries())await atomicWrite2(artifacts.sheets[index],sheet.svg);await atomicWrite2(artifacts.pdf,result.pdf);await atomicWrite2(artifacts.receipt,`${JSON.stringify(receipt,null,2)}
|
|
24
24
|
`);return{artifacts,checks:result.checks,receipt}}function starterDrawingSource(){return{$schema:"https://raw.githubusercontent.com/hraness/slopcamera/main/schema/drawing.schema.json",version:1,name:"sensor-control",title:"Fictional sensor and controller drawings",paper:"us-letter",sheets:[{figure:1,diagram:{version:1,name:"sensor-system",canvas:{width:480,height:500},shapes:[{id:"sensor",type:"rect",x:105,y:40,width:280,height:100,radius:0,label:"SENSOR 100",labelFontSize:16},{id:"controller",type:"rect",x:105,y:280,width:280,height:100,radius:0,label:"CONTROLLER 200",labelFontSize:16}],edges:[{id:"signal",from:"sensor",to:"controller",label:"SIGNAL",labelFontSize:16}]}},{figure:2,diagram:{version:1,name:"control-flow",canvas:{width:480,height:500},shapes:[{id:"receive",type:"rect",x:105,y:40,width:280,height:100,radius:0,label:"RECEIVE SIGNAL 210",labelFontSize:16},{id:"actuate",type:"rect",x:105,y:280,width:280,height:100,radius:0,label:"SET OUTPUT 220",labelFontSize:16}],edges:[{id:"next",from:"receive",to:"actuate"}]}}]}}import{rename as rename3,rm as rm3,writeFile as writeFile3}from"fs/promises";import{dirname as dirname5,join as join4}from"path";import{open as open2,mkdir as mkdir3,realpath,stat}from"fs/promises";import{basename as basename2,dirname as dirname4,isAbsolute as isAbsolute3,join as join3,relative,resolve as resolve4,win32}from"path";var mcpSourceByteLimit=1024*1024;class WorkspaceBoundaryError extends Error{code;constructor(code,message){super(message);this.name="WorkspaceBoundaryError";this.code=code}}function filesystemCode(error){if(typeof error==="object"&&error!==null&&"code"in error&&typeof error.code==="string"){return error.code}return}function normalizeRelativePath(value,options){if(value.length===0||value.includes("\x00")){throw new WorkspaceBoundaryError("INVALID_PATH","Path must be a non-empty root-relative path.")}if(isAbsolute3(value)||win32.isAbsolute(value)||/^[A-Za-z]:/.test(value)){throw new WorkspaceBoundaryError("INVALID_PATH","Absolute paths are not allowed.")}const segments=value.split(/[\\/]/).filter((segment)=>segment!==""&&segment!==".");if(segments.includes("..")){throw new WorkspaceBoundaryError("INVALID_PATH","Parent-directory traversal is not allowed.")}if(segments.length===0){if(!options.allowRoot){throw new WorkspaceBoundaryError("INVALID_PATH","Path must identify a file below the root.")}return{native:".",portable:"."}}return{native:segments.join("/"),portable:segments.join("/")}}function isConfined(rootDirectory,target){const fromRoot=relative(rootDirectory,target);return fromRoot===""||!fromRoot.startsWith("..")&&!isAbsolute3(fromRoot)}async function readUtf8WithCap(filePath,sourceLabel){let handle;try{handle=await open2(filePath,"r");const metadata=await handle.stat();if(!metadata.isFile()){throw new WorkspaceBoundaryError("SOURCE_NOT_FILE",`${sourceLabel} must be a regular file.`)}if(metadata.size>mcpSourceByteLimit){throw new WorkspaceBoundaryError("SOURCE_TOO_LARGE",`${sourceLabel} exceeds the ${mcpSourceByteLimit}-byte limit.`)}const buffer=Buffer.allocUnsafe(mcpSourceByteLimit+1);let bytesRead=0;while(bytesRead<=mcpSourceByteLimit){const next=await handle.read(buffer,bytesRead,mcpSourceByteLimit+1-bytesRead,null);if(next.bytesRead===0)break;bytesRead+=next.bytesRead}if(bytesRead>mcpSourceByteLimit){throw new WorkspaceBoundaryError("SOURCE_TOO_LARGE",`${sourceLabel} exceeds the ${mcpSourceByteLimit}-byte limit.`)}try{return new TextDecoder("utf-8",{fatal:true}).decode(buffer.subarray(0,bytesRead))}catch{throw new WorkspaceBoundaryError("SOURCE_ENCODING",`${sourceLabel} must contain valid UTF-8.`)}}catch(error){if(error instanceof WorkspaceBoundaryError)throw error;const code=filesystemCode(error);if(code==="ENOENT"){throw new WorkspaceBoundaryError("SOURCE_NOT_FOUND",`${sourceLabel} does not exist.`)}throw new WorkspaceBoundaryError("FILESYSTEM_ERROR",`${sourceLabel} could not be read.`)}finally{await handle?.close()}}class WorkspaceBoundary{rootDirectory;constructor(rootDirectory){this.rootDirectory=rootDirectory}static async create(rootDirectory){let resolvedRoot;try{resolvedRoot=await realpath(resolve4(rootDirectory));if(!(await stat(resolvedRoot)).isDirectory()){throw new WorkspaceBoundaryError("OUTPUT_NOT_DIRECTORY","MCP root must be a directory.")}}catch(error){if(error instanceof WorkspaceBoundaryError)throw error;throw new WorkspaceBoundaryError("FILESYSTEM_ERROR","MCP root could not be opened.")}return new WorkspaceBoundary(resolvedRoot)}assertConfined(target){if(!isConfined(this.rootDirectory,target)){throw new WorkspaceBoundaryError("PATH_OUTSIDE_ROOT","Path resolves outside the MCP root.")}}toRelativePath(absolutePath){this.assertConfined(absolutePath);const fromRoot=relative(this.rootDirectory,absolutePath);return fromRoot===""?".":fromRoot.split("\\").join("/")}async readSource(value,sourceLabel="Diagram source"){const normalized=normalizeRelativePath(value,{allowRoot:false});const lexicalPath=resolve4(this.rootDirectory,normalized.native);this.assertConfined(lexicalPath);let canonicalPath;try{canonicalPath=await realpath(lexicalPath)}catch(error){if(filesystemCode(error)==="ENOENT"){throw new WorkspaceBoundaryError("SOURCE_NOT_FOUND",`${sourceLabel} does not exist.`)}throw new WorkspaceBoundaryError("FILESYSTEM_ERROR",`${sourceLabel} could not be resolved.`)}this.assertConfined(canonicalPath);return{absolutePath:canonicalPath,relativePath:this.toRelativePath(canonicalPath),text:await readUtf8WithCap(canonicalPath,sourceLabel)}}async resolveInputFile(value,maximumBytes){const normalized=normalizeRelativePath(value,{allowRoot:false});const lexicalPath=resolve4(this.rootDirectory,normalized.native);this.assertConfined(lexicalPath);let canonicalPath;try{canonicalPath=await realpath(lexicalPath);this.assertConfined(canonicalPath);const metadata=await stat(canonicalPath);if(!metadata.isFile()){throw new WorkspaceBoundaryError("SOURCE_NOT_FILE","Input must be a regular file.")}if(!Number.isSafeInteger(maximumBytes)||maximumBytes<1||metadata.size>maximumBytes){throw new WorkspaceBoundaryError("SOURCE_TOO_LARGE",`Input exceeds the ${maximumBytes}-byte limit.`)}}catch(error){if(error instanceof WorkspaceBoundaryError)throw error;if(filesystemCode(error)==="ENOENT"){throw new WorkspaceBoundaryError("SOURCE_NOT_FOUND","Input does not exist.")}throw new WorkspaceBoundaryError("FILESYSTEM_ERROR","Input could not be resolved.")}return{absolutePath:canonicalPath,relativePath:this.toRelativePath(canonicalPath)}}async prepareOutputFile(value){const normalized=normalizeRelativePath(value,{allowRoot:false});const fileName=basename2(normalized.native);if(fileName==="."||fileName===".."||fileName.length===0){throw new WorkspaceBoundaryError("INVALID_PATH","Output path must identify a file below the root.")}const directory=await this.prepareOutputDirectory(dirname4(normalized.native));const absolutePath=join3(directory.absolutePath,fileName);this.assertConfined(absolutePath);return{absolutePath,relativePath:this.toRelativePath(absolutePath)}}async prepareOutputDirectory(value){const normalized=normalizeRelativePath(value,{allowRoot:true});const lexicalPath=resolve4(this.rootDirectory,normalized.native);this.assertConfined(lexicalPath);let ancestor=lexicalPath;for(;;){try{const canonicalAncestor=await realpath(ancestor);this.assertConfined(canonicalAncestor);break}catch(error){if(error instanceof WorkspaceBoundaryError)throw error;if(filesystemCode(error)!=="ENOENT"){throw new WorkspaceBoundaryError("FILESYSTEM_ERROR","Output directory could not be resolved.")}const parent=dirname4(ancestor);if(parent===ancestor){throw new WorkspaceBoundaryError("PATH_OUTSIDE_ROOT","Output directory resolves outside the MCP root.")}ancestor=parent}}try{await mkdir3(lexicalPath,{recursive:true});const canonicalPath=await realpath(lexicalPath);this.assertConfined(canonicalPath);if(!(await stat(canonicalPath)).isDirectory()){throw new WorkspaceBoundaryError("OUTPUT_NOT_DIRECTORY","Output path must be a directory.")}return{absolutePath:canonicalPath,relativePath:this.toRelativePath(canonicalPath)}}catch(error){if(error instanceof WorkspaceBoundaryError)throw error;throw new WorkspaceBoundaryError("FILESYSTEM_ERROR","Output directory could not be created.")}}}var mcpMaximumScale=4;var mcpMaximumRenderedPixels=16777216;var mcpMaximumShapes=64;var mcpMaximumEdges=128;var mcpMaximumReturnedFindings=40;var mcpMaximumReturnedEntities=256;var mcpMaximumReturnedAuditSamples=8192;var mcpMaximumReturnedDiffEntries=1024;var defaultScale=2;var maximumShapeIdsPerFinding=12;var builtInConfig=Object.freeze({icons:builtInIcons});var findingSchema={type:"object",additionalProperties:false,required:["code","message","shapeIds"],properties:{code:{type:"string"},message:{type:"string"},shapeIds:{type:"array",items:{type:"string"}}}};var scenePathSchema={type:"string",description:"Root-relative path to a spatial scene JSON source (1 MiB maximum)."};var sceneCameraIdSchema={type:"string",maxLength:128,pattern:"^camera_[a-zA-Z0-9][a-zA-Z0-9_-]*$",description:"Identifier of a camera declared by the scene (camera_\u2026)."};var entityTruncationSummarySchema={type:"object",additionalProperties:false,required:["entityCount","returnedEntityCount","entitiesTruncated"],properties:{entityCount:{type:"integer",minimum:0},returnedEntityCount:{type:"integer",minimum:0},entitiesTruncated:{type:"boolean"}}};function deepFreeze(value){if(typeof value!=="object"||value===null||Object.isFrozen(value)){return value}for(const nested of Object.values(value))deepFreeze(nested);return Object.freeze(value)}var slopcameraMcpTools=deepFreeze([{name:"check_diagram",title:"Check diagram",description:"Parse and lint one root-relative Slopcamera diagram source without changing files. Uses only built-in icons and themes.",inputSchema:{type:"object",additionalProperties:false,required:["path"],properties:{path:{type:"string",description:"Root-relative path to a diagram JSON source (1 MiB maximum)."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","findings","summary"],properties:{ok:{const:true},source:{type:"string"},findings:{type:"array",items:findingSchema},summary:{type:"object",additionalProperties:false,required:["shapeCount","edgeCount","findingCount","returnedFindingCount","findingsTruncated"],properties:{shapeCount:{type:"integer",minimum:0},edgeCount:{type:"integer",minimum:0},findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"}}}}},annotations:{title:"Check diagram",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"render_diagram",title:"Render diagram",description:"Render one root-relative Slopcamera diagram source with built-in icons and themes, overwriting its paired .tldr, light/dark SVG, and light/dark PNG artifacts.",inputSchema:{type:"object",additionalProperties:false,required:["path"],properties:{path:{type:"string",description:"Root-relative path to a diagram JSON source (1 MiB maximum)."},out_dir:{type:"string",description:"Optional root-relative output directory. Defaults to the source directory."},scale:{type:"number",exclusiveMinimum:0,maximum:mcpMaximumScale,default:defaultScale,description:"PNG scale. The scaled canvas may contain at most 16,777,216 pixels."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","scale","findings","artifacts","summary"],properties:{ok:{const:true},source:{type:"string"},scale:{type:"number"},findings:{type:"array",items:findingSchema},artifacts:{type:"object",additionalProperties:false,required:["tldr","lightSvg","darkSvg","lightPng","darkPng"],properties:{tldr:{type:"string"},lightSvg:{type:"string"},darkSvg:{type:"string"},lightPng:{type:"string"},darkPng:{type:"string"}}},summary:{type:"object",additionalProperties:false,required:["shapeCount","edgeCount","findingCount","returnedFindingCount","findingsTruncated"],properties:{shapeCount:{type:"integer",minimum:0},edgeCount:{type:"integer",minimum:0},findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"}}}}},annotations:{title:"Render diagram",readOnlyHint:false,destructiveHint:true,idempotentHint:true,openWorldHint:false}},{name:"search_slopcamera",title:"Search Slopcamera operations",description:"Search the fixed semantic Slopcamera operation registry by bounded text. This never executes code or changes files.",inputSchema:{type:"object",additionalProperties:false,properties:{query:{type:"string",maxLength:200,description:"Optional terms matched against operation codes and descriptions."},limit:{type:"integer",minimum:1,maximum:20,default:4}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","operations"],properties:{ok:{const:true},operations:{type:"array",maxItems:20,items:{type:"object",required:["code","title","description","execution","authentication","inputSchema"]}}}},annotations:{title:"Search Slopcamera operations",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"execute_slopcamera",title:"Execute Slopcamera operation",description:"Execute one exact operation code with typed JSON input. Never accepts or evaluates source code. Local paths remain confined to the configured workspace root.",inputSchema:{type:"object",additionalProperties:false,required:["operation","input"],properties:{operation:{type:"string",enum:slopcameraOperationCodes},input:{type:"object",description:"Typed input matching the selected operation's registry schema."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","operation","result"],properties:{ok:{const:true},operation:{type:"string",enum:slopcameraOperationCodes},result:{type:"object"}}},annotations:{title:"Execute Slopcamera operation",readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:true}},{name:"check_scene",title:"Check scene",description:"Parse and validate one root-relative Slopcamera spatial scene JSON source without changing files.",inputSchema:{type:"object",additionalProperties:false,required:["path"],properties:{path:scenePathSchema}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","sceneId","sceneSha256","summary"],properties:{ok:{const:true},source:{type:"string"},sceneId:{type:"string"},sceneSha256:{type:"string"},summary:{type:"object",additionalProperties:false,required:["durationUs","entityCount","cameraCount","assetCount","animationCount","generatorCount","overrideCount"],properties:{durationUs:{type:"integer",minimum:0},entityCount:{type:"integer",minimum:0},cameraCount:{type:"integer",minimum:0},assetCount:{type:"integer",minimum:0},animationCount:{type:"integer",minimum:0},generatorCount:{type:"integer",minimum:0},overrideCount:{type:"integer",minimum:0}}}}},annotations:{title:"Check scene",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"inspect_scene",title:"Inspect scene",description:"Snapshot one root-relative spatial scene's entities, editable controls, placements, assets, and generators without changing files.",inputSchema:{type:"object",additionalProperties:false,required:["path"],properties:{path:scenePathSchema}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","inspection","summary"],properties:{ok:{const:true},source:{type:"string"},inspection:{type:"object"},summary:entityTruncationSummarySchema}},annotations:{title:"Inspect scene",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"audit_scene",title:"Audit scene",description:"Sample one root-relative spatial scene against a camera and report per-entity geometric coverage, visibility findings, and bounds gaps. Optional asset_bounds accepts a Record<assetId,{min,max}> map, a slopcamera.spatial-asset-admission document, a {manifest,facts} pair, or an array of those.",inputSchema:{type:"object",additionalProperties:false,required:["path","camera_id"],properties:{path:scenePathSchema,camera_id:sceneCameraIdSchema,times_us:{type:"array",items:{type:"integer",minimum:0,maximum:SPATIAL_SCENE_LIMITS.durationUs},minItems:1,maxItems:SPATIAL_AUDIT_LIMITS.samples,description:"Optional sample times in microseconds. Defaults to evenly spaced coverage of the scene duration."},asset_bounds:{description:"Optional decoded scene-space asset bounds: a Record<assetId,{min,max}> map, a slopcamera.spatial-asset-admission document, a {manifest,facts} pair, or an array of those documents."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","report","summary"],properties:{ok:{const:true},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:false,required:["findingCount","returnedFindingCount","findingsTruncated","entityCount","returnedEntityCount","entitiesTruncated"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},entityCount:{type:"integer",minimum:0},returnedEntityCount:{type:"integer",minimum:0},entitiesTruncated:{type:"boolean"}}}}},annotations:{title:"Audit scene",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"diff_scenes",title:"Diff scenes",description:"Compare two root-relative spatial scene JSON sources and report added, removed, and changed collection entries without changing files.",inputSchema:{type:"object",additionalProperties:false,required:["path","other"],properties:{path:scenePathSchema,other:{type:"string",description:"Root-relative path to the second spatial scene JSON source (1 MiB maximum)."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","other","sceneSha256","otherSha256","diff","summary"],properties:{ok:{const:true},source:{type:"string"},other:{type:"string"},sceneSha256:{type:"string"},otherSha256:{type:"string"},diff:{type:"array"},summary:{type:"object",additionalProperties:false,required:["entryCount","returnedEntryCount","diffTruncated"],properties:{entryCount:{type:"integer",minimum:0},returnedEntryCount:{type:"integer",minimum:0},diffTruncated:{type:"boolean"}}}}},annotations:{title:"Diff scenes",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"evaluate_scene",title:"Evaluate scene",description:"Evaluate one root-relative spatial scene at one camera and integer microsecond time into an immutable snapshot without changing files.",inputSchema:{type:"object",additionalProperties:false,required:["path","camera_id","time_us"],properties:{path:scenePathSchema,camera_id:sceneCameraIdSchema,time_us:{type:"integer",minimum:0,maximum:SPATIAL_SCENE_LIMITS.durationUs,description:"Evaluation time in integer microseconds."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","snapshot","summary"],properties:{ok:{const:true},source:{type:"string"},snapshot:{type:"object"},summary:entityTruncationSummarySchema}},annotations:{title:"Evaluate scene",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"check_scene_direction",title:"Check scene direction",description:"Validate one authored direction document against one root-relative spatial scene: stale project digests, unresolved entity references, and intervals outside scene duration report as errors without compiling or changing files.",inputSchema:{type:"object",additionalProperties:false,required:["scene","direction"],properties:{scene:{...scenePathSchema,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},direction:{type:"string",description:"Root-relative path to the slopcamera.spatial-direction JSON document."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","report","summary"],properties:{ok:{const:true},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:false,required:["findingCount","returnedFindingCount","findingsTruncated","errorCount","warningCount"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},errorCount:{type:"integer",minimum:0},warningCount:{type:"integer",minimum:0}}}}},annotations:{title:"Check scene direction",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"plan_scene_direction",title:"Plan scene direction",description:"Compile one authored direction document into a deterministic, unverified proposal document \u2014 performance actions, camera rigs, shots and looks bound to the actual scene digest. Proposals are advisory only; nothing is applied to the scene.",inputSchema:{type:"object",additionalProperties:false,required:["scene","direction"],properties:{scene:{...scenePathSchema,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},direction:{type:"string",description:"Root-relative path to the slopcamera.spatial-direction JSON document."},camera_id:{...sceneCameraIdSchema,description:"Optional camera used to resolve coverage; defaults to the sole or first sorted scene camera."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","compilation","summary"],properties:{ok:{const:true},source:{type:"string"},compilation:{type:"object"},summary:{type:"object",additionalProperties:false,required:["advisoryCount","unresolvedIntentCount","proposalCounts"],properties:{advisoryCount:{type:"integer",minimum:0},unresolvedIntentCount:{type:"integer",minimum:0},proposalCounts:{type:"object",additionalProperties:false,required:["performance","cameraRigs","shots","lookIntents"],properties:{performance:{type:"integer",minimum:0},cameraRigs:{type:"integer",minimum:0},shots:{type:"integer",minimum:0},lookIntents:{type:"integer",minimum:0}}}}}}},annotations:{title:"Plan scene direction",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"plan_scene_gallery",title:"Plan scene gallery",description:"Compile a bounded set of single-axis direction variants into separate content-addressed candidate compilations plus a preview-reel plan. The planner never selects or promotes a candidate.",inputSchema:{type:"object",additionalProperties:false,required:["scene","direction","axis"],properties:{scene:{...scenePathSchema,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},direction:{type:"string",description:"Root-relative path to the slopcamera.spatial-direction JSON document."},axis:{type:"string",enum:[...SpatialGalleryAxisSchema.options],description:"Variation axis for the bounded candidate set."},camera_id:{...sceneCameraIdSchema,description:"Optional camera used to resolve coverage."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","gallery","summary"],properties:{ok:{const:true},source:{type:"string"},gallery:{type:"object"},summary:{type:"object",additionalProperties:false,required:["axis","candidateCount","selected"],properties:{axis:{type:"string"},candidateCount:{type:"integer",minimum:0},selected:{const:false}}}}},annotations:{title:"Plan scene gallery",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"check_scene_effects",title:"Check scene effects",description:"Validate one slopcamera.spatial-render-effects document or {document, documentSha256} binding against one scene: scene-digest bindings, entity and asset closure, and nested plan/particle/simulation digests report as findings before any host work.",inputSchema:{type:"object",additionalProperties:false,required:["scene","effects"],properties:{scene:{...scenePathSchema,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},effects:{type:"string",description:"Root-relative path to the render-effects document or binding JSON."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","report","summary"],properties:{ok:{const:true},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:false,required:["findingCount","returnedFindingCount","findingsTruncated","errorCount","warningCount"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},errorCount:{type:"integer",minimum:0},warningCount:{type:"integer",minimum:0}}}}},annotations:{title:"Check scene effects",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"plan_scene_effects",title:"Plan scene effects",description:"Assemble a canonical {document, documentSha256} render-effects binding for one scene from a draft JSON naming renderPlan, particleSystems and simulationBakes. Entity and asset closure rejects before the document is formed; the scene digest binds here, never by caller assertion.",inputSchema:{type:"object",additionalProperties:false,required:["scene","draft"],properties:{scene:{...scenePathSchema,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},draft:{type:"string",description:"Root-relative path to the effects draft JSON ({renderPlan, particleSystems?, simulationBakes?})."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","binding","summary"],properties:{ok:{const:true},source:{type:"string"},binding:{type:"object"},summary:{type:"object",additionalProperties:false,required:["documentSha256","particleSystemCount","simulationBakeCount"],properties:{documentSha256:{type:"string"},particleSystemCount:{type:"integer",minimum:0},simulationBakeCount:{type:"integer",minimum:0}}}}},annotations:{title:"Plan scene effects",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"check_scene_behavior",title:"Check scene behavior",description:"Validate one slopcamera.spatial-behavior document against one scene: bake-safe organism profile (input/const/fn/repeat/each/organism cells only), manifest-closure digests, entity and scene-digest bindings, channel declarations, fn-catalog resolution, wiring, and budget bounds report as findings before any host work.",inputSchema:{type:"object",additionalProperties:false,required:["scene","behavior"],properties:{scene:{...scenePathSchema,description:"Root-relative path to the spatial scene JSON source (1 MiB maximum)."},behavior:{type:"string",description:"Root-relative path to the spatial behavior document JSON."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","report","summary"],properties:{ok:{const:true},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:false,required:["findingCount","returnedFindingCount","findingsTruncated","errorCount","warningCount"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},errorCount:{type:"integer",minimum:0},warningCount:{type:"integer",minimum:0}}}}},annotations:{title:"Check scene behavior",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"audit_scene_behavior",title:"Audit scene behavior trace",description:"Analyze a baked behavior trace for pathological patterns: state thrash (rapid transitions), exact periodicity (trivially cyclic channels), dead channels (constant-valued), and unreachable states (declared in transitions but never visited). Advisory findings for gallery review \u2014 never selects or promotes.",inputSchema:{type:"object",additionalProperties:false,required:["bake"],properties:{bake:{type:"string",description:"Root-relative path to the behavior bake JSON (slopcamera.spatial-behavior-bake)."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","report","summary"],properties:{ok:{const:true},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:false,required:["findingCount","channelCount","emittedCount"],properties:{findingCount:{type:"integer",minimum:0},channelCount:{type:"integer",minimum:0},emittedCount:{type:"integer",minimum:0}}}}},annotations:{title:"Audit scene behavior trace",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"audit_scene_temporal",title:"Audit scene temporal evidence",description:"Evaluate one root-relative spatial scene at bounded sample times under one camera and report deterministic temporal findings: visibility flicker, transform discontinuity, foot-slide against declared contact windows, camera acceleration/jerk/angular velocity, exposure and focus jumps, and resource spikes.",inputSchema:{type:"object",additionalProperties:false,required:["path","camera_id"],properties:{path:scenePathSchema,camera_id:sceneCameraIdSchema,times_us:{type:"array",items:{type:"integer",minimum:0,maximum:SPATIAL_SCENE_LIMITS.durationUs},minItems:2,maxItems:SPATIAL_TEMPORAL_AUDIT_LIMITS.samples,description:"Optional sample times in microseconds (2\u2013256). Defaults to evenly spaced coverage of the scene duration."},contacts:{type:"string",description:"Optional root-relative path to a {contacts: [...]} ground-contact evidence JSON."},cut_before_us:{type:"array",items:{type:"integer",minimum:0,maximum:SPATIAL_SCENE_LIMITS.durationUs},maxItems:SPATIAL_TEMPORAL_AUDIT_LIMITS.cutBoundaries,description:"Optional intentional cut boundaries; discontinuities exactly at a cut are not findings."}}},outputSchema:{type:"object",additionalProperties:false,required:["ok","source","report","summary"],properties:{ok:{const:true},source:{type:"string"},report:{type:"object"},summary:{type:"object",additionalProperties:false,required:["findingCount","returnedFindingCount","findingsTruncated","sampleCount"],properties:{findingCount:{type:"integer",minimum:0},returnedFindingCount:{type:"integer",minimum:0},findingsTruncated:{type:"boolean"},sampleCount:{type:"integer",minimum:2}}}}},annotations:{title:"Audit scene temporal evidence",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}}]);class ToolFailure extends Error{code;issues;constructor(code,message,issues){super(message);this.name="ToolFailure";this.code=code;if(issues!==undefined)this.issues=issues}}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function safeFragment(value,maximumLength=160){return value.replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim().slice(0,maximumLength)}function safeIssues(issues){return issues.slice(0,24).map((issue)=>safeFragment(issue,240))}function rejectUnknownKeys(value,allowed){const unknown=Object.keys(value).filter((key)=>!allowed.has(key));if(unknown.length>0){throw new ToolFailure("INVALID_ARGUMENTS",`Unsupported argument: ${safeFragment(unknown[0]??"unknown")}.`)}}function parsePath(value){if(typeof value!=="string"||value.length===0){throw new ToolFailure("INVALID_ARGUMENTS","path must be a non-empty root-relative string.")}if(!value.toLowerCase().endsWith(".diagram.json")){throw new ToolFailure("INVALID_ARGUMENTS","path must end in .diagram.json.")}return value}function parseCheckArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["path"]));return{path:parsePath(value.path)}}function parseRenderArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["path","out_dir","scale"]));const outDirectory=value.out_dir;if(outDirectory!==undefined&&(typeof outDirectory!=="string"||outDirectory.length===0)){throw new ToolFailure("INVALID_ARGUMENTS","out_dir must be a non-empty root-relative string when present.")}const scale=value.scale??defaultScale;if(typeof scale!=="number"||!Number.isFinite(scale)||scale<=0||scale>mcpMaximumScale){throw new ToolFailure("RENDER_LIMIT",`scale must be greater than zero and no more than ${mcpMaximumScale}.`)}return{path:parsePath(value.path),...outDirectory===undefined?{}:{outDirectory},scale}}function parseSearchArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["query","limit"]));const query=value.query??"";const limit=value.limit??slopcameraOperationCodes.length;if(typeof query!=="string"||query.length>200||/[\u0000-\u001f\u007f]/u.test(query)||!Number.isInteger(limit)||limit<1||limit>20){throw new ToolFailure("INVALID_ARGUMENTS","query must be a bounded string and limit must be an integer from 1 through 20.")}return{query,limit}}function parseExecuteArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["operation","input"]));if(typeof value.operation!=="string"||!slopcameraOperationCodes.includes(value.operation)||!isRecord2(value.input)){throw new ToolFailure("INVALID_ARGUMENTS","operation must be an exact Slopcamera operation code and input must be an object.")}return{operation:value.operation,input:value.input}}var sceneCameraIdPattern=/^camera_[a-zA-Z0-9][a-zA-Z0-9_-]*$/u;function parseScenePath(value,label){if(typeof value!=="string"||value.length===0){throw new ToolFailure("INVALID_ARGUMENTS",`${label} must be a non-empty root-relative string.`)}if(!value.toLowerCase().endsWith(".json")){throw new ToolFailure("INVALID_ARGUMENTS",`${label} must end in .json.`)}return value}function parseSceneCameraId(value){if(typeof value!=="string"||value.length>128||!sceneCameraIdPattern.test(value)){throw new ToolFailure("INVALID_ARGUMENTS","camera_id must be a scene camera identifier (camera_ followed by letters, digits, _ or -).")}return value}function parseSceneSourceArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["path"]));return{path:parseScenePath(value.path,"path")}}function parseAuditSceneArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["path","camera_id","times_us","asset_bounds"]));let timesUs;if(value.times_us!==undefined){if(!Array.isArray(value.times_us)||value.times_us.length===0||value.times_us.length>SPATIAL_AUDIT_LIMITS.samples||value.times_us.some((timeUs)=>!Number.isSafeInteger(timeUs)||timeUs<0||timeUs>SPATIAL_SCENE_LIMITS.durationUs)){throw new ToolFailure("INVALID_ARGUMENTS",`times_us must be an array of 1\u2013${SPATIAL_AUDIT_LIMITS.samples} integer microsecond times within the scene duration bound.`)}timesUs=[...value.times_us]}return{path:parseScenePath(value.path,"path"),cameraId:parseSceneCameraId(value.camera_id),...timesUs===undefined?{}:{timesUs},..."asset_bounds"in value?{assetBounds:value.asset_bounds}:{}}}function parseDiffScenesArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["path","other"]));return{path:parseScenePath(value.path,"path"),other:parseScenePath(value.other,"other")}}function parseEvaluateSceneArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["path","camera_id","time_us"]));const timeUs=value.time_us;if(typeof timeUs!=="number"||!Number.isSafeInteger(timeUs)||timeUs<0||timeUs>SPATIAL_SCENE_LIMITS.durationUs){throw new ToolFailure("INVALID_ARGUMENTS",`time_us must be an integer microsecond time from 0 through ${SPATIAL_SCENE_LIMITS.durationUs}.`)}return{path:parseScenePath(value.path,"path"),cameraId:parseSceneCameraId(value.camera_id),timeUs}}function parseSceneDirectionArguments(value,requireAxis){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["scene","direction","camera_id","axis"]));if(requireAxis&&!SpatialGalleryAxisSchema.safeParse(value.axis).success){throw new ToolFailure("INVALID_ARGUMENTS",`axis must be one of ${SpatialGalleryAxisSchema.options.join(", ")}.`)}if(!requireAxis&&value.axis!==undefined){throw new ToolFailure("INVALID_ARGUMENTS","axis is only valid for plan_scene_gallery.")}return{scene:parseScenePath(value.scene,"scene"),direction:parseScenePath(value.direction,"direction"),...value.camera_id===undefined?{}:{cameraId:parseSceneCameraId(value.camera_id)},...value.axis===undefined?{}:{axis:value.axis}}}function parseSceneEffectsArguments(value,effectsKey){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["scene",effectsKey]));return{scene:parseScenePath(value.scene,"scene"),effects:parseScenePath(value[effectsKey],effectsKey)}}function parseSceneBehaviorArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["scene","behavior"]));return{scene:parseScenePath(value.scene,"scene"),behavior:parseScenePath(value.behavior,"behavior")}}function parseSceneBehaviorAuditArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["bake"]));return{bake:parseScenePath(value.bake,"bake")}}function parseSceneTemporalArguments(value){if(!isRecord2(value)){throw new ToolFailure("INVALID_ARGUMENTS","Tool arguments must be an object.")}rejectUnknownKeys(value,new Set(["path","camera_id","times_us","contacts","cut_before_us"]));const boundedTimes=(key,maximum)=>{const entries=value[key];if(entries===undefined)return;if(!Array.isArray(entries)||entries.length===0||entries.length>maximum||entries.some((timeUs)=>!Number.isSafeInteger(timeUs)||timeUs<0||timeUs>SPATIAL_SCENE_LIMITS.durationUs)){throw new ToolFailure("INVALID_ARGUMENTS",`${key} must be an array of 1\u2013${maximum} integer microsecond times within the scene duration bound.`)}return[...entries]};const timesUs=boundedTimes("times_us",SPATIAL_TEMPORAL_AUDIT_LIMITS.samples);const cutBeforeUs=boundedTimes("cut_before_us",SPATIAL_TEMPORAL_AUDIT_LIMITS.cutBoundaries);if(timesUs!==undefined&×Us.length<2){throw new ToolFailure("INVALID_ARGUMENTS","times_us must contain at least 2 sample times.")}return{path:parseScenePath(value.path,"path"),cameraId:parseSceneCameraId(value.camera_id),...timesUs===undefined?{}:{timesUs},...value.contacts===undefined?{}:{contacts:parseScenePath(value.contacts,"contacts")},...cutBeforeUs===undefined?{}:{cutBeforeUs}}}function assertBuiltInIcons(spec){for(const shape of spec.shapes){if((shape.type==="rect"||shape.type==="ellipse")&&shape.icon!==undefined&&!Object.hasOwn(builtInIcons,shape.icon)){throw new ToolFailure("UNKNOWN_ICON",`Shape ${safeFragment(shape.id)} requests unavailable built-in icon ${safeFragment(shape.icon)}.`)}}}function assertComplexityLimits(spec){const edgeCount=spec.edges?.length??0;if(spec.shapes.length>mcpMaximumShapes||edgeCount>mcpMaximumEdges){throw new ToolFailure("COMPLEXITY_LIMIT",`Diagram may contain at most ${mcpMaximumShapes} shapes and ${mcpMaximumEdges} edges in MCP mode.`)}}function assertRawComplexityLimits(value){if(!isRecord2(value))return;const shapeCount=Array.isArray(value.shapes)?value.shapes.length:0;const edgeCount=Array.isArray(value.edges)?value.edges.length:0;if(shapeCount>mcpMaximumShapes||edgeCount>mcpMaximumEdges){throw new ToolFailure("COMPLEXITY_LIMIT",`Diagram may contain at most ${mcpMaximumShapes} shapes and ${mcpMaximumEdges} edges in MCP mode.`)}}function assertRenderLimits(spec,scale){const scaledWidth=spec.canvas.width*scale;const scaledHeight=spec.canvas.height*scale;const pixels=Math.ceil(scaledWidth)*Math.ceil(scaledHeight);if(!Number.isFinite(pixels)||scaledWidth<1||scaledHeight<1||pixels>mcpMaximumRenderedPixels){throw new ToolFailure("RENDER_LIMIT",`Scaled canvas must be at least 1 pixel on each axis and no more than ${mcpMaximumRenderedPixels.toLocaleString("en-US")} pixels total.`)}}function boundedSlice(items,maximum){return items.length>maximum?items.slice(0,maximum):items}function publicFinding(finding){return{code:safeFragment(finding.code,64),message:safeFragment(finding.message,240),shapeIds:finding.shapeIds.slice(0,maximumShapeIdsPerFinding).map((shapeId)=>safeFragment(shapeId,120))}}function publicFindings(findings){return findings.slice(0,mcpMaximumReturnedFindings).map(publicFinding)}function diagramSummary(spec,findingCount,returnedFindingCount){return{shapeCount:spec.shapes.length,edgeCount:spec.edges?.length??0,findingCount,returnedFindingCount,findingsTruncated:returnedFindingCount<findingCount}}function successResult(text,structuredContent){return{content:[{type:"text",text}],structuredContent}}function failureResult(error){let code="INTERNAL_ERROR";let message="The tool failed safely.";let issues;if(error instanceof ToolFailure){code=error.code;message=safeFragment(error.message,320);issues=error.issues}else if(error instanceof WorkspaceBoundaryError){code=error.code;message=safeFragment(error.message,320)}else if(error instanceof SlopcameraCloudError){code=error.code;message=safeFragment(error.message.replace(/^\[[A-Z_]+\]\s*/u,""),320)}else if(error instanceof SlopcameraOperationError){code=error.code;message=safeFragment(error.message.replace(/^\[[A-Z_]+\]\s*/u,""),320)}else if(error instanceof VectorizeError){code=`VECTORIZE_${error.code.toUpperCase()}`;message="Local vectorization failed safely."}else if(error instanceof DiagramValidationError){code="INVALID_DIAGRAM";message="Diagram source did not pass validation.";issues=safeIssues(error.issues)}else if(error instanceof SlopcameraCodeError){code=error.code.toUpperCase().replace(/-/g,"_");message=safeFragment(error.message,320)}else if(error instanceof HostResourceError){code=`HOST_RESOURCE_${error.code}`;message="Host-resource admission failed safely."}else if(typeof error==="object"&&error!==null&&"issues"in error&&Array.isArray(error.issues)&&error.issues.every((issue)=>typeof issue==="string")){code="INVALID_LAYOUT";message="Diagram layout could not be resolved.";issues=safeIssues(error.issues)}const issueText=issues===undefined||issues.length===0?"":`
|
|
25
25
|
${issues.map((issue)=>`- ${issue}`).join(`
|
|
26
26
|
`)}`;return{content:[{type:"text",text:`[${code}] ${message}${issueText}`}],isError:true}}function portableDirectory(filePath){const separator=filePath.lastIndexOf("/");return separator===-1?".":filePath.slice(0,separator)}async function atomicOverwrite(filePath,data){const temporaryPath=join4(dirname5(filePath),`.${crypto.randomUUID()}.slopcamera-mcp.tmp`);try{await writeFile3(temporaryPath,data,{flag:"wx"});try{await rename3(temporaryPath,filePath)}catch(error){const code=typeof error==="object"&&error!==null&&"code"in error&&typeof error.code==="string"?error.code:undefined;if(code!=="EEXIST"&&code!=="EPERM")throw error;await rm3(filePath,{force:true});await rename3(temporaryPath,filePath)}}finally{await rm3(temporaryPath,{force:true})}}async function loadDiagram(boundary,path){const source=await boundary.readSource(path);let parsed;try{parsed=JSON.parse(source.text)}catch{throw new ToolFailure("INVALID_JSON","Diagram source is not valid JSON.")}assertRawComplexityLimits(parsed);const spec=parseDiagramSpec(parsed);assertComplexityLimits(spec);assertBuiltInIcons(spec);return{source,spec}}async function loadScene(boundary,path){const source=await boundary.readSource(path,"Scene source");const parsed=parseJsonText(source.text);try{return{source,scene:parseSpatialScene(parsed)}}catch(error){if(error instanceof SpatialSceneError){const where=error.path==="scene"?"":` at ${error.path}`;throw new ToolFailure("INVALID_SCENE",`Scene source did not pass validation${where}: ${safeFragment(error.message,240)}`)}throw error}}function parseJsonText(text){try{return JSON.parse(text)}catch{throw new ToolFailure("INVALID_JSON","Source is not valid JSON.")}}async function loadJson(boundary,path,label){const source=await boundary.readSource(path,label);return{source,value:parseJsonText(source.text)}}class SlopcameraMcpToolRuntime{boundary;generateDependencies;hostResourceCoordinator;renderQueue=Promise.resolve();constructor(boundary,generateDependencies,hostResourceCoordinator){this.boundary=boundary;this.generateDependencies=generateDependencies;this.hostResourceCoordinator=hostResourceCoordinator}static async create(rootDirectory,generateDependencies={},hostResourceCoordinator){return new SlopcameraMcpToolRuntime(await WorkspaceBoundary.create(rootDirectory),generateDependencies,hostResourceCoordinator??createDefaultHostResourceCoordinator())}async withHostAdmission(operation,callback){return await withSlopcameraOperationHostAdmission(operation,callback,{hostResourceCoordinator:this.hostResourceCoordinator})}async withSceneAdmission(callback){return await this.hostResourceCoordinator.withLease([{resource:"cpu",amount:1},{resource:"local-io",amount:1}],async(lease)=>{await lease.assertOwned();return await callback(lease)})}enqueueRender(operation){const result=this.renderQueue.then(operation,operation);this.renderQueue=result.then(()=>{return},()=>{return});return result}async call(name,argumentsValue){try{if(name==="check_diagram"){const options=parseCheckArguments(argumentsValue);return await this.withHostAdmission("slopcamera.diagram.check",async()=>await this.check(options))}if(name==="render_diagram"){const options=parseRenderArguments(argumentsValue);return await this.enqueueRender(async()=>await this.withHostAdmission("slopcamera.diagram.render",async()=>await this.render(options)))}if(name==="search_slopcamera"){const options=parseSearchArguments(argumentsValue);const operations=searchSlopcameraOperations(options.query,options.limit);return successResult(`Found ${operations.length} Slopcamera operation${operations.length===1?"":"s"}.`,{ok:true,operations})}if(name==="execute_slopcamera"){const options=parseExecuteArguments(argumentsValue);return await this.execute(options)}if(name==="check_scene"){const options=parseSceneSourceArguments(argumentsValue);return await this.withSceneAdmission(async()=>await this.checkScene(options))}if(name==="inspect_scene"){const options=parseSceneSourceArguments(argumentsValue);return await this.withSceneAdmission(async()=>await this.inspectScene(options))}if(name==="audit_scene"){const options=parseAuditSceneArguments(argumentsValue);return await this.withSceneAdmission(async()=>await this.auditScene(options))}if(name==="diff_scenes"){const options=parseDiffScenesArguments(argumentsValue);return await this.withSceneAdmission(async()=>await this.diffScenes(options))}if(name==="evaluate_scene"){const options=parseEvaluateSceneArguments(argumentsValue);return await this.withSceneAdmission(async()=>await this.evaluateScene(options))}if(name==="check_scene_direction"){const options=parseSceneDirectionArguments(argumentsValue,false);return await this.withSceneAdmission(async()=>await this.checkSceneDirection(options))}if(name==="plan_scene_direction"){const options=parseSceneDirectionArguments(argumentsValue,false);return await this.withSceneAdmission(async()=>await this.planSceneDirection(options))}if(name==="plan_scene_gallery"){const options=parseSceneDirectionArguments(argumentsValue,true);return await this.withSceneAdmission(async()=>await this.planSceneGallery(options))}if(name==="check_scene_effects"){const options=parseSceneEffectsArguments(argumentsValue,"effects");return await this.withSceneAdmission(async()=>await this.checkSceneEffects(options))}if(name==="plan_scene_effects"){const options=parseSceneEffectsArguments(argumentsValue,"draft");return await this.withSceneAdmission(async()=>await this.planSceneEffects(options))}if(name==="check_scene_behavior"){const options=parseSceneBehaviorArguments(argumentsValue);return await this.withSceneAdmission(async()=>await this.checkSceneBehavior(options))}if(name==="audit_scene_behavior"){const options=parseSceneBehaviorAuditArguments(argumentsValue);return await this.withSceneAdmission(async()=>await this.auditSceneBehavior(options))}if(name==="audit_scene_temporal"){const options=parseSceneTemporalArguments(argumentsValue);return await this.withSceneAdmission(async()=>await this.auditSceneTemporal(options))}throw new ToolFailure("UNKNOWN_TOOL","Requested tool is not available.")}catch(error){return failureResult(error)}}wrapSemanticResult(operation,result){if(result.isError===true)return result;return{content:result.content,structuredContent:{ok:true,operation,result:result.structuredContent??{}}}}async execute(options){if(options.operation==="slopcamera.diagram.check"){const input=parseSlopcameraOperationInput(options.operation,options.input);return this.wrapSemanticResult(options.operation,await this.withHostAdmission(options.operation,async()=>await this.check({path:input.path})))}if(options.operation==="slopcamera.diagram.render"){const input=parseSlopcameraOperationInput(options.operation,options.input);return this.enqueueRender(async()=>await this.withHostAdmission(options.operation,async()=>this.wrapSemanticResult(options.operation,await this.render({path:input.path,...input.outDirectory===undefined?{}:{outDirectory:input.outDirectory},scale:input.scale??defaultScale}))))}if(options.operation==="slopcamera.image.vectorize"){const input=parseSlopcameraOperationInput(options.operation,options.input);return this.enqueueRender(async()=>await this.withHostAdmission(options.operation,async(lease)=>{const source=await this.boundary.resolveInputFile(input.inputPath,vectorizeHardLimits.maxInputBytes);const output=await this.boundary.prepareOutputFile(input.outputPath);const result=await vectorizeImage(source.absolutePath,{outputPath:output.absolutePath,...input.duotone===undefined?{}:{duotone:input.duotone},...input.alphaCutoff===undefined?{}:{alphaCutoff:input.alphaCutoff},...input.timeoutMs===undefined?{}:{limits:{maxDurationMs:input.timeoutMs}},inheritedFileDescriptors:[lease.inheritedFileDescriptor]});return successResult(`Executed ${options.operation}: ${output.relativePath}`,{ok:true,operation:options.operation,result:{inputPath:source.relativePath,outputPath:output.relativePath,receipt:result.receipt}})}))}if(options.operation==="slopcamera.image.gallery"){const input=parseSlopcameraOperationInput(options.operation,options.input);return await this.withHostAdmission(options.operation,async()=>{const output=await this.boundary.prepareOutputDirectory(input.outputDir);const receipt=await generateSlopcameraImageGallery({...input,outputDir:output.absolutePath},this.generateDependencies);return successResult(`Executed ${options.operation}: ${receipt.counts.generated}/${receipt.counts.requested} candidates in ${output.relativePath}.`,{ok:true,operation:options.operation,result:{...receipt,outputDir:output.relativePath}})})}return await this.withHostAdmission(options.operation,async()=>{const input=parseSlopcameraOperationInput(options.operation,options.input);const output=await this.boundary.prepareOutputFile(input.outputPath);const generated=await generateSlopcameraImageFile({...input,outputPath:output.absolutePath},this.generateDependencies);return successResult(`Executed ${options.operation}: ${output.relativePath} (request ${safeFragment(generated.requestId,256)}).`,{ok:true,operation:options.operation,result:{bytes:generated.bytes,mediaType:generated.mediaType,model:generated.model,outputPath:output.relativePath,provider:generated.provider,requestId:generated.requestId,sha256:generated.sha256,warnings:generated.warnings}})})}async check(options){const{source,spec}=await loadDiagram(this.boundary,options.path);const allFindings=lintDiagram(spec);const findings=publicFindings(allFindings);const summary=diagramSummary(spec,allFindings.length,findings.length);const text=allFindings.length===0?`Checked ${source.relativePath}: no findings.`:`Checked ${source.relativePath}: ${allFindings.length} finding${allFindings.length===1?"":"s"}; ${findings.length} returned in structured content${findings.length<allFindings.length?" (truncated)":""}.`;return successResult(text,{ok:true,source:source.relativePath,findings,summary})}async render(options){const{source,spec}=await loadDiagram(this.boundary,options.path);assertRenderLimits(spec,options.scale);const outputDirectory=await this.boundary.prepareOutputDirectory(options.outDirectory??portableDirectory(source.relativePath));const tldr=serializeTldr(spec,builtInConfig);const[light,dark]=await Promise.all([renderSvg(spec,"light",builtInConfig),renderSvg(spec,"dark",builtInConfig)]);const lightPng=renderPng(light,builtInConfig,options.scale);const darkPng=renderPng(dark,builtInConfig,options.scale);const absoluteArtifacts={spec:source.absolutePath,tldr:join4(outputDirectory.absolutePath,`${spec.name}.tldr`),lightSvg:join4(outputDirectory.absolutePath,`${spec.name}.light.svg`),darkSvg:join4(outputDirectory.absolutePath,`${spec.name}.dark.svg`),lightPng:join4(outputDirectory.absolutePath,`${spec.name}.light.png`),darkPng:join4(outputDirectory.absolutePath,`${spec.name}.dark.png`)};await Promise.all([atomicOverwrite(absoluteArtifacts.tldr,tldr),atomicOverwrite(absoluteArtifacts.lightSvg,light.svg),atomicOverwrite(absoluteArtifacts.darkSvg,dark.svg),atomicOverwrite(absoluteArtifacts.lightPng,lightPng),atomicOverwrite(absoluteArtifacts.darkPng,darkPng)]);const artifacts={tldr:this.boundary.toRelativePath(absoluteArtifacts.tldr),lightSvg:this.boundary.toRelativePath(absoluteArtifacts.lightSvg),darkSvg:this.boundary.toRelativePath(absoluteArtifacts.darkSvg),lightPng:this.boundary.toRelativePath(absoluteArtifacts.lightPng),darkPng:this.boundary.toRelativePath(absoluteArtifacts.darkPng)};const allFindings=lintDiagram(spec);const findings=publicFindings(allFindings);const summary=diagramSummary(spec,allFindings.length,findings.length);const text=[`Rendered ${source.relativePath} with built-in assets:`,...Object.values(artifacts).map((artifact)=>`- ${artifact}`)].join(`
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{DrawingValidationError,SLOPCAMERA_CAPABILITY_MANIFEST_LIMITS,SLOPCAMERA_PORTABLE_CAPABILITY_VERSION,SLOPCAMERA_VERSION,STUDIO_LIMITS,SlopcameraCapabilityCommandSchema,SlopcameraCapabilityEffectSchema,SlopcameraCapabilityManifestSchema,SlopcameraCapabilityModuleDeclarationSchema,SlopcameraCapabilityModuleSchema,SlopcameraCapabilityOperationSchema,SlopcameraCapabilityPreparationSchema,SlopcameraCapabilityProfileSchema,SlopcameraCapabilityQualificationSchema,SlopcameraCapabilityResourceSchema,SlopcameraCapabilityResumeSchema,SlopcameraCapabilityToolSchema,SlopcameraCapabilityWorkflowSchema,SlopcameraMcpToolRuntime,SlopcameraSceneVariantsSchema,StudioCapabilityNameSchema,StudioDigestSchema,StudioEngineOptionsSchema,StudioEngineSchema,StudioExecutionProfileSchema,StudioJobSchema,StudioOutputArtifactSchema,StudioOutputFormatSchema,StudioOutputInterpretationSchema,StudioOutputRoleSchema,StudioOutputSpecSchema,StudioPathSchema,StudioPlanSchema,StudioReceiptSchema,StudioRenderSchema,StudioRuntimeIdentitySchema,StudioSourceBundleSchema,StudioSourceSpaceSchema,WorkspaceBoundary,WorkspaceBoundaryError,artifactSummary,checkDiagramFile,checkDrawingFile,compileSlopcameraCapabilityManifest,createPortableSlopcameraCapabilityManifest,defineSlopcameraCapabilityModule,diagramApi,drawingMinimumGlyphHeightPt,drawingPageGeometry,drawingProfile,drawingSourceByteLimit,inspectStudioBundle,inspectStudioPlan,mcpMaximumRenderedPixels,mcpMaximumScale,mcpSourceByteLimit,parseDrawingSource,parseSlopcameraCapabilityManifest,parseSlopcameraSceneVariants,parseStudioJob,parseStudioPlan,parseStudioReceipt,parseStudioRuntimeIdentity,parseStudioSourceBundle,planSlopcameraSceneGallery,planStudioJob,readDiagramFile,readDrawingFile,renderDiagramFile,renderDrawing,renderDrawingFile,runMcpServer,slopcameraApi,slopcameraMcpProtocolVersion,slopcameraMcpServerName,slopcameraMcpTools,slopcameraPortableCapabilityManifest,slopcameraSceneGalleryLimits,starterDrawingSource,studioJobSha256,studioOutputPath,studioRuntimeSha256,studioSourceBundleSha256,summarizeSceneVariantPatch,validateStudioReceipt}from"./index-
|
|
2
|
+
import{DrawingValidationError,SLOPCAMERA_CAPABILITY_MANIFEST_LIMITS,SLOPCAMERA_PORTABLE_CAPABILITY_VERSION,SLOPCAMERA_VERSION,STUDIO_LIMITS,SlopcameraCapabilityCommandSchema,SlopcameraCapabilityEffectSchema,SlopcameraCapabilityManifestSchema,SlopcameraCapabilityModuleDeclarationSchema,SlopcameraCapabilityModuleSchema,SlopcameraCapabilityOperationSchema,SlopcameraCapabilityPreparationSchema,SlopcameraCapabilityProfileSchema,SlopcameraCapabilityQualificationSchema,SlopcameraCapabilityResourceSchema,SlopcameraCapabilityResumeSchema,SlopcameraCapabilityToolSchema,SlopcameraCapabilityWorkflowSchema,SlopcameraMcpToolRuntime,SlopcameraSceneVariantsSchema,StudioCapabilityNameSchema,StudioDigestSchema,StudioEngineOptionsSchema,StudioEngineSchema,StudioExecutionProfileSchema,StudioJobSchema,StudioOutputArtifactSchema,StudioOutputFormatSchema,StudioOutputInterpretationSchema,StudioOutputRoleSchema,StudioOutputSpecSchema,StudioPathSchema,StudioPlanSchema,StudioReceiptSchema,StudioRenderSchema,StudioRuntimeIdentitySchema,StudioSourceBundleSchema,StudioSourceSpaceSchema,WorkspaceBoundary,WorkspaceBoundaryError,artifactSummary,checkDiagramFile,checkDrawingFile,compileSlopcameraCapabilityManifest,createPortableSlopcameraCapabilityManifest,defineSlopcameraCapabilityModule,diagramApi,drawingMinimumGlyphHeightPt,drawingPageGeometry,drawingProfile,drawingSourceByteLimit,inspectStudioBundle,inspectStudioPlan,mcpMaximumRenderedPixels,mcpMaximumScale,mcpSourceByteLimit,parseDrawingSource,parseSlopcameraCapabilityManifest,parseSlopcameraSceneVariants,parseStudioJob,parseStudioPlan,parseStudioReceipt,parseStudioRuntimeIdentity,parseStudioSourceBundle,planSlopcameraSceneGallery,planStudioJob,readDiagramFile,readDrawingFile,renderDiagramFile,renderDrawing,renderDrawingFile,runMcpServer,slopcameraApi,slopcameraMcpProtocolVersion,slopcameraMcpServerName,slopcameraMcpTools,slopcameraPortableCapabilityManifest,slopcameraSceneGalleryLimits,starterDrawingSource,studioJobSha256,studioOutputPath,studioRuntimeSha256,studioSourceBundleSha256,summarizeSceneVariantPatch,validateStudioReceipt}from"./index-10bz03js.js";import{bundledSkillPath,installSkill}from"./index-grk47tgs.js";import"./index-z1kd1x8j.js";import"./index-3cxf2c58.js";import{SlopcameraWorkflowError,defineSlopcameraWorkflow,runSlopcameraWorkflow}from"./index-qtn3s421.js";import{DiagramValidationError,SlopcameraOperationError,StackLayoutError,builtInIcons,composeSlopcameraImageGallery,critiqueIconRaster,executeSlopcameraOperation,executeSlopcameraOperationWithLease,extractIconLineArt,galleryCandidateId,galleryPromptFor,generateSlopcameraIcon,generateSlopcameraImageGallery,iconPromptFor,iconVisualGateProblems,isSlopcameraOperationCode,lintDiagram,parseDiagramSource,parseDiagramSpec,parseSlopcameraGalleryVary,parseSlopcameraOperationInput,planSlopcameraGallery,renderPng,renderSvg,resolveDiagramSource,resolveEdge,resolveStackLayout,searchSlopcameraOperations,serializeTldr,slopcameraGalleryAxes,slopcameraGalleryKinds,slopcameraGalleryLimits,slopcameraIconCritiqueDefaultModel,slopcameraIconCritiqueTimeoutMs,slopcameraIconDefaultInk,slopcameraIconDefaultRounds,slopcameraIconMaximumRounds,slopcameraIconPanel,slopcameraIconSubjectMaximumBytes,slopcameraOperationCodes,slopcameraOperationHostResourceClaims,slopcameraOperationRegistry,stackLayoutDefaults,withSlopcameraOperationHostAdmission}from"./index-sy1n4zfy.js";import{VTRACER_VERSION,VectorizeError,vectorizeDefaultLimits,vectorizeHardLimits,vectorizeImage,vectorizeProfileNames,vtracerReleases}from"./index-qry58nj2.js";import{SlopcameraCloudError,createFixedGatewayFetch,generateSlopcameraImage,generateSlopcameraImageFile,resolveSlopcameraGatewayCredential,slopcameraGatewayApiBaseUrl,slopcameraGatewayCredentialStatus,slopcameraImageModels,slopcameraMaximumPromptBytes,slopcameraMaximumRawImageBytes,slopcameraResponseMediaTypes}from"./index-77fjfg9f.js";import{HOST_RESOURCE_MAX_WAIT_MILLISECONDS,HostResourceError,createDefaultHostResourceCoordinator,createHostResourceCoordinator,createProcessLocalHostResourceCoordinator,defaultSlopcameraHostResourceProfile,defaultSlopcameraHostResourceStateRoot,normalizeHostResourceClaims,normalizeHostResourceProfile,slopcameraHostResourceNames}from"./index-b3geqczn.js";import"./index-80a36bc0.js";export{withSlopcameraOperationHostAdmission,vtracerReleases,vectorizeProfileNames,vectorizeImage,vectorizeHardLimits,vectorizeDefaultLimits,validateStudioReceipt,summarizeSceneVariantPatch,studioSourceBundleSha256,studioRuntimeSha256,studioOutputPath,studioJobSha256,starterDrawingSource,stackLayoutDefaults,slopcameraSceneGalleryLimits,slopcameraResponseMediaTypes,slopcameraPortableCapabilityManifest,slopcameraOperationRegistry,slopcameraOperationHostResourceClaims,slopcameraOperationCodes,slopcameraMcpTools,slopcameraMcpServerName,slopcameraMcpProtocolVersion,slopcameraMaximumRawImageBytes,slopcameraMaximumPromptBytes,slopcameraImageModels,slopcameraIconSubjectMaximumBytes,slopcameraIconPanel,slopcameraIconMaximumRounds,slopcameraIconDefaultRounds,slopcameraIconDefaultInk,slopcameraIconCritiqueTimeoutMs,slopcameraIconCritiqueDefaultModel,slopcameraHostResourceNames,slopcameraGatewayCredentialStatus,slopcameraGatewayApiBaseUrl,slopcameraGalleryLimits,slopcameraGalleryKinds,slopcameraGalleryAxes,slopcameraApi,serializeTldr,searchSlopcameraOperations,runSlopcameraWorkflow,runMcpServer,resolveStackLayout,resolveSlopcameraGatewayCredential,resolveEdge,resolveDiagramSource,renderSvg,renderPng,renderDrawingFile,renderDrawing,renderDiagramFile,readDrawingFile,readDiagramFile,planStudioJob,planSlopcameraSceneGallery,planSlopcameraGallery,parseStudioSourceBundle,parseStudioRuntimeIdentity,parseStudioReceipt,parseStudioPlan,parseStudioJob,parseSlopcameraSceneVariants,parseSlopcameraOperationInput,parseSlopcameraGalleryVary,parseSlopcameraCapabilityManifest,parseDrawingSource,parseDiagramSpec,parseDiagramSource,normalizeHostResourceProfile,normalizeHostResourceClaims,mcpSourceByteLimit,mcpMaximumScale,mcpMaximumRenderedPixels,lintDiagram,isSlopcameraOperationCode,installSkill,inspectStudioPlan,inspectStudioBundle,iconVisualGateProblems,iconPromptFor,generateSlopcameraImageGallery,generateSlopcameraImageFile,generateSlopcameraImage,generateSlopcameraIcon,galleryPromptFor,galleryCandidateId,extractIconLineArt,executeSlopcameraOperationWithLease,executeSlopcameraOperation,drawingSourceByteLimit,drawingProfile,drawingPageGeometry,drawingMinimumGlyphHeightPt,diagramApi,defineSlopcameraWorkflow,defineSlopcameraCapabilityModule,defaultSlopcameraHostResourceStateRoot,defaultSlopcameraHostResourceProfile,critiqueIconRaster,createProcessLocalHostResourceCoordinator,createPortableSlopcameraCapabilityManifest,createHostResourceCoordinator,createFixedGatewayFetch,createDefaultHostResourceCoordinator,composeSlopcameraImageGallery,compileSlopcameraCapabilityManifest,checkDrawingFile,checkDiagramFile,bundledSkillPath,builtInIcons,artifactSummary,WorkspaceBoundaryError,WorkspaceBoundary,VectorizeError,VTRACER_VERSION,StudioSourceSpaceSchema,StudioSourceBundleSchema,StudioRuntimeIdentitySchema,StudioRenderSchema,StudioReceiptSchema,StudioPlanSchema,StudioPathSchema,StudioOutputSpecSchema,StudioOutputRoleSchema,StudioOutputInterpretationSchema,StudioOutputFormatSchema,StudioOutputArtifactSchema,StudioJobSchema,StudioExecutionProfileSchema,StudioEngineSchema,StudioEngineOptionsSchema,StudioDigestSchema,StudioCapabilityNameSchema,StackLayoutError,SlopcameraWorkflowError,SlopcameraSceneVariantsSchema,SlopcameraOperationError,SlopcameraMcpToolRuntime,SlopcameraCloudError,SlopcameraCapabilityWorkflowSchema,SlopcameraCapabilityToolSchema,SlopcameraCapabilityResumeSchema,SlopcameraCapabilityResourceSchema,SlopcameraCapabilityQualificationSchema,SlopcameraCapabilityProfileSchema,SlopcameraCapabilityPreparationSchema,SlopcameraCapabilityOperationSchema,SlopcameraCapabilityModuleSchema,SlopcameraCapabilityModuleDeclarationSchema,SlopcameraCapabilityManifestSchema,SlopcameraCapabilityEffectSchema,SlopcameraCapabilityCommandSchema,STUDIO_LIMITS,SLOPCAMERA_VERSION,SLOPCAMERA_PORTABLE_CAPABILITY_VERSION,SLOPCAMERA_CAPABILITY_MANIFEST_LIMITS,HostResourceError,HOST_RESOURCE_MAX_WAIT_MILLISECONDS,DrawingValidationError,DiagramValidationError};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hraness/slopcamera",
|
|
3
|
-
"version": "3.3.
|
|
3
|
+
"version": "3.3.6",
|
|
4
4
|
"description": "A local visual studio for coding agents: author scenes, combine generated and recorded media, and export images, diagrams, animation, and video from retained sources.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -14,7 +14,7 @@ command -v slopcamera
|
|
|
14
14
|
|
|
15
15
|
A restricted shell can omit package-manager paths. Check known host installation paths before declaring a tool unavailable. If Bun is genuinely absent, follow its official [installation guide](https://bun.sh/docs/installation) within the user’s authorized setup scope. Do not switch package managers or pipe an unreviewed installer into a shell.
|
|
16
16
|
|
|
17
|
-
Slopcamera installs from its verified release archive: `bun add --global https://github.com/hraness/slopcamera/releases/download/v3.3.
|
|
17
|
+
Slopcamera installs from its verified release archive: `bun add --global https://github.com/hraness/slopcamera/releases/download/v3.3.5/hraness-slopcamera-3.3.5.tgz`, then `slopcamera doctor --json`. Building from source is the contributor path. Historical Atet archives do not install the renamed CLI; never substitute `slopcamera` into an old archive URL.
|
|
18
18
|
|
|
19
19
|
Use an existing compatible source build when available. Otherwise follow the [complete source-install guide](https://github.com/hraness/slopcamera/blob/main/docs/how-to/use-current-source.md): clone into a new directory, record its exact commit, install locked dependencies without lifecycle scripts, build the SDK and source CLI, then define the shell command against that checkout. A clone or skill installation alone does not install the executable. Do not alter an existing active checkout to satisfy this path.
|
|
20
20
|
|
package/src/version.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const SLOPCAMERA_VERSION = "3.3.
|
|
1
|
+
export const SLOPCAMERA_VERSION = "3.3.6" as const
|