@coloopx/colocad 0.1.0-alpha.3 → 0.1.0-alpha.4
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/NOTICE.md +2 -0
- package/README.md +30 -1
- package/README.zh-CN.md +30 -1
- package/bin/colocad.mjs +28 -4
- package/docs/README.md +27 -0
- package/docs/README.zh-CN.md +81 -0
- package/docs/modeling-history.md +60 -0
- package/examples/hiwin-kk60/README.md +55 -0
- package/examples/hiwin-kk60/model.mjs +94 -0
- package/examples/hiwin-kk60/run.mjs +14 -0
- package/examples/hiwin-kk60/sources.json +88 -0
- package/kernel/native/darwin-arm64/agent-cad +1 -1
- package/kernel/native/darwin-arm64/manifest.json +1 -2
- package/kernel/native/linux-arm64/agent-cad +1 -1
- package/kernel/native/linux-arm64/manifest.json +1 -2
- package/kernel/native/linux-x64/agent-cad +2 -2
- package/kernel/native/linux-x64/manifest.json +2 -3
- package/kernel/release.json +4 -4
- package/package.json +37 -4
- package/skills/colocad/SKILL.md +2 -0
- package/skills/colocad/references/history.md +19 -0
- package/src/render.mjs +72 -0
- package/src/session.d.mts +34 -0
- package/src/session.mjs +140 -0
- package/src/view-server.mjs +50 -0
- package/viewer/THREE-LICENSE +21 -0
- package/viewer/dist/index.js +4236 -0
- package/viewer/dist/standalone.js +4236 -0
- package/viewer/index.d.ts +18 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
[diffend] Oversized file quarantined before diffing.
|
|
2
2
|
name: package/kernel/native/linux-x64/agent-cad
|
|
3
|
-
size:
|
|
4
|
-
sha256:
|
|
3
|
+
size: 46383744 bytes
|
|
4
|
+
sha256: 33031163011d5fb73f12366362f74cdb72115e452c66116e5a53bb433eb1779e
|
package/kernel/release.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "0.1.0-alpha.
|
|
2
|
+
"version": "0.1.0-alpha.4",
|
|
3
3
|
"sha256": {
|
|
4
|
-
"
|
|
5
|
-
"linux-
|
|
6
|
-
"
|
|
4
|
+
"darwin-arm64": "e3cbc7abf95cc0911e5e9a1dae565c52e7bafe927f5bf7a42901aa9a48f2bca9",
|
|
5
|
+
"linux-arm64": "9e2e965f2e136d2fe31009738be8c42e98b39ccccf838c6f22b07d7ead39e714",
|
|
6
|
+
"linux-x64": "33031163011d5fb73f12366362f74cdb72115e452c66116e5a53bb433eb1779e"
|
|
7
7
|
}
|
|
8
8
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coloopx/colocad",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.4",
|
|
4
4
|
"description": "Parametric feature instructions, a local Rust B-rep kernel and an experimental SolidWorks author",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -26,7 +26,15 @@
|
|
|
26
26
|
"types": "./kernel/dist/index.d.ts",
|
|
27
27
|
"import": "./kernel/dist/index.js"
|
|
28
28
|
},
|
|
29
|
-
"./schema": "./kernel/schemas/model.schema.json"
|
|
29
|
+
"./schema": "./kernel/schemas/model.schema.json",
|
|
30
|
+
"./session": {
|
|
31
|
+
"types": "./src/session.d.mts",
|
|
32
|
+
"import": "./src/session.mjs"
|
|
33
|
+
},
|
|
34
|
+
"./viewer": {
|
|
35
|
+
"types": "./viewer/index.d.ts",
|
|
36
|
+
"import": "./viewer/dist/index.js"
|
|
37
|
+
}
|
|
30
38
|
},
|
|
31
39
|
"bin": {
|
|
32
40
|
"colocad": "bin/colocad.mjs"
|
|
@@ -47,15 +55,40 @@
|
|
|
47
55
|
"skills/colocad",
|
|
48
56
|
"kernel/release.json",
|
|
49
57
|
"scripts/check-release.mjs",
|
|
50
|
-
"README.zh-CN.md"
|
|
58
|
+
"README.zh-CN.md",
|
|
59
|
+
"viewer/dist",
|
|
60
|
+
"viewer/index.d.ts",
|
|
61
|
+
"viewer/THREE-LICENSE",
|
|
62
|
+
"examples/hiwin-kk60/model.mjs",
|
|
63
|
+
"examples/hiwin-kk60/run.mjs",
|
|
64
|
+
"examples/hiwin-kk60/README.md",
|
|
65
|
+
"examples/hiwin-kk60/sources.json",
|
|
66
|
+
"docs/modeling-history.md"
|
|
51
67
|
],
|
|
52
68
|
"scripts": {
|
|
53
69
|
"test": "node --test test/*.test.mjs",
|
|
54
70
|
"build:kernel": "node scripts/build-kernel.mjs",
|
|
55
|
-
"prepack": "node scripts/check-release.mjs"
|
|
71
|
+
"prepack": "node scripts/check-release.mjs",
|
|
72
|
+
"build:viewer": "node scripts/build-viewer.mjs",
|
|
73
|
+
"test:viewer": "node test/viewer.browser.mjs",
|
|
74
|
+
"test:integrations": "npm test --prefix examples/integrations",
|
|
75
|
+
"test:render": "node test/render.browser.mjs"
|
|
56
76
|
},
|
|
57
77
|
"publishConfig": {
|
|
58
78
|
"access": "public",
|
|
59
79
|
"registry": "https://registry.npmjs.org"
|
|
80
|
+
},
|
|
81
|
+
"devDependencies": {
|
|
82
|
+
"esbuild": "0.28.2",
|
|
83
|
+
"playwright": "1.65.0",
|
|
84
|
+
"three": "0.187.0"
|
|
85
|
+
},
|
|
86
|
+
"peerDependencies": {
|
|
87
|
+
"playwright": ">=1.50.0 <2"
|
|
88
|
+
},
|
|
89
|
+
"peerDependenciesMeta": {
|
|
90
|
+
"playwright": {
|
|
91
|
+
"optional": true
|
|
92
|
+
}
|
|
60
93
|
}
|
|
61
94
|
}
|
package/skills/colocad/SKILL.md
CHANGED
|
@@ -15,3 +15,5 @@ Choose the entry point that matches the model:
|
|
|
15
15
|
- For a `colocad/1` XY feature tree use the project's `node_modules/.bin/colocad plan TREE.json` and `node_modules/.bin/colocad build TREE.json NEW_DIR --preview`. Cuts start at `startZ` and travel along +Z. Linear pattern counts include their seed. This entry point also produces the feature tree and native job in `NEW_DIR/part/`.
|
|
16
16
|
|
|
17
17
|
Return the editable model and STEP. Reopen the STEP and check the dimensions that distinguish success for this task, such as a bore's diameter and axis or a cut reaching the cavity. For a long construction, keep inspectable milestones and a fixed camera. An assembly preview establishes appearance. A fit or motion claim needs the corresponding measurement.
|
|
18
|
+
|
|
19
|
+
For human review of construction steps, use the [persistent history workflow](references/history.md). Record real geometry milestones as well as assembly placements, retain failed attempts, and deliver the offline HTML alongside the editable source and STEP.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Persistent modeling history
|
|
2
|
+
|
|
3
|
+
Use this workflow when the user wants to inspect construction steps or hand off an offline replay. It requires a colocad build that lists `record` and `replay` in `colocad --help`; the older npm alpha.3 CLI does not include these commands.
|
|
4
|
+
|
|
5
|
+
Save each meaningful geometry or assembly milestone as JSON, then run from the project:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
./node_modules/.bin/colocad record model.json ./history --label "Bore the hub"
|
|
9
|
+
./node_modules/.bin/colocad view ./history
|
|
10
|
+
./node_modules/.bin/colocad replay ./history ./history.html
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`record` accepts a kernel model or a `colocad/1` feature tree, appends a real build with a preview, and prints the receipt. Reuse the session directory for later attempts. A failed build exits nonzero and stays in history. Change the cause, then record a corrected attempt; do not delete the failed step to imply uninterrupted success.
|
|
14
|
+
|
|
15
|
+
Choose steps that explain geometry: blank → bore/cut → shaped blade → repeated placements → full assembly. Avoid recording only final part placement if the user asked how the kernel constructed the shape. A milestone is an actual build call; internal feature timings remain in the receipt.
|
|
16
|
+
|
|
17
|
+
The HTML is self-contained and includes orbit/view controls, display-only clipping/explosion, the inputs and receipts, and the final exact STEP. Review playback uses a presentation cadence; recorded call durations are shown separately. Preserve the entire session directory if every intermediate STEP must remain available. A camera change or clipping plane does not modify the saved exact model.
|
|
18
|
+
|
|
19
|
+
For a modeling animation use the same CLI: `colocad render SESSION ./modeling.mp4` (or `.gif`). This requires optional Playwright/Chromium and FFmpeg. It replays actual persisted geometry in four views, preserving measured call times. Review pacing, cutaway and explosion are presentation only. Do not present the film duration as build time or a benchmark.
|
package/src/render.mjs
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { readFile,writeFile,mkdir,mkdtemp,rm,copyFile,access } from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { resolve,join,extname } from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { once } from 'node:events';
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { readSessionBundle } from './session.mjs';
|
|
10
|
+
export function parseRenderOptions(args){
|
|
11
|
+
const options={width:1440,height:900,fps:20,secondsPerStep:1.5};
|
|
12
|
+
const keys={'--width':['width',640,3840,true],'--height':['height',480,2160,true],'--fps':['fps',1,60,false],'--seconds-per-step':['secondsPerStep',.1,30,false]};
|
|
13
|
+
for(let i=0;i<args.length;i++){const key=keys[args[i]];if(!key)throw Error('Unknown render option: '+args[i]);const value=Number(args[++i]);if(!Number.isFinite(value)||value<key[1]||value>key[2]||(key[0]!=='secondsPerStep'&&!Number.isInteger(value))||(key[3]&&value%2))throw Error('Invalid render option: '+key[0]);options[key[0]]=value;}
|
|
14
|
+
return options;
|
|
15
|
+
}
|
|
16
|
+
export function filmFrames(steps,{fps=20,secondsPerStep=1.5}={}){
|
|
17
|
+
const frames=[],last=Math.max(0,steps.findLastIndex(s=>s.status==='succeeded'));
|
|
18
|
+
const add=(step,duration,phase)=>{const count=Math.max(1,Math.round(duration*fps));for(let i=0;i<count;i++)frames.push({step,phase,progress:i/Math.max(count-1,1)});};
|
|
19
|
+
add(last,2,'intro');for(let i=0;i<steps.length;i++)add(i,secondsPerStep,'history');add(last,4,'assembly');return frames;
|
|
20
|
+
}
|
|
21
|
+
const escapeJson=x=>JSON.stringify(x).replaceAll('<','\\u003c').replaceAll('\u2028','\\u2028').replaceAll('\u2029','\\u2029');
|
|
22
|
+
async function movieHtml(bundle){
|
|
23
|
+
const runtime=await readFile(new URL('../viewer/dist/standalone.js',import.meta.url),'utf8');
|
|
24
|
+
// Geometry and exact downloads already live in the persisted session; movie only needs meshes/receipts.
|
|
25
|
+
for(const s of bundle.steps){delete s.stepFile;delete s.png;}
|
|
26
|
+
return `<!doctype html><html lang="en"><meta charset="utf-8"><style>
|
|
27
|
+
*{box-sizing:border-box}body{margin:0;background:#0b1423;color:#e1eaf4;font:14px system-ui,sans-serif;overflow:hidden}main{height:100vh;padding:25px 30px;display:grid;grid-template-rows:58px 1fr 48px;gap:16px}header{display:flex;align-items:center;gap:22px}.brand{font-size:22px;letter-spacing:3px;font-weight:800}.brand span{color:#64d5c5}.title{font-size:15px;color:#9fb2c7}.tag{margin-left:auto;color:#70d5c7;font-size:11px;letter-spacing:1px}.body{display:grid;grid-template-columns:1fr 290px;gap:22px;min-height:0}.views{display:grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;gap:12px;min-height:0}.view{position:relative;border:1px solid #395166;border-radius:12px;overflow:hidden;background:#c7d5de;min-height:0}.camera{position:absolute;left:14px;top:13px;color:#244054;z-index:3;font-size:10px;letter-spacing:1.6px;font-weight:700;pointer-events:none}colocad-viewer{height:100%;min-height:0!important}.panel{padding:4px 0;display:flex;flex-direction:column;min-height:0}.eyebrow{font-size:10px;letter-spacing:2px;color:#65ccbf}.label{font-size:23px;font-weight:550;line-height:1.3;margin:12px 0 17px}.metrics{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:18px}.metric{border-top:1px solid #294057;padding-top:9px;color:#8fa6bd;font-size:9px;letter-spacing:.8px}.metric b{display:block;color:#f0f5fb;font-size:24px;letter-spacing:0;font-weight:550;margin-bottom:2px}.journal{flex:1;min-height:0;overflow:hidden}.entry{font-size:10px;color:#71889f;margin:7px 0;line-height:1.35;display:flex;gap:8px}.entry.active{color:#83e5d6}.entry.done{color:#c0cede}.number{width:18px;flex-shrink:0;font-variant-numeric:tabular-nums}.status{color:#74d4bf;font-size:11px;margin-top:12px}.note{color:#8fa6bd;font-size:10px;line-height:1.5;margin-top:8px}.bottom{display:flex;align-items:center;gap:20px;color:#92a8bf;font-size:10px;border-top:1px solid #2c4056;padding-top:12px}.progress{height:3px;background:#244055;position:absolute;bottom:0;left:0;width:100%}.fill{height:100%;background:#6dd5c5;width:0}.caption{margin-left:auto;font-size:11px;color:#c2d8e7}.stamp{color:#6fdac9}
|
|
28
|
+
</style><main><header><div class="brand">COLOCAD <span>/</span></div><div class="title"></div><div class="tag">NATIVE B-REP · FOUR VIEWS</div></header><div class="body"><div class="views">${['ISOMETRIC','END / Z AXIS','SIDE / SECTION DISPLAY','TOP / Y AXIS'].map(label=>`<div class="view"><div class="camera">${label}</div><colocad-viewer></colocad-viewer></div>`).join('')}</div><aside class="panel"><div class="eyebrow">PERSISTED MODELING SESSION</div><div class="label"></div><div class="metrics"></div><div class="journal"></div><div class="status"></div><div class="note">Recorded geometry, not image generation.<br>Review pacing is edited; call times are measured.<br>Section and explosion are display controls.</div></aside></div><div class="bottom"><span class="stamp">SDK → LOCAL RUST → STEP → RECORDED MESH</span><span>Model source and receipts retained in the session</span><span class="caption"></span></div></main><div class="progress"><div class="fill"></div></div><script id="data" type="application/json">${escapeJson(bundle)}</script><script>${runtime.replaceAll('</script','<\\/script')}</script><script>
|
|
29
|
+
const data=JSON.parse(document.getElementById('data').textContent),views=[...document.querySelectorAll('colocad-viewer')],cameras=['iso','front','side','top'];
|
|
30
|
+
document.querySelector('.title').textContent=data.title;
|
|
31
|
+
for(let i=0;i<views.length;i++){const v=views[i];v.session=data;const style=document.createElement('style');style.textContent=':host{min-height:0!important}.shell{display:block}.layout{display:block;height:100%}.stage{display:block;height:100%}.viewport{height:100%;min-height:0}header,footer,.timeline,.inspector,.stage-head,.controls,.viewbar,.watermark{display:none!important}';v.shadowRoot.append(style);v.controls.enableDamping=false;v.setProjection('orthographic');v.setSectionAxis('x');cancelAnimationFrame(v.frame);}
|
|
32
|
+
let last=-1;window.filmFrame=({step,phase,progress},frame,total)=>{
|
|
33
|
+
const s=data.steps[step];if(step!==last){for(const v of views)v.setStep(step);last=step;}
|
|
34
|
+
const explode=phase==='assembly'?70*Math.sin(Math.PI*progress)**2:phase==='history'&&s.kind==='assembly'?30*(1-progress)**2:0;
|
|
35
|
+
for(let i=0;i<views.length;i++){const v=views[i];v.cutaway=i===2;v.exploded=explode;v.applyDisplay();v.setView(cameras[i]);if(v.renderer&&v.center){v.camera.lookAt(v.center);v.resize();v.renderer.render(v.scene,v.camera);}}
|
|
36
|
+
document.querySelector('.label').textContent=phase==='intro'?'A complete product, built from features':phase==='assembly'?'Inspect the finished assembly':s.label;
|
|
37
|
+
const metrics=document.querySelector('.metrics');metrics.replaceChildren();for(const [name,value] of [['SOLIDS',s.geometry?.solids??'—'],['FEATURES',s.model?.features?.length??'—'],['THIS CALL',(s.durationMs/1000).toFixed(3)+' s'],['RECORDED CALLS',(data.steps.slice(0,step+1).reduce((n,x)=>n+(x.durationMs??0),0)/1000).toFixed(2)+' s']]){const d=document.createElement('div');d.className='metric';const b=document.createElement('b');b.textContent=value;d.append(b,document.createTextNode(name));metrics.append(d);}
|
|
38
|
+
const journal=document.querySelector('.journal');journal.replaceChildren();const count=Math.max(2,Math.min(12,Math.floor(journal.clientHeight/30)));const start=Math.max(0,Math.min(step-Math.floor(count/2),data.steps.length-count));for(let n=start;n<Math.min(data.steps.length,start+count);n++){const d=document.createElement('div');d.className='entry '+(n===step?'active':n<step?'done':'');const num=document.createElement('span');num.className='number';num.textContent=String(n+1).padStart(2,'0');d.append(num,document.createTextNode(data.steps[n].label));journal.append(d);}
|
|
39
|
+
document.querySelector('.status').textContent=s.status.toUpperCase()+' · '+s.id+' · '+s.kind;
|
|
40
|
+
document.querySelector('.caption').textContent=phase==='assembly'?'Explode → reassemble · source geometry unchanged':'Saved revision '+(step+1)+' / '+data.steps.length+' · mm';document.querySelector('.fill').style.width=100*(frame+1)/total+'%';
|
|
41
|
+
return views.map(v=>v.getState());};window.filmReady=views.every(v=>v.renderer);
|
|
42
|
+
</script></html>`;
|
|
43
|
+
}
|
|
44
|
+
async function command(binary,args){
|
|
45
|
+
const child=spawn(binary,args,{stdio:['ignore','pipe','pipe']});let out='',err='';child.stdout.on('data',x=>out+=x);child.stderr.on('data',x=>err=(err+x).slice(-6000));
|
|
46
|
+
const [code]=await once(child,'close');if(code!==0)throw Error(binary+' failed: '+err);return out;
|
|
47
|
+
}
|
|
48
|
+
export async function renderSession(directory,destination,options={}){
|
|
49
|
+
const settings=parseRenderOptions(Object.entries(options).flatMap(([k,v])=>[({width:'--width',height:'--height',fps:'--fps',secondsPerStep:'--seconds-per-step'})[k]??k,String(v)]));
|
|
50
|
+
const output=resolve(destination),extension=extname(output).toLowerCase();if(!['.mp4','.gif'].includes(extension))throw Error('render output must be .mp4 or .gif');
|
|
51
|
+
try{await access(output);throw Error('Output already exists: '+output);}catch(e){if(e.code!=='ENOENT')throw e;}
|
|
52
|
+
let chromium;try{({chromium}=await import('playwright'));}catch{throw Error('Movie export needs optional Playwright: npm install -D playwright && npx playwright install chromium');}
|
|
53
|
+
try{await command('ffmpeg',['-version']);}catch{throw Error('Movie export needs FFmpeg on PATH');}
|
|
54
|
+
const bundle=await readSessionBundle(directory);if(!bundle.steps.length)throw Error('Session has no steps');
|
|
55
|
+
const frames=filmFrames(bundle.steps,settings),temp=await mkdtemp(join(tmpdir(),'colocad-film-'));let browser,encoder;const errors=[];
|
|
56
|
+
try{
|
|
57
|
+
const html=join(temp,'film.html');await writeFile(html,await movieHtml(bundle));
|
|
58
|
+
try{browser=await chromium.launch({headless:true});}catch{throw Error('Chromium unavailable; run npx playwright install chromium');}
|
|
59
|
+
const page=await browser.newPage({viewport:{width:settings.width,height:settings.height},deviceScaleFactor:1});page.on('pageerror',e=>errors.push(e.message));await page.goto(pathToFileURL(html).href);await page.waitForFunction(()=>window.filmReady===true,{},{timeout:30000});
|
|
60
|
+
const mp4=join(temp,'film.mp4');encoder=spawn('ffmpeg',['-y','-hide_banner','-loglevel','error','-f','image2pipe','-vcodec','png','-framerate',String(settings.fps),'-i','pipe:0','-an','-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',mp4],{stdio:['pipe','ignore','pipe']});
|
|
61
|
+
let poster;let stderr='';encoder.stderr.on('data',x=>stderr=(stderr+x).slice(-6000));encoder.stdin.on('error',()=>{});const closed=once(encoder,'close');closed.catch(()=>{});
|
|
62
|
+
for(let i=0;i<frames.length;i++){await page.evaluate(({frame,i,total})=>window.filmFrame(frame,i,total),{frame:frames[i],i,total:frames.length});const png=await page.screenshot({type:'png'});if(i===0)poster=png;if(!encoder.stdin.write(png))await once(encoder.stdin,'drain');if(i%Math.max(1,settings.fps*5)===0)process.stderr.write(JSON.stringify({event:'render-progress',frame:i+1,frames:frames.length})+'\n');}
|
|
63
|
+
encoder.stdin.end();const [code]=await closed;if(code!==0)throw Error('FFmpeg failed: '+stderr);if(errors.length)throw Error('Viewer errors: '+errors.join('; '));
|
|
64
|
+
let rendered=mp4;
|
|
65
|
+
if(extension==='.gif'){
|
|
66
|
+
const palette=join(temp,'palette.png');await command('ffmpeg',['-y','-v','error','-i',mp4,'-vf','palettegen=stats_mode=diff','-frames:v','1',palette]);
|
|
67
|
+
rendered=join(temp,'film.gif');await command('ffmpeg',['-y','-v','error','-i',mp4,'-i',palette,'-lavfi','paletteuse=dither=bayer:bayer_scale=4','-loop','0',rendered]);
|
|
68
|
+
}
|
|
69
|
+
const bytes=await readFile(rendered),metadata={format:'colocad/film/1',file:output,sha256:createHash('sha256').update(bytes).digest('hex'),bytes:bytes.length,...settings,frames:frames.length,durationSeconds:frames.length/settings.fps,reviewTiming:'edited pacing; not a benchmark',steps:bundle.steps.map(s=>({id:s.id,label:s.label,status:s.status,durationMs:s.durationMs,inputSha256:s.inputSha256,receiptSha256:s.receiptSha256})),browserErrors:errors};
|
|
70
|
+
await mkdir(resolve(output,'..'),{recursive:true});await copyFile(rendered,output,constants.COPYFILE_EXCL);await writeFile(output+'.poster.png',poster);await writeFile(output+'.json',JSON.stringify(metadata,null,2)+'\n');return metadata;
|
|
71
|
+
}finally{encoder?.kill('SIGTERM');await browser?.close();await rm(temp,{recursive:true,force:true});}
|
|
72
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Config, Model, Receipt, PreviewOptions, Sketch } from '../kernel/dist/types.js';
|
|
2
|
+
export interface StepMetadata { label?: string; kind?: string; }
|
|
3
|
+
export interface SessionStep {
|
|
4
|
+
id: string; label: string; kind: string; operation: 'build'|'edit'|'observe';
|
|
5
|
+
status: 'running'|'succeeded'|'failed'|'interrupted'; startedAt: string;
|
|
6
|
+
finishedAt?: string; durationMs?: number; inputFile: string; inputSha256: string;
|
|
7
|
+
receiptFile?: string; receiptSha256?: string; artifactDirectory?: string;
|
|
8
|
+
geometry?: Record<string, unknown>; error?: { code: string; message: string };
|
|
9
|
+
nativeTimingMs?: Record<string, unknown>; degradations?: Record<string, unknown>[];
|
|
10
|
+
requestedParameters?: Record<string, number>;
|
|
11
|
+
}
|
|
12
|
+
export interface SessionLedger { format: 'colocad/session/1'; id: string; title: string; createdAt: string; steps: SessionStep[]; }
|
|
13
|
+
export type SessionConfig = Omit<Config, 'outputRoot'>;
|
|
14
|
+
export type RecordedReceipt = Receipt & { session_step: string };
|
|
15
|
+
export class ModelingSession {
|
|
16
|
+
readonly root: string;
|
|
17
|
+
static create(directory: string, options?: SessionConfig & {title?: string}): Promise<ModelingSession>;
|
|
18
|
+
static open(directory: string, options?: SessionConfig): Promise<ModelingSession>;
|
|
19
|
+
read(): Promise<SessionLedger>;
|
|
20
|
+
source(): Promise<Model>;
|
|
21
|
+
build(model: Model, metadata?: StepMetadata): Promise<RecordedReceipt>;
|
|
22
|
+
edit(parameters: Record<string, number>, metadata?: StepMetadata): Promise<RecordedReceipt>;
|
|
23
|
+
preview(model: Model, options?: Partial<PreviewOptions>, metadata?: StepMetadata): Promise<RecordedReceipt>;
|
|
24
|
+
observe(options?: Partial<PreviewOptions>, metadata?: StepMetadata): Promise<RecordedReceipt>;
|
|
25
|
+
capabilities(): Promise<Receipt>; schema(): Promise<Receipt>; validate(model: Model): Promise<Receipt>;
|
|
26
|
+
solveSketch(sketch: Sketch, parameters?: Record<string,number>): Promise<Receipt>;
|
|
27
|
+
inspectStep(model: Model, asset: string): Promise<Receipt>;
|
|
28
|
+
}
|
|
29
|
+
export function createSessionTools(session: ModelingSession): Promise<Array<{
|
|
30
|
+
name: string; description: string; inputSchema: Record<string,unknown>;
|
|
31
|
+
execute(args: any): Promise<Receipt>;
|
|
32
|
+
}>>;
|
|
33
|
+
export function readSessionBundle(directory: string, options?: {cutaway?: boolean; view?: 'iso'|'front'|'side'|'top'}): Promise<Record<string, any>>;
|
|
34
|
+
export function exportSessionHtml(directory: string, destination: string, options?: {cutaway?: boolean; view?: 'iso'|'front'|'side'|'top'}): Promise<{file: string; steps: number; meshDefinitions: number; bytes: number}>;
|
package/src/session.mjs
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile, rename, rm, realpath } from 'node:fs/promises';
|
|
2
|
+
import { resolve, join, relative, isAbsolute, sep } from 'node:path';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { performance } from 'node:perf_hooks';
|
|
5
|
+
import { CadClient, createCadTools } from './index.mjs';
|
|
6
|
+
|
|
7
|
+
const format='colocad/session/1';
|
|
8
|
+
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
9
|
+
const json=value=>JSON.stringify(value,null,2)+'\n';
|
|
10
|
+
async function atomic(file,value){const temp=file+'.'+randomUUID()+'.tmp';await writeFile(temp,json(value));await rename(temp,file);}
|
|
11
|
+
async function load(file){return JSON.parse(await readFile(file,'utf8'));}
|
|
12
|
+
function inside(root,path){
|
|
13
|
+
if(typeof path!=='string'||isAbsolute(path)||path.split(/[\\/]/).includes('..'))throw Error('SESSION_PATH: expected relative artifact path');
|
|
14
|
+
const target=resolve(root,path);if(target!==root&&!target.startsWith(root+sep))throw Error('SESSION_PATH');return target;
|
|
15
|
+
}
|
|
16
|
+
async function checked(root,path,hash){
|
|
17
|
+
const file=inside(root,path),actual=await realpath(file),base=await realpath(root);
|
|
18
|
+
if(!actual.startsWith(base+sep))throw Error('SESSION_PATH: symlink leaves session');
|
|
19
|
+
const bytes=await readFile(file);if(hash&&sha(bytes)!==hash)throw Error('SESSION_INTEGRITY: '+path);return bytes;
|
|
20
|
+
}
|
|
21
|
+
function alive(pid){if(!Number.isInteger(pid)||pid<1)return true;try{process.kill(pid,0);return true;}catch(e){return e.code!=='ESRCH';}}
|
|
22
|
+
|
|
23
|
+
export class ModelingSession {
|
|
24
|
+
constructor(root,config={}){this.root=resolve(root);this.config=config;this.cad=new CadClient({...config,outputRoot:join(this.root,'artifacts')});}
|
|
25
|
+
static async create(directory,{title='CAD modeling session',...config}={}){
|
|
26
|
+
const s=new ModelingSession(directory,config);await mkdir(s.root,{recursive:true});
|
|
27
|
+
await writeFile(join(s.root,'session.json'),json({format,id:randomUUID(),title,createdAt:new Date().toISOString(),steps:[]}),{flag:'wx'});return s;
|
|
28
|
+
}
|
|
29
|
+
static async open(directory,config={}){
|
|
30
|
+
const s=new ModelingSession(directory,config);await s.read();
|
|
31
|
+
await s.lock(async()=>{const ledger=await s.read();let changed=false;
|
|
32
|
+
for(const step of ledger.steps)if(step.status==='running'){Object.assign(step,{status:'interrupted',finishedAt:new Date().toISOString(),error:{code:'INTERRUPTED',message:'Previous process ended before committing its result'}});changed=true;}
|
|
33
|
+
if(changed)await atomic(join(s.root,'session.json'),ledger);
|
|
34
|
+
},true);return s;
|
|
35
|
+
}
|
|
36
|
+
async read(){const ledger=await load(join(this.root,'session.json'));if(ledger.format!==format||!Array.isArray(ledger.steps))throw Error('SESSION_FORMAT: unsupported ledger');return ledger;}
|
|
37
|
+
async lock(fn,recover=false){
|
|
38
|
+
const file=join(this.root,'.writer.lock');
|
|
39
|
+
if(recover){try{const owner=await load(file);if(!alive(owner.pid))await rm(file);}catch(e){if(e.code!=='ENOENT')throw e;}}
|
|
40
|
+
try{await writeFile(file,json({pid:process.pid}),{flag:'wx'});}catch(e){if(e.code==='EEXIST')throw Error('SESSION_BUSY: another local writer owns this session');throw e;}
|
|
41
|
+
try{return await fn();}finally{await rm(file,{force:true});}
|
|
42
|
+
}
|
|
43
|
+
async source(){const l=await this.read(),s=l.steps.findLast(x=>x.status==='succeeded'&&x.operation!=='observe');if(!s)throw Error('SESSION_EMPTY: build a model first');return JSON.parse(await checked(this.root,s.inputFile,s.inputSha256));}
|
|
44
|
+
async latestGeometry(){return (await this.read()).steps.findLast(x=>x.status==='succeeded'&&x.operation!=='observe');}
|
|
45
|
+
async build(model,metadata={}){const input=structuredClone(model);return this.lock(()=>this.run(input,'build',metadata));}
|
|
46
|
+
async edit(parameters,metadata={}){return this.lock(async()=>{
|
|
47
|
+
const model=await this.source();
|
|
48
|
+
// Keep invalid edits in history too; the native validator provides the receipt.
|
|
49
|
+
for(const key of Object.keys(parameters))if(!Object.hasOwn(model.parameters,key))return this.run(model,'edit',metadata,{ok:false,error:{code:'UNKNOWN_PARAMETER',message:key}},parameters);
|
|
50
|
+
model.parameters={...model.parameters,...parameters};return this.run(model,'edit',metadata,undefined,parameters);
|
|
51
|
+
});}
|
|
52
|
+
async preview(model,options={},metadata={}){return this.lock(async()=>{
|
|
53
|
+
const next=structuredClone(model);next.preview={...next.preview,...options};const last=await this.latestGeometry();
|
|
54
|
+
if(last){const prior=await this.source(),clean=x=>{const v=structuredClone(x);delete v.preview;return v;};
|
|
55
|
+
if(JSON.stringify(clean(prior))===JSON.stringify(clean(next))&&(prior.preview?.chord_mm??.2)===(next.preview.chord_mm??.2)&&(prior.preview?.pose??'normal')===(next.preview.pose??'normal'))return this.run(next,'observe',metadata);
|
|
56
|
+
}return this.run(next,'build',metadata);
|
|
57
|
+
});}
|
|
58
|
+
async observe(options={},metadata={}){return this.lock(async()=>{const model=await this.source();model.preview={...model.preview,...options};return this.run(model,'observe',metadata);});}
|
|
59
|
+
async run(model,operation,{label=operation,kind=operation==='observe'?'inspection':'geometry'}={},preset,requestedParameters){
|
|
60
|
+
const ledger=await this.read(),id='s'+String(ledger.steps.length+1).padStart(4,'0'),dir=join('steps',id);
|
|
61
|
+
await mkdir(join(this.root,dir),{recursive:true});
|
|
62
|
+
if(operation!=='observe')model.preview={view:'iso',chord_mm:.6,width:960,height:640,...model.preview};
|
|
63
|
+
const bytes=json(model);await writeFile(join(this.root,dir,'input.json'),bytes);
|
|
64
|
+
const step={id,label:String(label),kind:String(kind),operation,status:'running',startedAt:new Date().toISOString(),inputFile:dir+'/input.json',inputSha256:sha(bytes),receiptFile:dir+'/receipt.json'};
|
|
65
|
+
if(requestedParameters)step.requestedParameters=requestedParameters;
|
|
66
|
+
ledger.steps.push(step);await atomic(join(this.root,'session.json'),ledger);
|
|
67
|
+
const start=performance.now();let result;
|
|
68
|
+
try{
|
|
69
|
+
const previous=ledger.steps.slice(0,-1).findLast(x=>x.status==='succeeded'&&x.operation!=='observe');
|
|
70
|
+
result=preset??await (operation==='observe'
|
|
71
|
+
?this.cad.observeArtifact(inside(this.root,previous.artifactDirectory),model.preview)
|
|
72
|
+
:this.cad.build(model,previous?inside(this.root,previous.artifactDirectory):undefined));
|
|
73
|
+
}catch(e){result={ok:false,error:{code:'SESSION_EXECUTION_FAILED',message:String(e.message)}};}
|
|
74
|
+
step.durationMs=performance.now()-start;step.finishedAt=new Date().toISOString();step.status=result.ok?'succeeded':'failed';
|
|
75
|
+
const saved=structuredClone(result);
|
|
76
|
+
if(result.ok){
|
|
77
|
+
step.artifactDirectory=relative(this.root,result.data.artifact_directory).split(sep).join('/');inside(this.root,step.artifactDirectory);
|
|
78
|
+
saved.data.artifact_directory=step.artifactDirectory;
|
|
79
|
+
if(saved.data.source_artifact_directory)saved.data.source_artifact_directory=relative(this.root,saved.data.source_artifact_directory).split(sep).join('/');
|
|
80
|
+
step.geometry=result.data.geometry;step.nativeTimingMs=result.data.timing_ms;
|
|
81
|
+
step.degradations=result.data.features?.filter(x=>x.degradation).map(x=>({id:x.id,...x.degradation}));
|
|
82
|
+
}else step.error=result.error;
|
|
83
|
+
const receiptBytes=json(saved);step.receiptSha256=sha(receiptBytes);
|
|
84
|
+
await writeFile(join(this.root,step.receiptFile),receiptBytes);await atomic(join(this.root,'session.json'),ledger);
|
|
85
|
+
return {...result,session_step:id};
|
|
86
|
+
}
|
|
87
|
+
capabilities(){return this.cad.capabilities();} schema(){return this.cad.schema();} validate(m){return this.cad.validate(m);}
|
|
88
|
+
solveSketch(s,p){return this.cad.solveSketch(s,p);} inspectStep(m,a){return this.cad.inspectStep(m,a);}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function createSessionTools(session) {
|
|
92
|
+
const tools=await createCadTools(session.cad);
|
|
93
|
+
for(const tool of tools){
|
|
94
|
+
if(tool.name==='cad_build')tool.execute=({model})=>session.build(model,{label:'Agent build'});
|
|
95
|
+
if(tool.name==='cad_preview')tool.execute=({model,options})=>session.preview(model,options,{label:'Agent preview'});
|
|
96
|
+
if(tool.name==='cad_edit'){
|
|
97
|
+
delete tool.inputSchema.properties.model;
|
|
98
|
+
tool.inputSchema.required=['parameters'];
|
|
99
|
+
tool.description='Edit numeric parameters of the latest successful recorded model; preserve failed attempts and return a new revision.';
|
|
100
|
+
tool.execute=({parameters})=>session.edit(parameters,{label:'Agent parameter edit'});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return tools;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function readSessionBundle(directory,{cutaway=false,view='iso'}={}){
|
|
107
|
+
const root=resolve(directory),ledger=await load(join(root,'session.json'));
|
|
108
|
+
if(ledger.format!==format)throw Error('SESSION_FORMAT');
|
|
109
|
+
const bundle={format:'colocad/viewer/1',title:ledger.title,id:ledger.id,createdAt:ledger.createdAt,display:{cutaway,view},steps:[],meshes:{}};
|
|
110
|
+
const last=ledger.steps.findLast(x=>x.status==='succeeded'&&x.operation!=='observe');
|
|
111
|
+
for(const entry of ledger.steps){
|
|
112
|
+
const step={...entry};
|
|
113
|
+
if(entry.inputFile)step.model=JSON.parse(await checked(root,entry.inputFile,entry.inputSha256));
|
|
114
|
+
if(entry.receiptFile&&entry.receiptSha256)step.receipt=JSON.parse(await checked(root,entry.receiptFile,entry.receiptSha256));
|
|
115
|
+
if(entry.status==='succeeded'){
|
|
116
|
+
const data=step.receipt.data,artifact=entry.artifactDirectory;inside(root,artifact);
|
|
117
|
+
// Observation results keep their original exact-geometry source for later lookup.
|
|
118
|
+
const source=data.source_artifact_directory??artifact;
|
|
119
|
+
const sourceReport=source===artifact?data:await load(inside(root,source+'/report.json'));
|
|
120
|
+
const hash=sourceReport.artifact_sha256?.['preview.mesh.json'];
|
|
121
|
+
if(!hash)throw Error('SESSION_INTEGRITY: missing native preview mesh hash');
|
|
122
|
+
const scene=JSON.parse(await checked(root,source+'/preview.mesh.json',hash));
|
|
123
|
+
step.scene={instances:scene.instances?.length?scene.instances:scene.meshes.map(([id])=>({id,definition:id,origin:[0,0,0],axes:[[1,0,0],[0,1,0],[0,0,1]]})),definitions:{}};
|
|
124
|
+
for(const [id,mesh] of scene.meshes){const key=sha(JSON.stringify(mesh));bundle.meshes[key]??=mesh;step.scene.definitions[id]=key;}
|
|
125
|
+
if(data.artifact_sha256?.['preview.png'])step.png='data:image/png;base64,'+(await checked(root,artifact+'/preview.png',data.artifact_sha256['preview.png'])).toString('base64');
|
|
126
|
+
if(entry.id===last?.id)step.stepFile=(await checked(root,source+'/model.step',sourceReport.artifact_sha256['model.step'])).toString('base64');
|
|
127
|
+
}
|
|
128
|
+
bundle.steps.push(step);
|
|
129
|
+
}
|
|
130
|
+
return bundle;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function exportSessionHtml(directory,destination,options={}){
|
|
134
|
+
const bundle=await readSessionBundle(directory,options);
|
|
135
|
+
const runtime=await readFile(new URL('../viewer/dist/standalone.js',import.meta.url),'utf8');
|
|
136
|
+
const payload=JSON.stringify(bundle).replaceAll('<','\\u003c').replaceAll('\u2028','\\u2028').replaceAll('\u2029','\\u2029');
|
|
137
|
+
const html='<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>colocad modeling history</title><style>html,body{margin:0;height:100%;background:#0a1220}colocad-viewer{display:block;height:100vh}</style><colocad-viewer></colocad-viewer><script id="colocad-session" type="application/json">'+payload+'</script><script>'+runtime.replaceAll('</script','<\\/script')+'</script><script>document.querySelector("colocad-viewer").session=JSON.parse(document.getElementById("colocad-session").textContent);</script></html>';
|
|
138
|
+
await mkdir(resolve(destination,'..'),{recursive:true});await writeFile(destination,html);
|
|
139
|
+
return {file:resolve(destination),steps:bundle.steps.length,meshDefinitions:Object.keys(bundle.meshes).length,bytes:Buffer.byteLength(html)};
|
|
140
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { mkdtemp,readFile,rm } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join,resolve } from 'node:path';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { exportSessionHtml } from './session.mjs';
|
|
7
|
+
|
|
8
|
+
export function parseViewOptions(args){
|
|
9
|
+
const options={port:0,open:true,cutaway:false,view:'iso'};
|
|
10
|
+
for(let i=0;i<args.length;i++){
|
|
11
|
+
const arg=args[i];
|
|
12
|
+
if(arg==='--no-open')options.open=false;
|
|
13
|
+
else if(arg==='--cutaway')options.cutaway=true;
|
|
14
|
+
else if(arg==='--port'){
|
|
15
|
+
const value=args[++i];if(!/^\d+$/.test(value??'')||Number(value)>65535)throw Error('--port must be an integer from 0 to 65535');options.port=Number(value);
|
|
16
|
+
}else if(arg==='--export'){
|
|
17
|
+
const value=args[++i];if(!value||value.startsWith('--'))throw Error('--export requires an HTML path');options.export=resolve(value);
|
|
18
|
+
}else if(arg==='--view'){
|
|
19
|
+
const value=args[++i];if(!['iso','front','side','top'].includes(value))throw Error('--view must be iso, front, side or top');options.view=value;
|
|
20
|
+
}else throw Error('Unknown viewer option: '+arg);
|
|
21
|
+
}
|
|
22
|
+
return options;
|
|
23
|
+
}
|
|
24
|
+
function openBrowser(url){
|
|
25
|
+
const command=process.platform==='darwin'?'open':process.platform==='win32'?'cmd':'xdg-open';
|
|
26
|
+
const args=process.platform==='win32'?['/c','start','',url]:[url];
|
|
27
|
+
const child=spawn(command,args,{stdio:'ignore'});
|
|
28
|
+
child.on('error',()=>process.stderr.write('Browser could not be opened; use the printed viewer URL.\n'));
|
|
29
|
+
child.on('exit',code=>{if(code)process.stderr.write('Browser opener exited '+code+'; use the printed viewer URL.\n');});
|
|
30
|
+
child.unref();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function startViewer(directory,options={}){
|
|
34
|
+
const root=resolve(directory),temp=await mkdtemp(join(tmpdir(),'colocad-view-'));
|
|
35
|
+
const htmlPath=options.export??join(temp,'history.html');let html,server;
|
|
36
|
+
try{
|
|
37
|
+
await exportSessionHtml(root,htmlPath,{cutaway:options.cutaway??false,view:options.view??'iso'});html=await readFile(htmlPath);
|
|
38
|
+
server=createServer((request,response)=>{
|
|
39
|
+
const path=new URL(request.url,'http://127.0.0.1').pathname;
|
|
40
|
+
if(path==='/favicon.ico'){response.writeHead(204);response.end();return;}
|
|
41
|
+
if(path!=='/'||!['GET','HEAD'].includes(request.method)){response.writeHead(404);response.end('Not found');return;}
|
|
42
|
+
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8','Content-Length':html.length,'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});
|
|
43
|
+
response.end(request.method==='HEAD'?undefined:html);
|
|
44
|
+
});
|
|
45
|
+
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(options.port??0,'127.0.0.1',resolve);});
|
|
46
|
+
}catch(error){await rm(temp,{recursive:true,force:true});throw error;}
|
|
47
|
+
const address=server.address(),url='http://127.0.0.1:'+address.port+'/';
|
|
48
|
+
if(options.open!==false)openBrowser(url);
|
|
49
|
+
return {url,exportedHtml:options.export??null,async close(){await new Promise(resolve=>{server.close(resolve);server.closeAllConnections();});await rm(temp,{recursive:true,force:true});}};
|
|
50
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License
|
|
2
|
+
|
|
3
|
+
Copyright © 2010-2026 three.js authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|