spi3der 26.11.20001 → 26.11.20005

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vívó Péter
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 all
13
+ 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 THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -4,6 +4,16 @@ Interactive 3D creation and exploration, powered by **3Draft**. Based on the 202
4
4
 
5
5
  The editor opens with **no scene** and **does not request VR** until you choose Enter XR. WebXR/Meta Quest and ViRtuSH hand interactions remain available. The scene picker offers **Globe**, **Deep Sky** and **Fifth Percent VR (LARK + Deep Sky)**. Model-format tooling is retained.
6
6
 
7
+ ## ChatGPT-native MCP App Workshop (current direction)
8
+
9
+ The **primary** spi3der workshop is a 3D viewport rendered **inside the ChatGPT conversation**, via the MCP Apps resource `ui://spi3der/workshop-v1.html` (`text/html;profile=mcp-app`). The `open_workshop` tool attaches `_meta.ui.resourceUri` and the ChatGPT compatibility key `openai/outputTemplate`; its output includes the scene geometry in `structuredContent`. No second editor or chatbot sidebar is required.
10
+
11
+ The embedded widget initially provides a simple shaded mesh view, orbit and zoom; camera state stays local to the widget. The agent generates/edit models with the 3Draft `build_model` operations and can call `open_workshop` with a sequence of steps and `from` pointing to an earlier model. The model currently travels in the MCP tool result, **not** through a persistent live multiplayer session. In-widget geometry manipulation and automatic bidirectional sync are not implemented yet.
12
+
13
+ Server: `api/mcp.mjs`, adapter: `mcp/workshop-app.js`, widget: `mcp/workshop-widget.js`, contract test: `npm run test:mcp-app`. For ChatGPT the remote MCP endpoint must be deployed and reconnected/refreshed as a custom plugin. Source commits alone do not enable the widget in a running ChatGPT conversation.
14
+
15
+ The earlier `workshop.html` / `npm run workshop` prototype is *legacy diagnostics*, not the product direction. Do not rebuild or polish its extra UI.
16
+
7
17
  ## Run locally
8
18
 
9
19
  ```sh
@@ -25,7 +35,7 @@ The Dockerfile serves the browser application from nginx on port 8080, with corr
25
35
 
26
36
  ## npm
27
37
 
28
- The package name is `spi3der`, with a CLI that hosts the app locally. The package is configured for `npm pack` / `npm publish` but is **not automatically published**. The source project has no license declaration; the npm metadata intentionally uses `UNLICENSED` until the author decides on a license.
38
+ The package name is `spi3der`, with a CLI that hosts the app locally. The package is configured for `npm pack` / `npm publish` but is **not automatically published**. The project is licensed under MIT (see LICENSE).
29
39
 
30
40
  ## Compatibility
31
41
 
@@ -34,3 +44,46 @@ The package name is `spi3der`, with a CLI that hosts the app locally. The packag
34
44
  - Desktop starts empty; use **Enter XR** to enter VR manually.
35
45
 
36
46
  Original source: https://github.com/Pengeszikra/five-percent
47
+
48
+
49
+ ## Legacy local Workshop 002 (diagnostics only)
50
+
51
+ ```sh
52
+ npm install
53
+ npm run workshop
54
+ # open http://localhost:5173/workshop.html
55
+ ```
56
+
57
+ This is a **local-first** shared scene with the existing 3Draft geometry kernel, not a second model format.
58
+
59
+ **Human in browser**: WebGL2 scene (drag to orbit, scroll to zoom, click to select), add/transform/rotate/remove named meshes, inspect deterministic SVG views, export JSON, and queue new instructions **while an agent is working**. The WebGL camera is *local to each browser*, not part of shared geometry.
60
+
61
+ **Agent in another terminal**: connect an MCP client to the same running Workshop instance through:
62
+
63
+ ```json
64
+ {
65
+ "mcpServers": {
66
+ "spi3der-workshop": {
67
+ "command": "node",
68
+ "args": ["/ABSOLUTE/PATH/TO/spi3der/bin/workshop-mcp.mjs"]
69
+ }
70
+ }
71
+ }
72
+ ```
73
+
74
+ This stdio proxy forwards all MCP calls into the **one** running HTTP workshop process. There is no second scene. On the same machine: `npm run mcp:workshop`. The proxy accepts `SPI3DER_WORKSHOP_URL` if the HTTP endpoint is not on port 5173.
75
+
76
+ The agent should invoke ordinary 3Draft tools (`add_box`, `transform`, `render`, `inspect`, `list`, etc.) and periodically call **`workshop_messages`** to read new human instructions; **`workshop_reply`** acknowledges/responds to them. The browser's instruction box can take additional messages immediately, without cancelling scene operations. These messages are **not** auto-executed by a model: the connected agent has to poll them explicitly.
77
+
78
+ HTTP interface:
79
+ - `GET /api/scene`: scene state with monotonic revision
80
+ - `POST /api/tool`: execute a 3Draft tool against that scene
81
+ - `GET /api/events`: SSE changes to the shared scene and instruction queue
82
+ - `GET /api/version`, `GET /api/inbox`, `POST /api/inbox`, `POST /api/presence`, `GET /api/participants`
83
+ - `POST /mcp`: minimal JSON-RPC over HTTP, **not a complete Streamable HTTP MCP** transport; use the stdio bridge for MCP clients.
84
+
85
+ **Test:** `npm run test:workshop` exercises MCP → scene → browser API, instruction acknowledgments, participant presence and static-file protection.
86
+
87
+ **Current boundaries:** one process / one in-memory shared scene, no persistence across restart; no realtime editing link to the legacy full Spider Paint WebGL editor; no multi-user permission or concurrent edit locks; no agent background execution, no pause/resume coordinator; the HTTP MCP endpoint is a local prototype and is not authenticated. Only bind to 127.0.0.1. A host ChatGPT UI may not support embedding this external live viewer. No npm publish is implied by a Git commit.
88
+
89
+ Architecture and collaboration invariants live in `AGENTS.md`.
package/api/mcp.mjs CHANGED
@@ -1,7 +1,8 @@
1
- // The public MCP endpoint: https://spider-paint.vercel.app/api/mcp (Streamable HTTP, stateless, no auth).
1
+ // spi3der MCP endpoint: /api/mcp (Streamable HTTP, stateless for model results).
2
2
  // A Vercel Node function around mcp/http.js (synced from 3Draft). Static files it reads (sky.md, the Deep Sky
3
3
  // catalogue) are fetched from the site itself.
4
4
  import { handleHttp } from '../mcp/http.js';
5
+ import { handleWorkshopMcp } from '../mcp/workshop-app.js';
5
6
 
6
7
  const readBody = (req) => new Promise((resolve, reject) => {
7
8
  if (typeof req.body === 'string') return resolve(req.body);
@@ -16,7 +17,7 @@ const readBody = (req) => new Promise((resolve, reject) => {
16
17
 
17
18
  export default async function handler(req, res) {
18
19
  const proto = String(req.headers['x-forwarded-proto'] ?? 'https').split(',')[0];
19
- const host = String(req.headers['x-forwarded-host'] ?? req.headers.host ?? 'spider-paint.vercel.app').split(',')[0];
20
+ const host = String(req.headers['x-forwarded-host'] ?? req.headers.host ?? 'localhost').split(',')[0];
20
21
  const origin = `${proto}://${host}`;
21
22
  const fetchText = async (path) => {
22
23
  const r = await fetch(origin + path);
@@ -24,7 +25,17 @@ export default async function handler(req, res) {
24
25
  return r.text();
25
26
  };
26
27
  const body = req.method === 'POST' ? await readBody(req) : '';
27
- const out = await handleHttp({ method: req.method, body, origin, fetchText });
28
+ let out;
29
+ if(req.method==='POST'){
30
+ try{
31
+ const json=JSON.parse(body);
32
+ if(!Array.isArray(json)){
33
+ const handled=await handleWorkshopMcp(json,{origin,fetchText});
34
+ if(handled!==undefined)out={status:handled===null?202:200,headers:{'content-type':'application/json','access-control-allow-origin':'*','access-control-allow-headers':'content-type, accept, mcp-protocol-version','access-control-expose-headers':'mcp-protocol-version'},body:handled===null?'':JSON.stringify(handled)};
35
+ }
36
+ }catch(e){if(out===undefined && e instanceof SyntaxError) { /* hand malformed input to standard transport */ } else if(out===undefined)throw e;}
37
+ }
38
+ out??=await handleHttp({ method: req.method, body, origin, fetchText });
28
39
  for (const [k, v] of Object.entries(out.headers ?? {})) res.setHeader(k, v);
29
40
  res.statusCode = out.status;
30
41
  res.end(out.body ?? '');
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ // stdio MCP bridge to the running local Workshop.
3
+ // One MCP server, one shared scene; do not instantiate a second scene here.
4
+ import { createInterface } from 'node:readline';
5
+ const endpoint=process.env.SPI3DER_WORKSHOP_URL || 'http://127.0.0.1:5173/mcp';
6
+ const rl=createInterface({input:process.stdin,crlfDelay:Infinity});
7
+ let pending=Promise.resolve();
8
+ const reply=obj=>process.stdout.write(JSON.stringify(obj)+'\n');
9
+ rl.on('line',line=>{
10
+ pending=pending.then(async()=>{
11
+ if(!line.trim())return;
12
+ let rpc;
13
+ try{rpc=JSON.parse(line)}catch{return reply({jsonrpc:'2.0',id:null,error:{code:-32700,message:'invalid JSON'}})}
14
+ try {
15
+ const response=await fetch(endpoint,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(rpc),signal:AbortSignal.timeout(30000)});
16
+ if(rpc.id==null)return;
17
+ if(!response.ok)throw Error('HTTP '+response.status);
18
+ reply(await response.json());
19
+ }catch(e){if(rpc.id!=null)reply({jsonrpc:'2.0',id:rpc.id,error:{code:-32000,message:'Workshop unreachable at '+endpoint+': '+e.message}})}
20
+ }).catch(e=>console.error('workshop bridge:',e));
21
+ });
@@ -0,0 +1,137 @@
1
+ #!/usr/bin/env node
2
+ // spi3der Workshop v0: one shared in-memory scene for the local UI and HTTP MCP clients.
3
+ // Loopback only: no auth; do not expose this server on a public interface.
4
+ import { createServer } from 'node:http';
5
+ import { readFile } from 'node:fs/promises';
6
+ import { extname, resolve, dirname, sep } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { createScene } from '../mcp/scene.js';
9
+
10
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
11
+ const scene = createScene();
12
+ const port = Number(process.env.PORT || process.argv[2] || 5173);
13
+ const clients = new Set();
14
+ // Participant messages are durable for this process lifetime, not autonomous model runs.
15
+ const inbox = [];
16
+ let messageId=0;
17
+ const participants=new Map();
18
+ const taskTools=[
19
+ {name:'workshop_messages',description:'Read pending human instructions sent while working. Poll between modelling operations.',inputSchema:{type:'object',properties:{after:{type:'integer',description:'Last message id seen (default 0)'},participant:{type:'string'}}},annotations:{readOnlyHint:true}},
20
+ {name:'workshop_reply',description:'Acknowledge or reply to a message without blocking the 3D task.',inputSchema:{type:'object',properties:{id:{type:'integer'},reply:{type:'string'},status:{type:'string',enum:['acknowledged','done','question']}},required:['id']}},
21
+ {name:'workshop_participants',description:'Read active participants. Their cameras are personal, not scene state.',inputSchema:{type:'object',properties:{}},annotations:{readOnlyHint:true}}
22
+ ];
23
+ const messageTools=(name,args={})=>{
24
+ if(name==='workshop_messages')return {messages:inbox.filter(m=>m.id>(Number(args.after)||0)),latest:messageId};
25
+ if(name==='workshop_participants')return {participants:[...participants.values()].filter(p=>Date.now()-p.lastSeen<120000).map(({id,label})=>({id,label}))};
26
+ if(name==='workshop_reply'){const m=inbox.find(m=>m.id===args.id);if(!m)throw Error('unknown message id');m.status=['acknowledged','done','question'].includes(args.status)?args.status:'acknowledged';m.reply=String(args.reply||'').slice(0,2000);broadcast();return {message:m}};
27
+ return null;
28
+ };
29
+ const callWorkshop=(name,args={})=>{
30
+ if(name.startsWith('workshop_')){try{return {isError:false,text:JSON.stringify(messageTools(name,args))}}catch(e){return {isError:true,text:e.message}}}
31
+ return scene.call(name,args);
32
+ };
33
+ const contentTypes = { '.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.css':'text/css; charset=utf-8','.svg':'image/svg+xml','.wasm':'application/wasm','.png':'image/png' };
34
+ const sendJson = (res, status, payload) => {
35
+ res.writeHead(status, { 'Content-Type':'application/json; charset=utf-8', 'Cache-Control':'no-store', 'X-Content-Type-Options':'nosniff' });
36
+ res.end(JSON.stringify(payload));
37
+ };
38
+ const postBody = async (req) => {
39
+ let text = '';
40
+ for await (const chunk of req) {
41
+ text += chunk.toString();
42
+ if (text.length > 1_000_000) throw new Error('request too large');
43
+ }
44
+ return JSON.parse(text || '{}');
45
+ };
46
+ const broadcast = () => {
47
+ const event = 'event: scene\ndata: ' + JSON.stringify({ rev: scene.data().rev, objects: scene.data().objects.map(o => o.name) }) + '\n\n';
48
+ for (const res of clients) res.write(event);
49
+ };
50
+ scene.subscribe(broadcast);
51
+ const protocol = '2025-06-18';
52
+ const toolCall = (name, args) => callWorkshop(name, args);
53
+ const mcp = (req) => {
54
+ const { id, method, params = {} } = req;
55
+ const wrap = (result) => ({ jsonrpc: '2.0', id, result });
56
+ if (method === 'initialize') return wrap({ protocolVersion:protocol, capabilities:{ tools:{} }, serverInfo:{name:'spi3der-workshop',version:'26.11.20003'}, instructions:'Local shared Workshop: MCP and browser edit one scene. Visit /workshop.html.' });
57
+ if (method === 'ping') return wrap({});
58
+ if (method === 'tools/list') return wrap({ tools:[...scene.list(),...taskTools] });
59
+ if (method === 'tools/call') {
60
+ const out = toolCall(params.name, params.arguments || {});
61
+ return wrap({ content:[{type:'text',text:out.text}], ...(out.isError ? {isError:true} : {}) });
62
+ }
63
+ return { jsonrpc:'2.0',id,error:{code:-32601,message:'method not found'} };
64
+ };
65
+ const server = createServer(async (req, res) => {
66
+ try {
67
+ const url = new URL(req.url, 'http://localhost');
68
+ const path = url.pathname;
69
+ if (req.method === 'GET' && path === '/api/version') {
70
+ const pkg=JSON.parse(await readFile(resolve(root,'package.json'),'utf8'));
71
+ const [y,m,packed]=pkg.version.split('.').map(Number);
72
+ return sendJson(res,200,{version:pkg.version,display:[y,m,Math.floor(packed/1000),packed%1000].map((n,i)=>String(n).padStart(i===3?3:2,'0')).join('.')});
73
+ }
74
+ if (req.method === 'GET' && path === '/api/inbox') return sendJson(res,200,{messages:inbox,latest:messageId});
75
+ if (req.method === 'POST' && path === '/api/inbox') {
76
+ const data=await postBody(req);
77
+ const text=String(data.text||'').trim();
78
+ if(!text||text.length>4000) return sendJson(res,400,{error:'Instruction must be 1-4000 characters'});
79
+ const message={id:++messageId,participant:String(data.participant||'human').slice(0,64),text,status:'pending',reply:'',createdAt:new Date().toISOString()};
80
+ inbox.push(message);if(inbox.length>500)inbox.shift();broadcast();return sendJson(res,201,{message});
81
+ }
82
+ if (req.method === 'POST' && path === '/api/presence') {
83
+ const data=await postBody(req);const id=String(data.id||'').slice(0,64);
84
+ if(!id) return sendJson(res,400,{error:'participant id required'});
85
+ participants.set(id,{id,label:String(data.label||id).slice(0,64),lastSeen:Date.now()});
86
+ return sendJson(res,200,{ok:true});
87
+ }
88
+ if (req.method === 'GET' && path === '/api/participants')return sendJson(res,200,messageTools('workshop_participants'));
89
+ if (req.method === 'GET' && path === '/api/scene') return sendJson(res,200,scene.data());
90
+ if (req.method === 'GET' && path === '/api/tools') return sendJson(res,200,[...scene.list(),...taskTools].map(({name,description,inputSchema})=>({name,description,inputSchema})));
91
+ if (req.method === 'GET' && path === '/api/render') {
92
+ const allowed = ['sheet','front','left','top','persp'];
93
+ const view = allowed.includes(url.searchParams.get('view')) ? url.searchParams.get('view') : 'persp';
94
+ const size = Math.max(180, Math.min(900, Number(url.searchParams.get('size')) || 640));
95
+ const out = toolCall('render',{view,size});
96
+ if(out.isError) return sendJson(res,400,{error:out.text});
97
+ // The render tool emits JSON with svg or plain SVG depending on its version.
98
+ let parsed; try { parsed=JSON.parse(out.text); } catch { parsed=out.text; }
99
+ const svg = typeof parsed === 'string' ? parsed : (parsed.svg || parsed.render || out.text);
100
+ res.writeHead(200,{'Content-Type':'image/svg+xml; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff','Content-Security-Policy':"default-src 'none'; style-src 'unsafe-inline'"});
101
+ return res.end(svg);
102
+ }
103
+ if (req.method === 'GET' && path === '/api/events') {
104
+ res.writeHead(200,{'Content-Type':'text/event-stream','Cache-Control':'no-store','Connection':'keep-alive','X-Accel-Buffering':'no'});
105
+ clients.add(res);res.write('retry: 1000\n\n');res.write('event: scene\ndata: '+JSON.stringify({rev:scene.data().rev})+'\n\n');
106
+ req.on('close',()=>clients.delete(res));return;
107
+ }
108
+ if (req.method === 'POST' && path === '/api/tool') {
109
+ const {name,arguments:args} = await postBody(req);
110
+ if (typeof name !== 'string' || !name || !args || typeof args !== 'object' || Array.isArray(args)) return sendJson(res,400,{error:'name and object arguments required'});
111
+ const out = toolCall(name,args); return sendJson(res,out.isError?400:200,out.isError?{error:out.text}:{text:out.text,rev:scene.data().rev});
112
+ }
113
+ if (req.method === 'POST' && path === '/mcp') {
114
+ const rpc = await postBody(req);
115
+ if (!rpc || Array.isArray(rpc) || typeof rpc.method !== 'string') return sendJson(res,400,{jsonrpc:'2.0',id:rpc?.id??null,error:{code:-32600,message:'invalid request'}});
116
+ if (rpc.id == null) return res.writeHead(202).end();
117
+ return sendJson(res,200,mcp(rpc));
118
+ }
119
+ if (req.method === 'GET' && path === '/mcp') return sendJson(res,200,{name:'spi3der-workshop',transport:'JSON-RPC POST /mcp',note:'Local experimental HTTP MCP; not a full Streamable HTTP implementation'});
120
+ if (req.method !== 'GET' && req.method !== 'HEAD') return res.writeHead(405).end();
121
+ const relative = decodeURIComponent(path === '/' ? '/workshop.html' : path).replace(/^\/+/, '');
122
+ const file = resolve(root,relative);
123
+ if (!file.startsWith(root+sep)) return res.writeHead(403).end();
124
+ // Never expose private repository files, environment/config, or arbitrary sources.
125
+ const allowedFiles=new Set(['workshop.html','index.html','favicon.svg','manifest.webmanifest']);
126
+ const allowedFolders=['src/','engine/','models/','icons/','media/'];
127
+ if(!allowedFiles.has(relative)&&!allowedFolders.some(p=>relative.startsWith(p)))return res.writeHead(404).end();
128
+ const bytes = await readFile(file);
129
+ res.writeHead(200,{'Content-Type':contentTypes[extname(file)]||'application/octet-stream','X-Content-Type-Options':'nosniff'});
130
+ res.end(req.method==='HEAD'?'':bytes);
131
+ } catch (e) {
132
+ sendJson(res,e instanceof SyntaxError?400:500,{error:e.message});
133
+ }
134
+ });
135
+ const heartbeat=setInterval(()=>{ for (const c of clients) c.write(': heartbeat\n\n'); },20000);
136
+ heartbeat.unref();
137
+ server.listen(port,'127.0.0.1',()=>console.log('spi3der Workshop: http://localhost:'+port+'/workshop.html'));
@@ -0,0 +1,43 @@
1
+ // ChatGPT/MCP Apps adapter. Lives in spi3der, not in the headless 3Draft kernel.
2
+ import { publicTools, unpack } from './http.js';
3
+ import { widgetHTML } from './workshop-widget.js';
4
+ export const RESOURCE_URI='ui://spi3der/workshop-v1.html';
5
+ const displayTool={
6
+ name:'open_workshop',
7
+ description:'Open a 3D model directly inside the conversation as an interactive orbitable spi3der workshop. Accept the modelling steps used by build_model; continue a previous model with from.',
8
+ inputSchema:{type:'object',properties:{steps:{type:'array',items:{type:'object',properties:{tool:{type:'string'},args:{type:'object'}},required:['tool']}},from:{type:'string',description:'Previous build_model open_url or open_workshop open_url'}}},annotations:{readOnlyHint:false,openWorldHint:false},
9
+ _meta:{ui:{resourceUri:RESOURCE_URI},'openai/outputTemplate':RESOURCE_URI}
10
+ };
11
+ const err=(id,code,message)=>({jsonrpc:'2.0',id,error:{code,message}});
12
+ const answer=(id,result)=>({jsonrpc:'2.0',id,result});
13
+ export async function handleWorkshopMcp(request,{origin,fetchText}) {
14
+ if(!request||Array.isArray(request)||request.jsonrpc!=='2.0'||typeof request.method!=='string')return err(request?.id??null,-32600,'invalid request');
15
+ const {id,method,params={}}=request;
16
+ if(id===undefined||id===null)return null;
17
+ if(method==='tools/list')return answer(id,{tools:[...publicTools().map(({name,description,inputSchema,annotations})=>({name,description,inputSchema,annotations})),displayTool]});
18
+ if(method==='resources/list')return answer(id,{resources:[{uri:RESOURCE_URI,name:'spi3der 3D Workshop',mimeType:'text/html;profile=mcp-app',description:'Interactive 3D scene embedded in the conversation'}]});
19
+ if(method==='resources/read'){
20
+ if(params.uri!==RESOURCE_URI)return err(id,-32002,'resource not found');
21
+ return answer(id,{contents:[{uri:RESOURCE_URI,mimeType:'text/html;profile=mcp-app',text:widgetHTML}]});
22
+ }
23
+ if(method==='initialize'){
24
+ return answer(id,{protocolVersion:params.protocolVersion||'2025-06-18',capabilities:{tools:{},resources:{listChanged:false}},serverInfo:{name:'spi3der',title:'spi3der',version:'26.11.20005'},instructions:'spi3der is a ChatGPT-native 3D workshop. Use open_workshop to render the scene inline, not links to another browser tab. The headless 3Draft engine supplies geometries.'});
25
+ }
26
+ if(method==='tools/call'&&params.name==='open_workshop'){
27
+ try{
28
+ const modelTool=publicTools().find(t=>t.name==='build_model');
29
+ const args=params.arguments||{};
30
+ const out=await modelTool.run({steps:args.steps||[],from:args.from,render:'none'},{origin,fetchText});
31
+ if(out.failed) return answer(id,{isError:true,content:[{type:'text',text:JSON.stringify(out.steps)}]});
32
+ const packed=/#scene=([A-Za-z0-9_-]+)/.exec(out.open_url||'')?.[1];
33
+ if(!packed)throw Error('scene too large for the stateless preview');
34
+ const scene=unpack(packed);
35
+ return answer(id,{
36
+ structuredContent:{scene,open_url:out.open_url,revision:1},
37
+ content:[{type:'text',text:JSON.stringify({objects:out.objects,open_url:out.open_url,steps:out.steps})}],
38
+ _meta:{ui:{resourceUri:RESOURCE_URI},'openai/outputTemplate':RESOURCE_URI}
39
+ });
40
+ }catch(e){return answer(id,{isError:true,content:[{type:'text',text:String(e.message||e)}]})}
41
+ }
42
+ return undefined;
43
+ }
@@ -0,0 +1,69 @@
1
+ // Inline MCP Apps viewport: no external scripts and no duplicate editor chrome.
2
+ // Scene data comes from window.openai.toolOutput. Camera stays private to this widget.
3
+ export const widgetHTML = `<!doctype html>
4
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
5
+ <style>
6
+ html,body{margin:0;width:100%;height:100%;overflow:hidden;background:#101518;color:#d5e3e5;font:12px system-ui}
7
+ #viewport{position:relative;width:100%;height:100%;min-height:300px;overflow:hidden;touch-action:none}
8
+ canvas{width:100%;height:100%;display:block;touch-action:none}
9
+ .info{position:absolute;left:12px;bottom:10px;pointer-events:none;color:#a0b3bb;text-shadow:0 1px 2px #000}
10
+ #name{position:absolute;top:10px;left:12px;color:#ddecef;pointer-events:none}
11
+ </style></head><body><div id="viewport">
12
+ <canvas id="c"></canvas><span id="name">spi3der · 3D workshop</span>
13
+ <div class="info">Drag to orbit · Scroll to zoom · Independent camera</div>
14
+ </div>
15
+ <script>
16
+ (()=>{
17
+ const canvas=document.getElementById('c'),ctx=canvas.getContext('2d');
18
+ let scene=window.openai?.toolOutput?.scene || {objects:[]};
19
+ let yaw=.65,pitch=.36,zoom=1,pan=[0,0,0],initial=true;
20
+ const clamp=(n,a,b)=>Math.max(a,Math.min(b,n));
21
+ const color=s=>/^#[0-9a-f]{3,8}$/i.test(s||'')?s:'#789aa5';
22
+ const all=()=>scene?.objects||[];
23
+ function geometry(){
24
+ const objects=all(),pts=[];
25
+ for(const o of objects)for(const p of o.mesh?.positions||[])pts.push(p);
26
+ if(!pts.length)return {center:[0,0,0],r:2};
27
+ const low=[Infinity,Infinity,Infinity],high=[-Infinity,-Infinity,-Infinity];
28
+ for(const p of pts)for(let i=0;i<3;i++){low[i]=Math.min(low[i],p[i]);high[i]=Math.max(high[i],p[i])}
29
+ const center=low.map((n,i)=>(n+high[i])/2);
30
+ return {center,r:Math.max(1,Math.hypot(...high.map((n,i)=>n-low[i])))};
31
+ }
32
+ function draw(){
33
+ const box=canvas.getBoundingClientRect(),dpr=Math.min(devicePixelRatio||1,2);
34
+ canvas.width=Math.max(1,Math.round(box.width*dpr));canvas.height=Math.max(1,Math.round(box.height*dpr));
35
+ ctx.setTransform(dpr,0,0,dpr,0,0);const w=box.width,h=box.height;
36
+ ctx.clearRect(0,0,w,h);
37
+ const {center,r}=geometry(),scale=Math.min(w,h)*.7/(r*zoom);
38
+ const cy=Math.cos(yaw),sy=Math.sin(yaw),cp=Math.cos(pitch),sp=Math.sin(pitch);
39
+ function proj(p){
40
+ const x=p[0]-center[0]-pan[0],y=p[1]-center[1]-pan[1],z=p[2]-center[2]-pan[2];
41
+ const a=x*cy-z*sy,b=x*sy+z*cy;
42
+ const dy=y*cp-b*sp,depth=y*sp+b*cp;
43
+ return [w/2+a*scale,h/2-dy*scale,depth];
44
+ }
45
+ const polygons=[];
46
+ for(const o of all()){const m=o.mesh||{};
47
+ for(const f of m.faces||[]){const vertices=(f.v||[]).map(i=>m.positions?.[i]).filter(Boolean).map(proj);
48
+ if(vertices.length>=3)polygons.push({v:vertices,c:color(f.color),z:vertices.reduce((s,p)=>s+p[2],0)/vertices.length})}
49
+ }
50
+ polygons.sort((a,b)=>a.z-b.z);
51
+ ctx.lineJoin='round';
52
+ for(const p of polygons){ctx.beginPath();p.v.forEach((v,i)=>i?ctx.lineTo(v[0],v[1]):ctx.moveTo(v[0],v[1]));ctx.closePath();ctx.fillStyle=p.c;ctx.fill();ctx.strokeStyle='#11191f';ctx.lineWidth=Math.max(.65,1/zoom);ctx.stroke()}
53
+ if(!polygons.length){ctx.textAlign='center';ctx.fillStyle='#829aa6';ctx.fillText('Empty 3D scene',w/2,h/2)}
54
+ }
55
+ let last=null;
56
+ canvas.addEventListener('pointerdown',e=>{last=[e.clientX,e.clientY];canvas.setPointerCapture(e.pointerId)});
57
+ canvas.addEventListener('pointermove',e=>{if(!last)return;yaw+=(e.clientX-last[0])*.01;pitch=clamp(pitch+(e.clientY-last[1])*.01,-1.5,1.5);last=[e.clientX,e.clientY];draw()});
58
+ canvas.addEventListener('pointerup',()=>last=null);
59
+ canvas.addEventListener('pointercancel',()=>last=null);
60
+ canvas.addEventListener('wheel',e=>{e.preventDefault();zoom=clamp(zoom*Math.exp(e.deltaY*.001),.12,20);draw()},{passive:false});
61
+ new ResizeObserver(draw).observe(document.getElementById('viewport'));
62
+ const newScene=()=>{
63
+ const value=window.openai?.toolOutput?.scene;
64
+ if(value){scene=value;draw()}
65
+ };
66
+ window.addEventListener('openai:set_globals',newScene);
67
+ newScene();draw();
68
+ })();
69
+ </script></body></html>`;
package/package.json CHANGED
@@ -1,16 +1,21 @@
1
1
  {
2
2
  "name": "spi3der",
3
- "version": "26.11.20001",
3
+ "version": "26.11.20005",
4
4
  "description": "Browser-native 3D scene building, WebXR and ViRtuSH, based on 3Draft",
5
- "license": "UNLICENSED",
5
+ "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
8
- "spi3der": "./bin/spi3der.mjs"
8
+ "spi3der": "./bin/spi3der.mjs",
9
+ "spi3der-workshop-mcp": "./bin/workshop-mcp.mjs"
9
10
  },
10
11
  "scripts": {
11
12
  "start": "node bin/spi3der.mjs",
12
13
  "test": "node tests/math.mjs && node tests/smoke.mjs",
13
- "bump": "node scripts/bump.mjs"
14
+ "bump": "node scripts/bump.mjs",
15
+ "workshop": "node bin/workshop.mjs",
16
+ "test:workshop": "node tests/workshop.mjs",
17
+ "mcp:workshop": "node bin/workshop-mcp.mjs",
18
+ "test:mcp-app": "node tests/mcp-app.mjs"
14
19
  },
15
20
  "files": [
16
21
  "api/",
@@ -37,7 +42,9 @@
37
42
  "sw.js",
38
43
  "Dockerfile",
39
44
  "nginx.conf",
40
- "README.md"
45
+ "README.md",
46
+ "workshop.html",
47
+ "LICENSE"
41
48
  ],
42
49
  "dependencies": {
43
50
  "@vercel/blob": "^2.3.0"
@@ -0,0 +1,59 @@
1
+ // Dependency-free, participant-local WebGL2 viewer of shared 3Draft meshes.
2
+ // Camera is deliberately NOT part of the shared scene. Drag = orbit, wheel = zoom, click = select.
3
+ export class WorkshopView {
4
+ constructor(canvas, onSelect = () => {}) {
5
+ this.canvas=canvas; this.onSelect=onSelect; this.objects=[];
6
+ this.camera={yaw:0.6,pitch:0.35,distance:9,target:[0,0,0]};
7
+ const gl=canvas.getContext('webgl2',{antialias:true,alpha:false});
8
+ if(!gl)throw Error('WebGL2 unavailable');
9
+ this.gl=gl;
10
+ const shader=(type,src)=>{const s=gl.createShader(type);gl.shaderSource(s,src);gl.compileShader(s);if(!gl.getShaderParameter(s,gl.COMPILE_STATUS))throw Error(gl.getShaderInfoLog(s));return s};
11
+ const vs=shader(gl.VERTEX_SHADER,`#version 300 es
12
+ in vec3 position; in vec3 color;
13
+ uniform mat4 projectionView;
14
+ out vec3 vColor;
15
+ void main(){gl_Position=projectionView*vec4(position,1.);vColor=color;}`);
16
+ const fs=shader(gl.FRAGMENT_SHADER,`#version 300 es
17
+ precision mediump float;
18
+ in vec3 vColor;out vec4 fragColor;
19
+ void main(){fragColor=vec4(vColor,1.);}`);
20
+ const program=gl.createProgram();gl.attachShader(program,vs);gl.attachShader(program,fs);gl.linkProgram(program);
21
+ if(!gl.getProgramParameter(program,gl.LINK_STATUS))throw Error(gl.getProgramInfoLog(program));
22
+ this.program=program;this.location=gl.getUniformLocation(program,'projectionView');
23
+ this.vao=gl.createVertexArray();gl.bindVertexArray(this.vao);
24
+ this.vertexBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.vertexBuffer);
25
+ gl.enableVertexAttribArray(gl.getAttribLocation(program,'position'));
26
+ gl.vertexAttribPointer(gl.getAttribLocation(program,'position'),3,gl.FLOAT,false,24,0);
27
+ gl.enableVertexAttribArray(gl.getAttribLocation(program,'color'));
28
+ gl.vertexAttribPointer(gl.getAttribLocation(program,'color'),3,gl.FLOAT,false,24,12);
29
+ gl.clearColor(.035,.055,.075,1);gl.enable(gl.DEPTH_TEST);
30
+ let down=null;
31
+ canvas.addEventListener('pointerdown',e=>{down={x:e.clientX,y:e.clientY,yaw:this.camera.yaw,pitch:this.camera.pitch,moved:false};canvas.setPointerCapture(e.pointerId)});
32
+ canvas.addEventListener('pointermove',e=>{if(!down)return;const dx=e.clientX-down.x,dy=e.clientY-down.y;if(Math.abs(dx)+Math.abs(dy)>3)down.moved=true;this.camera.yaw=down.yaw-dx*.007;this.camera.pitch=Math.max(-1.5,Math.min(1.5,down.pitch+dy*.007));this.draw()});
33
+ canvas.addEventListener('pointerup',e=>{if(down&&!down.moved)this.pick(e.offsetX,e.offsetY);down=null});
34
+ canvas.addEventListener('wheel',e=>{e.preventDefault();this.camera.distance=Math.max(.25,Math.min(100000,this.camera.distance*Math.exp(e.deltaY*.001)));this.draw()},{passive:false});
35
+ new ResizeObserver(()=>this.draw()).observe(canvas);
36
+ }
37
+ setScene(objects){this.objects=objects||[];this.draw()}
38
+ reset(){this.camera={yaw:.6,pitch:.35,distance:9,target:[0,0,0]};this.draw()}
39
+ fit(){const pts=this.objects.flatMap(o=>o.mesh?.positions||[]);if(!pts.length)return this.reset();const lo=[Infinity,Infinity,Infinity],hi=[-Infinity,-Infinity,-Infinity];for(const p of pts)for(let k=0;k<3;k++){lo[k]=Math.min(lo[k],p[k]);hi[k]=Math.max(hi[k],p[k])}this.camera.target=lo.map((v,k)=>(v+hi[k])/2);this.camera.distance=Math.max(2,Math.hypot(...hi.map((v,k)=>v-lo[k]))*1.6);this.draw()}
40
+ // Column-major 4x4 matrix, projection derived from a camera basis (right, up, forward).
41
+ basis(){const {yaw,pitch,distance,target}=this.camera;const eye=[target[0]+distance*Math.sin(yaw)*Math.cos(pitch),target[1]+distance*Math.sin(pitch),target[2]+distance*Math.cos(yaw)*Math.cos(pitch)];
42
+ const norm=v=>{const l=Math.hypot(...v)||1;return v.map(n=>n/l)};
43
+ const cross=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]];
44
+ const forward=norm(target.map((v,i)=>v-eye[i])),right=norm(cross(forward,[0,1,0])),up=cross(right,forward);
45
+ return {eye,right,up,forward}}
46
+ matrix(){const {eye,right,up,forward}=this.basis(),w=this.canvas.width,h=this.canvas.height,aspect=w/h,f=1/Math.tan(Math.PI/6),near=.01,far=Math.max(100000,this.camera.distance*100);
47
+ const view=[right[0],up[0],-forward[0],0,right[1],up[1],-forward[1],0,right[2],up[2],-forward[2],0,
48
+ -right.reduce((s,v,i)=>s+v*eye[i],0),-up.reduce((s,v,i)=>s+v*eye[i],0),forward.reduce((s,v,i)=>s+v*eye[i],0),1];
49
+ const proj=[f/aspect,0,0,0,0,f,0,0,0,0,(far+near)/(near-far),-1,0,0,2*far*near/(near-far),0];
50
+ const out=new Float32Array(16);for(let c=0;c<4;c++)for(let r=0;r<4;r++)for(let k=0;k<4;k++)out[c*4+r]+=proj[k*4+r]*view[c*4+k];return out}
51
+ draw(){const gl=this.gl,c=this.canvas,w=Math.max(1,Math.floor(c.clientWidth*devicePixelRatio)),h=Math.max(1,Math.floor(c.clientHeight*devicePixelRatio));if(c.width!==w||c.height!==h){c.width=w;c.height=h}gl.viewport(0,0,w,h);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);
52
+ const vertices=[];for(const o of this.objects){const mesh=o.mesh;if(!mesh?.faces)continue;for(const face of mesh.faces){const ids=face.v||[];if(ids.length<3)continue;const hex=(face.color||'#9aabb6').replace('#','');const s=hex.length===3?hex.split('').map(x=>x+x).join(''):hex;const rgb=[0,2,4].map(i=>parseInt(s.slice(i,i+2),16)/255);if(rgb.some(x=>!Number.isFinite(x)))continue;
53
+ for(let j=1;j<ids.length-1;j++)for(const index of [ids[0],ids[j],ids[j+1]]){const p=mesh.positions[index];if(p)vertices.push(...p,...rgb)}
54
+ }}gl.useProgram(this.program);gl.uniformMatrix4fv(this.location,false,this.matrix());gl.bindVertexArray(this.vao);gl.bindBuffer(gl.ARRAY_BUFFER,this.vertexBuffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertices),gl.DYNAMIC_DRAW);gl.drawArrays(gl.TRIANGLES,0,vertices.length/6)}
55
+ pick(x,y){const {eye,right,up,forward}=this.basis(),c=this.canvas,aspect=c.clientWidth/c.clientHeight,t=Math.tan(Math.PI/6),nx=(x/c.clientWidth*2-1)*aspect*t,ny=(1-y/c.clientHeight*2)*t;
56
+ const d=forward.map((v,i)=>v+nx*right[i]+ny*up[i]);const norm=Math.hypot(...d);const dir=d.map(v=>v/norm),cross=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2]],sub=(a,b)=>a.map((v,i)=>v-b[i]),dot=(a,b)=>a.reduce((s,v,i)=>s+v*b[i],0);
57
+ let best=Infinity,name=null;for(const o of this.objects){const m=o.mesh;for(const f of m.faces||[]){const ids=f.v;for(let j=1;j<ids.length-1;j++){const a=m.positions[ids[0]],b=m.positions[ids[j]],cc=m.positions[ids[j+1]];if(!a||!b||!cc)continue;const e1=sub(b,a),e2=sub(cc,a),p=cross(dir,e2),det=dot(e1,p);if(Math.abs(det)<1e-8)continue;const inv=1/det,s=sub(eye,a),u=dot(s,p)*inv;if(u<0||u>1)continue;const q=cross(s,e1),v=dot(dir,q)*inv;if(v<0||u+v>1)continue;const distance=dot(e2,q)*inv;if(distance>0&&distance<best){best=distance;name=o.name}}}}
58
+ if(name)this.onSelect(name)}
59
+ }
package/workshop.html ADDED
@@ -0,0 +1,46 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
3
+ <title>spi3der · Workshop</title><link rel="icon" href="/favicon.svg"><style>
4
+ :root{color-scheme:dark;font:14px/1.45 system-ui,Arial,sans-serif;background:#0c1116;color:#e0edf2;--line:#28404b;--cyan:#36e5ec;--orange:#ff9c42}
5
+ *{box-sizing:border-box}body{margin:0}header{display:flex;align-items:center;gap:16px;padding:14px 22px;border-bottom:1px solid var(--line);flex-wrap:wrap}h1{margin:0;font-size:23px;letter-spacing:.09em}h1 b{color:var(--cyan)}.sub{font-size:12px;color:#829aa6}main{display:grid;grid-template-columns:minmax(320px,1fr) 330px;height:calc(100dvh - 73px)}.stage{min-height:300px;display:flex;flex-direction:column;padding:16px;gap:10px;background:radial-gradient(ellipse,#15303b 0%,#0c1116 75%)}.viewport{flex:1;min-height:260px;display:grid;place-items:center;overflow:hidden;border:1px solid var(--line);border-radius:10px;background:#080d12}.viewport img,.viewport canvas{height:100%;width:100%;object-fit:contain;min-height:0}.viewport canvas{display:block;touch-action:none}.viewport img[hidden],.viewport canvas[hidden]{display:none}.tools{display:flex;flex-wrap:wrap;gap:8px}button,select,input,textarea{font:inherit;background:#192933;color:#e0edf2;border:1px solid #36505d;border-radius:6px;padding:8px 10px}button{cursor:pointer}button:hover{border-color:var(--cyan)}button.primary{background:#08666d;border-color:#159da5}button.warn{color:#ffba80}aside{border-left:1px solid var(--line);padding:16px;overflow:auto;display:flex;flex-direction:column;gap:17px}h2{font-size:12px;letter-spacing:.14em;color:#8da6b2;text-transform:uppercase;margin:0 0 10px}.row{display:flex;gap:8px;align-items:center}.row>*{min-width:0}.row input{width:100%}.obj{display:flex;align-items:center;justify-content:space-between;width:100%;margin:3px 0;text-align:left}.selected{border-color:var(--cyan);background:#16383d}label{display:block;font-size:12px;color:#a6bbc5;margin:7px 0 4px}.coords{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}pre{margin:0;white-space:pre-wrap;overflow-wrap:anywhere;max-height:170px;overflow:auto;color:#99b5bf;font:12px/1.5 ui-monospace,monospace}textarea{width:100%;height:86px;resize:vertical;font:12px/1.4 ui-monospace,monospace}.foot{font:12px ui-monospace,monospace;color:#91a9b5}.pill{color:var(--cyan)}@media(max-width:800px){main{height:auto;display:block}.stage{height:62vh}aside{border-left:0;border-top:1px solid var(--line)}}
6
+ </style></head><body>
7
+ <header><h1>spi<b>3</b>der <span class="sub">/ WORKSHOP 002</span></h1><span class="sub">Human ↔ Scene ↔ AI</span><span id="version" class="sub"></span><span style="margin-left:auto" id="status" class="pill">connecting…</span><a href="/" style="color:#8fb1bb">Original editor</a></header>
8
+ <main><section class="stage"><div class="tools"><select id="view"><option value="persp">Perspective</option><option value="front">Front</option><option value="left">Side</option><option value="top">Top</option><option value="sheet">Four views</option></select><button id="mode">SVG preview</button><button id="fit">Fit camera</button><button id="refresh">Refresh</button><button id="export">Export scene JSON</button></div>
9
+ <div class="viewport"><canvas id="gl" aria-label="3D view — drag to orbit, scroll to zoom, click to select"></canvas><img id="render" hidden alt="3Draft SVG preview"></div><div class="foot">Interactive WebGL2: drag to orbit · wheel to zoom · click to select. SVG verification available via toggle. Your camera remains independent.</div></section>
10
+ <aside>
11
+ <section><h2>Build</h2><div class="row"><input id="name" placeholder="Object name" value="box-1"><button id="add" class="primary">+ Box</button></div><label>Size (X / Y / Z)</label><div class="coords"><input id="sx" type="number" value="1" step=".1"><input id="sy" type="number" value="1" step=".1"><input id="sz" type="number" value="1" step=".1"></div><label>Color</label><input id="color" type="color" value="#35bec9"></section>
12
+ <section><h2>Objects <span id="count"></span></h2><div id="objects" aria-live="polite"></div></section>
13
+ <section><h2>Selected object <span id="chosen" class="pill">none</span></h2><label>Move by X / Y / Z</label><div class="coords"><input id="dx" type="number" value="0" step=".1"><input id="dy" type="number" value="0" step=".1"><input id="dz" type="number" value="0" step=".1"></div><div class="row" style="margin-top:8px"><button id="move">Move</button><button id="rotate">Rotate Y +15°</button><button id="remove" class="warn">Remove</button></div></section>
14
+ <section><h2>Instructions while AI is working</h2><label>Send another instruction at any time (Ctrl+Enter)</label><textarea id="message" placeholder="And please add another wheel…"></textarea><div class="row"><button id="sendMessage" class="primary">Add instruction</button><span class="foot" id="messageStatus">Queued until an agent reads it</span></div><div id="inbox" class="foot" style="max-height:160px;overflow:auto;margin-top:9px"></div></section>
15
+ <section><h2>Agent console</h2><label>MCP tool name</label><input id="tool" value="list" style="width:100%"><label>Arguments (JSON)</label><textarea id="args">{}</textarea><button id="run" class="primary">Run tool</button><pre id="output"></pre><p class="foot">Local HTTP MCP: POST /mcp. Browser actions and MCP actions edit the same scene.</p></section>
16
+ </aside></main>
17
+ <script type="module">
18
+ import {WorkshopView} from '/src/workshop-view.js';
19
+ const $=id=>document.getElementById(id);
20
+ const viewer=new WorkshopView($('gl'),name=>{selected=name;update()});
21
+ let svgMode=false;
22
+ $('mode').onclick=()=>{svgMode=!svgMode;$('render').hidden=!svgMode;$('gl').hidden=svgMode;$('mode').textContent=svgMode?'Interactive 3D':'SVG preview';update()};
23
+ $('fit').onclick=()=>viewer.fit();
24
+ const participant='human-'+Math.random().toString(36).slice(2);
25
+ const pollPresence=()=>fetch('/api/presence',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:participant,label:'Human'})}).catch(()=>{});
26
+ pollPresence();setInterval(pollPresence,30000);
27
+ async function updateInbox(){try{const result=await(await fetch('/api/inbox')).json();$('inbox').replaceChildren();for(const message of result.messages.slice(-12).reverse()){const row=document.createElement('div');row.style.margin='5px 0';row.textContent='#'+message.id+' ['+message.status+'] '+message.text+(message.reply?' — '+message.reply:'');$('inbox').append(row)}}catch{}}
28
+ const sendMessage=async()=>{const text=$('message').value.trim();if(!text)return;const response=await fetch('/api/inbox',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({text,participant})});if(!response.ok){$('messageStatus').textContent='Send failed';return}$('message').value='';$('messageStatus').textContent='Instruction queued';updateInbox()};
29
+ $('sendMessage').onclick=sendMessage;
30
+ $('message').addEventListener('keydown',e=>{if(e.key==='Enter'&&(e.ctrlKey||e.metaKey)){e.preventDefault();sendMessage()}});
31
+ fetch('/api/version').then(r=>r.ok?r.json():null).then(p=>{if(p)$('version').textContent=p.display}).catch(()=>{});
32
+
33
+ let selected=null,revision=-1;
34
+ const xyz=(x,y,z)=>[x,y,z].map(k=>Number($(k).value));
35
+ const call=async(name,args={})=>{const r=await fetch('/api/tool',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name,arguments:args})});const v=await r.json();if(!r.ok)throw Error(v.error||r.statusText);return v};
36
+ async function update(){try{const scene=await (await fetch('/api/scene',{cache:'no-store'})).json();revision=scene.rev;viewer.setScene(scene.objects);$('count').textContent='('+scene.objects.length+')';const list=$('objects');list.replaceChildren();for(const obj of scene.objects){const b=document.createElement('button');b.className='obj'+(obj.name===selected?' selected':'');b.textContent=obj.name;b.onclick=()=>{selected=obj.name;update()};list.append(b)}if(selected&&!scene.objects.some(o=>o.name===selected))selected=null;$('chosen').textContent=selected||'none';if(svgMode)$('render').src='/api/render?view='+encodeURIComponent($('view').value)+'&size=640&rev='+revision;$('status').textContent='LIVE · rev '+revision;}catch(e){$('status').textContent='Disconnected';$('output').textContent=e.message}}
37
+ async function action(fn){try{const result=await fn();if(result)$('output').textContent=result.text??JSON.stringify(result);await update()}catch(e){$('output').textContent='ERROR: '+e.message}}
38
+ $('view').onchange=update;$('refresh').onclick=update;
39
+ $('add').onclick=()=>action(async()=>{const name=$('name').value.trim();const r=await call('add_box',{name,size:xyz('sx','sy','sz'),at:[0,0.5,0],color:$('color').value});selected=name;return r});
40
+ $('move').onclick=()=>action(()=>call('transform',{name:selected,move:xyz('dx','dy','dz')}));
41
+ $('rotate').onclick=()=>action(()=>call('transform',{name:selected,rotate_y:15}));
42
+ $('remove').onclick=()=>action(()=>call('remove',{name:selected}));
43
+ $('run').onclick=()=>action(()=>call($('tool').value.trim(),JSON.parse($('args').value)));
44
+ $('export').onclick=async()=>{try{const data=await(await fetch('/api/scene')).json();const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));a.download='spi3der-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),1000)}catch(e){$('output').textContent=e.message}};
45
+ const stream=new EventSource('/api/events');stream.addEventListener('scene',()=>{update();updateInbox()});stream.onerror=()=>{$('status').textContent='Reconnecting…'};update();updateInbox();
46
+ </script></body></html>