@hraness/slopcamera 3.8.0 → 3.8.1
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 +286 -298
- package/apps/desktop/application/html-overlay-integrity.ts +27 -4
- package/apps/desktop/application/operation.ts +1 -1
- package/apps/desktop/application/operations/spatial-render.ts +1 -1
- package/apps/desktop/cli/commands.ts +1 -1
- package/apps/desktop/dist/cli/main.js +244 -244
- package/dist/cli.js +1 -1
- package/dist/{index-k9bjw80z.js → index-6jrxaser.js} +1 -1
- package/dist/index.js +1 -1
- package/docs/README.md +4 -1
- package/package.json +2 -2
- package/skills/slopcamera/references/install.md +2 -2
- package/src/version.ts +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{SLOPCAMERA_VERSION,VISUAL_STYLE_PROFILES,artifactSummary,checkDiagramFile,checkDrawingFile,createVisualStyleDirection,generateSlopcameraIconSet,getVisualStyleProfile,parseSlopcameraIconSetSpec,renderDiagramFile,renderDrawingFile,runMcpServer,slopcameraIconSetMaximumSetRounds,starterDrawingSource}from"./index-
|
|
3
|
+
import{SLOPCAMERA_VERSION,VISUAL_STYLE_PROFILES,artifactSummary,checkDiagramFile,checkDrawingFile,createVisualStyleDirection,generateSlopcameraIconSet,getVisualStyleProfile,parseSlopcameraIconSetSpec,renderDiagramFile,renderDrawingFile,runMcpServer,slopcameraIconSetMaximumSetRounds,starterDrawingSource}from"./index-6jrxaser.js";import{installSkill,pathExists}from"./index-grk47tgs.js";import"./index-z1kd1x8j.js";import"./index-3cxf2c58.js";import"./index-842t02pp.js";import{executeSlopcameraOperation,generateSlopcameraIcon,generateSlopcameraImageGallery,isSlopcameraOperationCode,parseSlopcameraGalleryVary,searchSlopcameraOperations,slopcameraGalleryKinds,slopcameraGalleryLimits,slopcameraIconContexts,slopcameraIconMaximumRounds,slopcameraOperationCodes,withSlopcameraOperationHostAdmission}from"./index-y8spxs77.js";import{vectorizeImage}from"./index-mnp0bftq.js";import{generateSlopcameraImageFile,slopcameraGatewayCredentialStatus,slopcameraImageModels}from"./index-p74xy76d.js";import"./index-b3geqczn.js";import{__require}from"./index-80a36bc0.js";import{readFile,writeFile}from"fs/promises";import{dirname,resolve}from"path";function reportUsefulResult(observer){try{if(observer!==undefined)Promise.resolve(observer()).catch(()=>{return})}catch{}}import{maybeShowSupportInvitation,runSupportCommand,supportAdvancedHelp,supportHelpLine}from"@hraness/support-foundation/node";var slopcameraSupportHelpLine=()=>supportHelpLine({command:["slopcamera"]});var slopcameraSupportAdvancedHelp=()=>supportAdvancedHelp({command:["slopcamera"]});var supportProfile={id:"slopcamera",name:"Slopcamera",valueProposition:"Support ongoing development of local media 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.8.0";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.8.1";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,VISUAL_STYLE_IDS,VISUAL_STYLE_PROFILES,VISUAL_STYLE_VARIATION_ALGORITHM,VisualStyleIdSchema,VisualStyleProfileSchema,WorkspaceBoundary,WorkspaceBoundaryError,artifactSummary,checkDiagramFile,checkDrawingFile,compileSlopcameraCapabilityManifest,createPortableSlopcameraCapabilityManifest,createVisualStyleDirection,critiqueSlopcameraIconSet,defineSlopcameraCapabilityModule,diagramApi,drawingMinimumGlyphHeightPt,drawingPageGeometry,drawingProfile,drawingSourceByteLimit,generateSlopcameraIconSet,getVisualStyleProfile,inspectStudioBundle,inspectStudioPlan,mcpMaximumRenderedPixels,mcpMaximumScale,mcpSourceByteLimit,parseDrawingSource,parseSlopcameraCapabilityManifest,parseSlopcameraIconSetSpec,parseSlopcameraSceneVariants,parseStudioJob,parseStudioPlan,parseStudioReceipt,parseStudioRuntimeIdentity,parseStudioSourceBundle,planSlopcameraSceneGallery,planStudioJob,readDiagramFile,readDrawingFile,renderDiagramFile,renderDrawing,renderDrawingFile,runMcpServer,sampleVisualStyleExposure,slopcameraApi,slopcameraIconSetDefaultPool,slopcameraIconSetDefaultSetRounds,slopcameraIconSetMaximumMembers,slopcameraIconSetMaximumNameBytes,slopcameraIconSetMaximumSetRounds,slopcameraIconSetSlugPattern,slopcameraMcpProtocolVersion,slopcameraMcpServerName,slopcameraMcpTools,slopcameraPortableCapabilityManifest,slopcameraSceneGalleryLimits,starterDrawingSource,studioJobSha256,studioOutputPath,studioRuntimeSha256,studioSourceBundleSha256,summarizeSceneVariantPatch,validateStudioReceipt,visualStyleFrameVariation}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,VISUAL_STYLE_IDS,VISUAL_STYLE_PROFILES,VISUAL_STYLE_VARIATION_ALGORITHM,VisualStyleIdSchema,VisualStyleProfileSchema,WorkspaceBoundary,WorkspaceBoundaryError,artifactSummary,checkDiagramFile,checkDrawingFile,compileSlopcameraCapabilityManifest,createPortableSlopcameraCapabilityManifest,createVisualStyleDirection,critiqueSlopcameraIconSet,defineSlopcameraCapabilityModule,diagramApi,drawingMinimumGlyphHeightPt,drawingPageGeometry,drawingProfile,drawingSourceByteLimit,generateSlopcameraIconSet,getVisualStyleProfile,inspectStudioBundle,inspectStudioPlan,mcpMaximumRenderedPixels,mcpMaximumScale,mcpSourceByteLimit,parseDrawingSource,parseSlopcameraCapabilityManifest,parseSlopcameraIconSetSpec,parseSlopcameraSceneVariants,parseStudioJob,parseStudioPlan,parseStudioReceipt,parseStudioRuntimeIdentity,parseStudioSourceBundle,planSlopcameraSceneGallery,planStudioJob,readDiagramFile,readDrawingFile,renderDiagramFile,renderDrawing,renderDrawingFile,runMcpServer,sampleVisualStyleExposure,slopcameraApi,slopcameraIconSetDefaultPool,slopcameraIconSetDefaultSetRounds,slopcameraIconSetMaximumMembers,slopcameraIconSetMaximumNameBytes,slopcameraIconSetMaximumSetRounds,slopcameraIconSetSlugPattern,slopcameraMcpProtocolVersion,slopcameraMcpServerName,slopcameraMcpTools,slopcameraPortableCapabilityManifest,slopcameraSceneGalleryLimits,starterDrawingSource,studioJobSha256,studioOutputPath,studioRuntimeSha256,studioSourceBundleSha256,summarizeSceneVariantPatch,validateStudioReceipt,visualStyleFrameVariation}from"./index-6jrxaser.js";import{bundledSkillPath,installSkill}from"./index-grk47tgs.js";import"./index-z1kd1x8j.js";import"./index-3cxf2c58.js";import{SlopcameraWorkflowError,defineSlopcameraWorkflow,runSlopcameraWorkflow}from"./index-842t02pp.js";import{DiagramValidationError,SlopcameraOperationError,StackLayoutError,builtInIcons,collectSlopcameraIconCandidates,composeSlopcameraImageGallery,critiqueIconRaster,estimateIconStrokePixels,executeSlopcameraOperation,executeSlopcameraOperationWithLease,extractIconLineArt,galleryCandidateId,galleryPromptFor,generateSlopcameraIcon,generateSlopcameraImageGallery,iconPromptFor,iconVisualGateProblems,isSlopcameraOperationCode,lintDiagram,loadIconLanguageRuntime,measureIconCandidateMetrics,parseDiagramSource,parseDiagramSpec,parseSlopcameraGalleryVary,parseSlopcameraOperationInput,planSlopcameraGallery,renderIconPreview,renderPng,renderSvg,resolveDiagramSource,resolveEdge,resolveStackLayout,searchSlopcameraOperations,serializeTldr,slopcameraGalleryAxes,slopcameraGalleryKinds,slopcameraGalleryLimits,slopcameraIconContextProfiles,slopcameraIconContexts,slopcameraIconCritiqueDefaultModel,slopcameraIconCritiqueTimeoutMs,slopcameraIconDefaultInk,slopcameraIconDefaultRounds,slopcameraIconMaximumRounds,slopcameraIconPanel,slopcameraIconSubjectMaximumBytes,slopcameraOperationCodes,slopcameraOperationHostResourceClaims,slopcameraOperationRegistry,stackLayoutDefaults,withSlopcameraOperationHostAdmission,writeAtomically}from"./index-y8spxs77.js";import{VTRACER_VERSION,VectorizeError,vectorizeDefaultLimits,vectorizeHardLimits,vectorizeImage,vectorizeProfileNames,vtracerReleases}from"./index-mnp0bftq.js";import{SlopcameraCloudError,createFixedGatewayFetch,generateSlopcameraImage,generateSlopcameraImageFile,resolveSlopcameraGatewayCredential,slopcameraGatewayApiBaseUrl,slopcameraGatewayCredentialStatus,slopcameraImageModels,slopcameraMaximumPromptBytes,slopcameraMaximumRawImageBytes,slopcameraResponseMediaTypes}from"./index-p74xy76d.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{writeAtomically,withSlopcameraOperationHostAdmission,vtracerReleases,visualStyleFrameVariation,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,slopcameraIconSetSlugPattern,slopcameraIconSetMaximumSetRounds,slopcameraIconSetMaximumNameBytes,slopcameraIconSetMaximumMembers,slopcameraIconSetDefaultSetRounds,slopcameraIconSetDefaultPool,slopcameraIconPanel,slopcameraIconMaximumRounds,slopcameraIconDefaultRounds,slopcameraIconDefaultInk,slopcameraIconCritiqueTimeoutMs,slopcameraIconCritiqueDefaultModel,slopcameraIconContexts,slopcameraIconContextProfiles,slopcameraHostResourceNames,slopcameraGatewayCredentialStatus,slopcameraGatewayApiBaseUrl,slopcameraGalleryLimits,slopcameraGalleryKinds,slopcameraGalleryAxes,slopcameraApi,serializeTldr,searchSlopcameraOperations,sampleVisualStyleExposure,runSlopcameraWorkflow,runMcpServer,resolveStackLayout,resolveSlopcameraGatewayCredential,resolveEdge,resolveDiagramSource,renderSvg,renderPng,renderIconPreview,renderDrawingFile,renderDrawing,renderDiagramFile,readDrawingFile,readDiagramFile,planStudioJob,planSlopcameraSceneGallery,planSlopcameraGallery,parseStudioSourceBundle,parseStudioRuntimeIdentity,parseStudioReceipt,parseStudioPlan,parseStudioJob,parseSlopcameraSceneVariants,parseSlopcameraOperationInput,parseSlopcameraIconSetSpec,parseSlopcameraGalleryVary,parseSlopcameraCapabilityManifest,parseDrawingSource,parseDiagramSpec,parseDiagramSource,normalizeHostResourceProfile,normalizeHostResourceClaims,measureIconCandidateMetrics,mcpSourceByteLimit,mcpMaximumScale,mcpMaximumRenderedPixels,loadIconLanguageRuntime,lintDiagram,isSlopcameraOperationCode,installSkill,inspectStudioPlan,inspectStudioBundle,iconVisualGateProblems,iconPromptFor,getVisualStyleProfile,generateSlopcameraImageGallery,generateSlopcameraImageFile,generateSlopcameraImage,generateSlopcameraIconSet,generateSlopcameraIcon,galleryPromptFor,galleryCandidateId,extractIconLineArt,executeSlopcameraOperationWithLease,executeSlopcameraOperation,estimateIconStrokePixels,drawingSourceByteLimit,drawingProfile,drawingPageGeometry,drawingMinimumGlyphHeightPt,diagramApi,defineSlopcameraWorkflow,defineSlopcameraCapabilityModule,defaultSlopcameraHostResourceStateRoot,defaultSlopcameraHostResourceProfile,critiqueSlopcameraIconSet,critiqueIconRaster,createVisualStyleDirection,createProcessLocalHostResourceCoordinator,createPortableSlopcameraCapabilityManifest,createHostResourceCoordinator,createFixedGatewayFetch,createDefaultHostResourceCoordinator,composeSlopcameraImageGallery,compileSlopcameraCapabilityManifest,collectSlopcameraIconCandidates,checkDrawingFile,checkDiagramFile,bundledSkillPath,builtInIcons,artifactSummary,WorkspaceBoundaryError,WorkspaceBoundary,VisualStyleProfileSchema,VisualStyleIdSchema,VectorizeError,VTRACER_VERSION,VISUAL_STYLE_VARIATION_ALGORITHM,VISUAL_STYLE_PROFILES,VISUAL_STYLE_IDS,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/docs/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# SlopCamera documentation
|
|
2
2
|
|
|
3
|
-
Slopcamera is a media studio for coding agents.
|
|
3
|
+
Slopcamera is a media studio for coding agents. Your agent writes a short source file, the CLI checks and renders it, and a revision is an edit to that file and a new render. Choose a guide for the work you want to do.
|
|
4
4
|
|
|
5
5
|
Install the [current Slopcamera release](../README.md#install-slopcamera) for the CLI, SDK, and matching Agent Skill. Each guide names its local runtimes and any correction that needs [current source](how-to/use-current-source.md). Some examples import TypeScript from the repository and need a checkout to run. Historical Atet archives retain their original package and commands. The [CLI parity table](cli-parity.md) maps every action of the retired menu-bar companion to a command. The [capability reference](reference/capabilities.md) distinguishes them and lists local runtime requirements.
|
|
6
6
|
|
|
@@ -35,12 +35,15 @@ Install the [current Slopcamera release](../README.md#install-slopcamera) for th
|
|
|
35
35
|
|
|
36
36
|
- [Capabilities, versions, and platforms](reference/capabilities.md): current Slopcamera capabilities, historical Atet versions, and supported runtime boundaries.
|
|
37
37
|
- [SDK surfaces](reference/sdk.md): portable and local imports, operation projections, and execution contracts.
|
|
38
|
+
- [Techniques catalog](https://slopcamera.com/docs/reference/techniques): every packaged technique by job, with its first command, guide, and a rendered example where one exists.
|
|
38
39
|
- [CLI help](reference/capabilities.md#discover-the-installed-contract): exact grammar and JSON schemas from the installed host.
|
|
39
40
|
|
|
40
41
|
## Understand the design
|
|
41
42
|
|
|
42
43
|
- [Source, representations, and projects](architecture.md): what stays editable, what a receipt proves, and how local and cloud work fit together.
|
|
43
44
|
- [Extension architecture](extension-architecture.md): the closed registry, inert recipe packs, trusted workflows, and where authored code can and cannot go.
|
|
45
|
+
- [Why Slopcamera](https://slopcamera.com/docs/explanation/why-slopcamera): why the agent keeps a source file and reuses installed techniques, with comparisons to [Remotion](https://slopcamera.com/docs/explanation/slopcamera-vs-remotion), [HyperFrames](https://slopcamera.com/docs/explanation/slopcamera-vs-hyperframes), and [other tools](https://slopcamera.com/docs/explanation/remotion-alternatives-for-coding-agents).
|
|
46
|
+
- [Token benchmark](https://slopcamera.com/docs/explanation/token-benchmark): agent token use and cost on four media tasks with and without Slopcamera installed, with the harness and raw results in [`bench/token-savings`](../bench/token-savings/README.md).
|
|
44
47
|
- [Choose an HTML authoring surface](html-overlay-creative-toolkit.md): why DOM, vector, Three.js, and explicit GPU profiles serve different jobs. Its ecosystem research is dated separately from its supported locks.
|
|
45
48
|
|
|
46
49
|
## Work with an agent
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hraness/slopcamera",
|
|
3
|
-
"version": "3.8.
|
|
3
|
+
"version": "3.8.1",
|
|
4
4
|
"description": "SlopCamera lets your coding agent make images, diagrams, animation, 3D scenes, and video from source files it can keep revising.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -220,7 +220,7 @@
|
|
|
220
220
|
"typecheck:sdk": "tsc --noEmit -p tsconfig.json",
|
|
221
221
|
"typecheck:desktop": "tsc --noEmit -p apps/desktop/tsconfig.json",
|
|
222
222
|
"lint": "bun run lint:sdk && bun run lint:desktop && bun run lint:api",
|
|
223
|
-
"lint:sdk": "eslint src packages/scene scripts",
|
|
223
|
+
"lint:sdk": "eslint src packages/scene scripts bench",
|
|
224
224
|
"lint:desktop": "eslint apps/desktop/contracts apps/desktop/core apps/desktop/application apps/desktop/code apps/desktop/workflows apps/desktop/html-overlay apps/desktop/cli apps/desktop/qualification apps/desktop/analysis apps/desktop/studio",
|
|
225
225
|
"test": "bun run test:sdk && bun run test:desktop && bun run test:api && bun run --cwd apps/web test",
|
|
226
226
|
"test:sdk": "bun test ./src ./packages/scene",
|
|
@@ -14,14 +14,14 @@ 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.
|
|
17
|
+
Slopcamera installs from its verified release archive: `bun add --global https://github.com/hraness/slopcamera/releases/download/v3.8.0/hraness-slopcamera-3.8.0.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
|
If an update from a previous local archive reports `DependencyLoop`, use Bun's
|
|
20
20
|
[named tarball syntax](https://bun.com/docs/pm/cli/add#tarball-dependencies) with
|
|
21
21
|
the same verified archive:
|
|
22
22
|
|
|
23
23
|
```sh
|
|
24
|
-
bun add --global @hraness/slopcamera@https://github.com/hraness/slopcamera/releases/download/v3.
|
|
24
|
+
bun add --global @hraness/slopcamera@https://github.com/hraness/slopcamera/releases/download/v3.8.0/hraness-slopcamera-3.8.0.tgz
|
|
25
25
|
slopcamera --version
|
|
26
26
|
```
|
|
27
27
|
|
package/src/version.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const SLOPCAMERA_VERSION = "3.8.
|
|
1
|
+
export const SLOPCAMERA_VERSION = "3.8.1" as const
|