loop-canvas 0.1.6 → 0.1.7
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/cli.mjs +6 -6
- package/package.json +1 -1
- package/public/app.css +1 -1
- package/public/app.js +111 -89
- package/public/duo3d.js +4259 -0
- package/public/fflate.LICENSE.txt +21 -0
- package/public/index.html +4 -2
- package/public/three.LICENSE.txt +21 -0
- package/server.mjs +28 -25
package/server.mjs
CHANGED
|
@@ -1,37 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import hn from"node:http";import y from"node:fs";import D from"node:fs/promises";import h from"node:path";import te from"node:os";import no from"node:crypto";import{spawn as je,execFile as mn,execFileSync as oo}from"node:child_process";import pn from"node:net";import{fileURLToPath as ro}from"node:url";var io=!1,le=h.dirname(ro(import.meta.url)),at=h.join(le,"public"),V=h.join(le,"cli.mjs"),gn=di(process.argv.slice(2)),_=h.resolve(gn.dir||".loop"),Y=h.dirname(_),Le=h.join(_,"canvas.json"),Qe=h.join(_,"server.json");y.mkdirSync(h.join(_,"frames"),{recursive:!0});var Ne=process.env.LOOP_CLAUDE_BIN||$e("claude"),Et=process.env.LOOP_CODEX_BIN||$e("codex")||["/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex","/Applications/Codex.app/Contents/Resources/codex",h.join(te.homedir(),"Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex")].find(e=>{try{return y.accessSync(e,y.constants.X_OK),!0}catch{return!1}}),we={claude:{label:"Claude Code",bin:Ne},codex:{label:"Codex",bin:Et}},so=["fable","opus","sonnet","haiku"],ao=["low","medium","high","xhigh","max"],Ut=0,Jt=null;function co(){return Date.now()-Ut<3e4?Jt:(Ut=Date.now(),Jt=lo())}function lo(){let e=h.join(te.homedir(),".codex"),t=[],n={},i=null;try{let r=JSON.parse(y.readFileSync(h.join(e,"models_cache.json"),"utf8"));for(let s of Array.isArray(r)?r:r.models||[]){let a=s.slug||s.id;!a||(s.visibility||"list")!=="list"||(t.push(a),n[a]=(s.supported_reasoning_levels||s.supported_reasoning_efforts||[]).map(l=>l?.effort||l).filter(l=>typeof l=="string"))}}catch{}try{i=/^\s*model_reasoning_effort\s*=\s*"([^"]+)"/m.exec(y.readFileSync(h.join(e,"config.toml"),"utf8"))?.[1]||null}catch{}return{models:t,efforts:n,effort:i}}function Ce(e=Te()){let t=d.agent.pick?.[e]||{},n,i,r;if(e==="codex"){let a=co(),l=fo();n={model:l,effort:a.effort},i=a.models,r=a.efforts[t.model||l]||["low","medium","high"]}else{let a=d.agent.chat?.runner==="claude"?d.agent.chat:{};n={model:process.env.LOOP_MODEL||a.model||null,effort:process.env.LOOP_EFFORT||a.effort||null},i=so,r=ao}let s=t.effort||n.effort||null;return{runner:e,models:i,efforts:r,chat:n,pick:{model:t.model||null,effort:t.effort||null},model:t.model||n.model||null,effort:s&&r.includes(s)?s:e==="codex"?null:s}}function fo(){if(process.env.LOOP_CODEX_MODEL)return process.env.LOOP_CODEX_MODEL;let e=h.join(te.homedir(),".codex"),t=null,n=[];try{t=/^\s*model\s*=\s*"([^"]+)"/m.exec(y.readFileSync(h.join(e,"config.toml"),"utf8"))?.[1]||null}catch{}try{let i=JSON.parse(y.readFileSync(h.join(e,"models_cache.json"),"utf8"));n=(Array.isArray(i)?i:i.models||[]).filter(r=>(r.visibility||"list")==="list").map(r=>r.slug||r.id).filter(Boolean)}catch{}return t&&(!n.length||n.includes(t))?t:n[0]||t||null}var N=(e=8)=>no.randomBytes(e).toString("base64url").slice(0,e),d=uo()||{version:1,name:h.basename(Y),token:N(16),agent:{mode:"headless"},frames:[],strokes:[],comments:[]},v=new Map,ae=null,ge=null;function uo(){try{return JSON.parse(y.readFileSync(Le,"utf8"))}catch{return null}}var ye=h.join(_,"canvas-history"),ho=80,ct=null,ht=null,wn=e=>({at:Date.now(),frames:new Set((e.frames||[]).map(t=>t.id)),comments:(e.comments||[]).length,sections:(e.sections||[]).length});function yn(e="auto",t=!1){try{let n=wn(d),i=ht;ht=n;let r=i&&([...i.frames].some($=>!n.frames.has($))||n.comments<i.comments||n.sections<i.sections),s=!ct||Date.now()-ct.at>10*6e4;if(!t&&!r&&!s||!y.existsSync(Le))return;let a=JSON.parse(y.readFileSync(Le,"utf8"));if(!a.frames?.length&&!a.comments?.length)return;y.mkdirSync(ye,{recursive:!0});let l=String(Date.now());y.writeFileSync(h.join(ye,`${l}.json`),JSON.stringify({label:t?e:r?"before a change":"auto",at:Date.now(),state:{name:a.name,frames:a.frames||[],sections:a.sections||[],strokes:a.strokes||[],comments:a.comments||[]}}));let m=y.readdirSync(ye).filter($=>/^\d+\.json$/.test($)).sort();for(let $ of m.slice(0,Math.max(0,m.length-ho)))y.rmSync(h.join(ye,$),{force:!0});ct={at:Date.now()}}catch{}}function mo(){try{return y.readdirSync(ye).filter(e=>/^\d+\.json$/.test(e)).sort().reverse().map(e=>{try{let t=JSON.parse(y.readFileSync(h.join(ye,e),"utf8"));return{id:e.slice(0,-5),at:t.at,label:t.label,frames:t.state.frames.length,comments:t.state.comments.filter(n=>!n.parentId).length,names:t.state.frames.slice(0,4).map(n=>n.name)}}catch{return null}}).filter(Boolean)}catch{return[]}}function ze(){yn();let e=Le+".tmp";y.writeFileSync(e,JSON.stringify(d)),y.renameSync(e,Le)}var mt=null;function po(){clearTimeout(mt),mt=setTimeout(ze,120)}d.sections||=[];for(let e of d.frames)delete e.building;for(let e of d.comments)e.status==="working"&&(e.status="error",e.reply="Interrupted \u2014 the server restarted.");for(let e of d.strokes||[]){if(!e.frameId||e.fx!=null)continue;let t=d.frames.find(b=>b.id===e.frameId);if(!t)continue;e.fx=t.x,e.fy=t.y;let n=e.commentId&&d.comments.find(b=>b.id===e.commentId),i=n?.anchor;if(!i||i.scope==="area"||i.scope==="elements"||!Number.isFinite(i.x)||!Number.isFinite(i.y))continue;let r=d.strokes.filter(b=>b.commentId===n.id&&b.frameId===t.id),s=r.flatMap(b=>b.points.filter((I,j)=>j%2===0)),a=r.flatMap(b=>b.points.filter((I,j)=>j%2===1));if(!s.length)continue;let l=t.x+i.x-(Math.min(...s)+Math.max(...s))/2,m=t.y+i.y-(Math.min(...a)+Math.max(...a))/2;if(Math.hypot(l,m)<4)continue;let $=(b,I)=>s.filter((j,E)=>j+b>=t.x&&j+b<=t.x+t.w&&a[E]+I>=t.y&&a[E]+I<=t.y+t.h).length;if(!($(l,m)<=$(0,0)))for(let b of r)b.fx=t.x-l,b.fy=t.y-m}var go=(()=>{let e=(n,i)=>{try{return oo(n,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1500,cwd:h.dirname(_)}).trim()}catch{return""}},t=process.env.LOOP_NAME||(process.platform==="darwin"?e("id",["-F"]):"")||e("git",["config","user.name"]);if(!t)try{t=te.userInfo().username}catch{}return String(t||"").trim().slice(0,32)||"Host"})();function kn(e){let t={};for(let[a,l]of v)t[a]={commentId:l.commentId,step:l.step,startedAt:l.startedAt};let{token:n,cloud:i,...r}=d,s=Te();return{...r,chatContext:e==="owner"?_n():void 0,publicLink:e==="owner"&&ae?`${ae}${Z}/?t=${d.token}`:void 0,codeId:Zn,down:[...xe],chatHistory:!!Wn(),hostName:d.hostName||go,live:t,role:e,version:_t,update:e==="owner"?ee:void 0,emailSharing:!!H,chatListening:Re(),agentBin:s,agentLabel:we[s].label,models:Ce(s),runners:Object.fromEntries(Object.entries(we).map(([a,l])=>[a,!!l.bin])),share:e==="owner"?At():void 0}}var dt=new Map;async function wo(e){if(dt.has(e))return dt.get(e);let t=null,n=async i=>{try{let r=await fetch(i,{redirect:"follow",signal:AbortSignal.timeout(5e3)}),s=(r.headers.get("content-type")||"").split(";")[0];if(r.ok&&/^image\//.test(s)){let a=Buffer.from(await r.arrayBuffer());if(a.length&&a.length<3e5)return{type:s,buf:a}}}catch{}return null};try{let r=[...(await fetch(`https://${e}/`,{redirect:"follow",signal:AbortSignal.timeout(5e3),headers:{accept:"text/html"}}).then(a=>a.ok?a.text():"").catch(()=>"")).matchAll(/<link[^>]+rel=["'][^"']*icon[^"']*["'][^>]*>/gi)].map(a=>/href=["']([^"']+)["']/.exec(a[0])?.[1]).filter(Boolean),s=r.find(a=>/\.svg(\?|$)/i.test(a))||r.find(a=>/\.png/i.test(a))||r[0];s&&(t=await n(new URL(s,`https://${e}/`).href))}catch{}return t||=await n(`https://${e}/favicon.ico`),dt.set(e,t),t}var Z="/__loop";function Kt(e,t,n,i=409){e.writeHead(i,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),e.end(`<!doctype html><meta charset="utf-8"><body style="margin:0;height:100vh;display:grid;place-items:center;background:#fff;color:#88888F;font:14px/1.5 Inter,system-ui,sans-serif"><div style="max-width:420px;padding:24px;text-align:center"><div style="color:#17171A;font-weight:600;font-size:15px;margin-bottom:4px">${t}</div>${n}</div></body>`)}var xe=new Set,Dt=e=>{try{let t=new URL(e);return/^(localhost|127\.0\.0\.1|\[::1\])$/.test(t.hostname)?t.origin:null}catch{return null}};function yo(){if(!qe.size)return;let e=new Set(d.frames.filter(t=>t.kind==="url").map(t=>Dt(t.src)).filter(Boolean));for(let t of[...xe])e.has(t)||xe.delete(t);for(let t of e){let n=new URL(t),i=pn.connect({host:n.hostname.replace(/^\[|\]$/g,""),port:+n.port||80}),r=!1,s=a=>{r||(r=!0,i.destroy(),a===xe.has(t)&&(a?xe.delete(t):xe.add(t),K({type:"state"})))};i.setTimeout(1500,()=>s(!1)),i.on("connect",()=>s(!0)),i.on("error",()=>s(!1))}}setInterval(yo,4e3).unref();function pt(e,t,n,i){let r=new URL(n),s={...e.headers,host:r.host},a=hn.request({hostname:r.hostname,port:r.port||80,method:e.method,path:i||e.url,headers:s},l=>{let m={...l.headers};typeof m.location=="string"&&m.location.startsWith(r.origin)&&(m.location=m.location.slice(r.origin.length)||"/"),delete m["x-frame-options"],m.vary=[m.vary,"Referer"].filter(Boolean).join(", "),m["content-security-policy"]&&(m["content-security-policy"]=String(m["content-security-policy"]).replace(/frame-ancestors[^;]*;?/i,"")),t.writeHead(l.statusCode||502,m),l.pipe(t)});a.on("error",l=>{if(t.headersSent)return t.end();t.writeHead(502,{"content-type":"text/html; charset=utf-8"}),t.end(`<body style="font:14px system-ui;color:#8b8880;display:grid;place-items:center;height:100vh;margin:0">The dev server at ${Oe(n)} isn't responding (${Oe(l.code||l.message)}). Start it, or run <code>loop scan</code>.</body>`)}),e.pipe(a)}var qe=new Set;function gt(e,t){e.write(`data: ${JSON.stringify(t)}
|
|
3
3
|
|
|
4
|
-
`)}var
|
|
4
|
+
`)}var bn=["frames","comments","strokes","sections"];function ko(e,t){let n={};for(let[i,r]of Object.entries(t))n[i]=bn.includes(i)&&Array.isArray(r)?new Map(r.map(s=>[s.id,JSON.stringify(s)])):JSON.stringify(r??null);e.last=n}function $n(e){let t=kn(e.role),n=e.last;if(!n)return ko(e,t),{type:"state",state:t};let i={type:"patch"},r=!1;for(let[s,a]of Object.entries(t))if(bn.includes(s)&&Array.isArray(a)){let l=n[s]instanceof Map?n[s]:new Map,m=new Map,$=[];for(let j of a){let E=JSON.stringify(j);m.set(j.id,E),l.get(j.id)!==E&&$.push(j)}let b=[...m.keys()],I=b.length!==l.size||b.join(`
|
|
5
5
|
`)!==[...l.keys()].join(`
|
|
6
|
-
`);(
|
|
7
|
-
<meta name="loop-placeholder" content="1"><title>${
|
|
8
|
-
<meta name="loop-empty" content="1"><title>${
|
|
9
|
-
<body></body></html>`;function
|
|
6
|
+
`);($.length||I)&&((i.lists||={})[s]={up:$,...I?{order:b}:{}},r=!0),n[s]=m}else{let l=JSON.stringify(a??null);n[s]!==l&&((i.set||={})[s]=a??null,n[s]=l,r=!0)}return r?i:null}function K(e){for(let t of qe){if(e.type!=="state"){gt(t.res,e);continue}let n=$n(t);n&>(t.res,n)}}var Yt=null,H=null,wt=new Set;function x(e){po(),clearTimeout(Yt),Yt=setTimeout(()=>K({type:"state"}),16),e||H?.schedulePush();for(let t of[...wt])t()}var Ie=new Map;function De(e){if(e.kind!=="folder"||Ie.has(e.id))return;let t=null;try{let n=y.watch(e.src,{recursive:!0},(i,r)=>{if(!(r&&(r.startsWith(".")||r.includes("node_modules")))){if(clearTimeout(t),tt.add(e.id),e.shapeless&&!Lt(h.join(e.src,e.entry||"index.html"))&&(delete e.shapeless,x()),v.get(e.id)?.inbox&&r&&Q(e.id,`Editing ${h.basename(String(r))}`),e.building&&e.optionOf&&Date.now()-e.createdAt>1500){let s=d.comments.find(a=>a.id===e.optionOf.cid)?.options?.find(a=>a.frameId===e.id);s&&!s.touched&&(s.touched=!0,e.building="filling",x(),v.has(e.optionOf.from)&&Q(e.optionOf.from,`Making option ${s.id}${s.placeholder?"":` \xB7 ${s.name}`}`))}t=setTimeout(()=>{K({type:"frame-changed",frameId:e.id,live:v.has(e.id)}),v.has(e.id)||H?.frameChanged(e)},v.has(e.id)?450:200)}});Ie.set(e.id,n)}catch{}}function Me(e){Ie.get(e)?.close(),Ie.delete(e)}d.frames.forEach(De);function yt(e=1280,t=800,n){let i=n&&d.frames.find(a=>a.id===n);if(i){let a=($,b)=>d.frames.some(I=>$<I.x+I.w+60&&$+e+60>I.x&&b<I.y+I.h+60&&b+t+60>I.y),l=i.x+i.w+120,m=i.y;for(let $=0;$<50&&a(l,m);$++)l+=160;return{x:l,y:m}}if(!d.frames.length)return{x:0,y:0};let r=Math.max(...d.frames.map(a=>a.x+a.w)),s=Math.min(...d.frames.map(a=>a.y));return{x:r+120,y:s}}function Sn(e){return(e||"frame").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"frame"}function bo(e){let t=e.split(/[?#]/)[0];return t==="/"||!t?"Home":t.split("/").filter(Boolean).map(n=>decodeURIComponent(n).replace(/\.html?$/,"").replace(/[-_]+/g," ").replace(/^\w/,i=>i.toUpperCase())).join(" / ").slice(0,60)}function z({src:e,route:t,name:n,w:i,h:r,x:s,y:a,near:l,dup:m}){if(i=+i||be.Desktop[0],r=+r||be.Desktop[1],t!=null){t="/"+String(t).replace(/^\/+/,"");let T=!m&&d.frames.find(M=>M.kind==="route"&&M.src===t&&M.w===i);if(T)return T;let R=s!=null&&a!=null?{x:+s,y:+a}:yt(i,r,l),L={id:N(6),name:n||t,kind:"route",src:t,entry:"",w:i,h:r,...R,createdAt:Date.now()};return d.frames.push(L),x(),L}let $=/^https?:\/\//.test(e);if($){let T=null;try{T=new URL(e)}catch{}if(T&&/^(localhost|127\.0\.0\.1|\[::1\])$/.test(T.hostname)&&+T.port===X){if(T.pathname===Z||T.pathname.startsWith(Z+"/")||!d.proxy)throw new Error(`${e} is the Loop canvas itself, not your app. Give the address your app runs on (loop scan --url http://localhost:<port>), or a folder with an index.html.`);return z({route:T.pathname+T.search,name:n,w:i,h:r,x:s,y:a,near:l,dup:m})}let R=Dt(e);if(T&&R&&(!d.proxy||d.proxy===R))return d.proxy=R,z({route:T.pathname+T.search,name:n,w:i,h:r,x:s,y:a,near:l,dup:m})}let b=$?"url":"folder",I="index.html";$||(e=h.resolve(Y,e),y.existsSync(e)&&y.statSync(e).isFile()&&(I=h.basename(e),e=h.dirname(e)));let j=s!=null&&a!=null?{x:+s,y:+a}:yt(i,r,l),E={id:N(6),name:n||($?new URL(e).pathname:h.basename(e)),kind:b,src:e,entry:I,w:i,h:r,...j,createdAt:Date.now()};return d.frames.push(E),De(E),x(),E}var Oe=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&","<":"<",">":">",'"':"""})[t]),$o=e=>`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
7
|
+
<meta name="loop-placeholder" content="1"><title>${Oe(e)}</title><style>html,body{height:100%;margin:0;background:#fff}</style></head><body></body></html>`,So=e=>`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
8
|
+
<meta name="loop-empty" content="1"><title>${Oe(e)}</title><style>html,body{height:100%;margin:0;background:#fff}</style></head>
|
|
9
|
+
<body></body></html>`;function ke(e){let t=Sn(e),n=h.join(_,"frames",t),i=2;for(;y.existsSync(n);)n=h.join(_,"frames",`${t}-${i++}`);return n}function se(e){let t=new Set(d.frames.map(n=>n.name));if(!t.has(e))return e;for(let n=2;;n++)if(!t.has(`${e} ${n}`))return`${e} ${n}`}function Xt(e,t=!1){let n=ke(e);return y.mkdirSync(n,{recursive:!0}),y.writeFileSync(h.join(n,"index.html"),t?So(e):$o(e)),n}var xn=new Set(["node_modules",".git",".loop",".next","dist","build"]);async function fe(e,t,n={bytes:3e7}){await D.mkdir(t,{recursive:!0});for(let i of await D.readdir(e,{withFileTypes:!0})){if(i.name.startsWith(".")||xn.has(i.name))continue;let r=h.join(e,i.name),s=h.join(t,i.name);if(i.isDirectory())await fe(r,s,n);else if(i.isFile()){let{size:a}=await D.stat(r);if((n.bytes-=a)<0)throw new Error("frame too large to snapshot");await D.copyFile(r,s)}}}async function kt(e,t=e,n=new Set){for(let i of await D.readdir(e,{withFileTypes:!0})){if(i.name.startsWith(".")||xn.has(i.name))continue;let r=h.join(e,i.name);i.isDirectory()?await kt(r,t,n):n.add(h.relative(t,r))}return n}function ot(e,t,n){for(let i of y.readdirSync(e,{withFileTypes:!0})){if(i.name.startsWith("."))continue;let r=h.join(e,i.name);i.isDirectory()?ot(r,t,n):n.add(h.relative(t,r))}}var Vt=new Map;async function Mt(e,t){if(e.kind!=="folder")return null;let n=h.join(_,"history",t);try{return await fe(e.src,n),xo(e,t,n),n}catch{return null}}var Lt=e=>{try{return/<meta name="loop-(empty|placeholder)"/.test(y.readFileSync(e,"utf8").slice(0,2e3))}catch{return!1}};function xo(e,t,n){let i=d.comments.find(r=>r.id===t);i&&Lt(h.join(n,e.entry||"index.html"))&&(i.snapBlank=!0)}for(let e of d.comments)if(e.snapshot&&!e.snapBlank){let t=d.frames.find(n=>n.id===e.frameId);t?.kind==="folder"&&Lt(h.join(e.snapshot,t.entry||"index.html"))&&(e.snapBlank=!0)}async function Ge(e,t){if(e.kind!=="folder")return null;let n=h.join(_,"history",t);try{return await D.rm(n,{recursive:!0,force:!0}),await fe(e.src,n),n}catch{return null}}async function Ue(e,t){let n=await kt(e.src),i=await kt(t);for(let r of n)i.has(r)||await D.rm(h.join(e.src,r),{force:!0});await fe(t,e.src)}function Zt(e,t={}){let n=t.file_path||t.path||t.notebook_path,i=n?h.basename(n):"",r=String(t.command||"");switch(e){case"Read":return n&&/\.(png|jpe?g|webp|gif)$/i.test(n)?n.includes(`${h.sep}shots${h.sep}`)?"Looking at the screen":n.includes(`${h.sep}annotations${h.sep}`)?"Looking at your marks":"Looking at your reference":i?`Reading ${i}`:"Reading the code";case"Edit":case"MultiEdit":return i?`Editing ${i}`:"Editing";case"Write":return i?`Writing ${i}`:"Writing";case"Glob":case"Grep":return"Searching the code";case"Bash":return/cli\.mjs"? shot\b|\bloop shot\b/.test(r)?"Taking a screenshot":/cli\.mjs"? (new|add-route)\b/.test(r)?"Adding a frame":/cli\.mjs"? option\b/.test(r)?"Setting up an option":r?"Running a command":"Working\u2026";case"TodoWrite":return"Planning";case"WebFetch":case"WebSearch":return"Looking something up";default:return e}}var be={Mobile:[393,852],Tablet:[834,1194],Desktop:[1440,1024]},We=e=>e.w<=480?"Mobile":e.w>=1100?"Desktop":e.h>=e.w*1.15?"Tablet":"Custom-size";function bt(e){let t=d.frames.filter(n=>n.id!==e?.id);return["","How Loop canvases work (follow these conventions):",`- A frame is one screen at one device size. Standard sizes: Mobile ${be.Mobile.join("\xD7")}, Tablet ${be.Tablet.join("\xD7")}, Desktop ${be.Desktop.join("\xD7")}. When someone asks for a "mobile", "phone", "tablet", "iPad", "desktop" or "web" version, use the matching size.`,"- Change only the project (or this frame's folder). Never edit Loop itself: its canvas, toolbar, menus or .loop/ files are not yours to change.","- A frame IS the device screen: design edge to edge at that size. Never draw a phone or laptop mockup, notch, status bar, home indicator or bezel inside a frame, and never letterbox a small layout in the middle of a big frame.","- Phones and tablets have safe areas, like the real devices. On a real phone the status bar (time, signal, battery) covers the top 54px of the screen and the home indicator the bottom 34px, and Loop can show them on stage; on a tablet, 24px at the top and 20px at the bottom. Keep text, buttons and headers out of those strips (pad the top and bottom of the page by that much, sticky headers and tab bars included) and let the page's background run underneath them.",'- "A mobile version of this" means the same screen, content and copy, re-laid-out for that width: single column, stacked sections, a mobile navigation pattern (top bar, tab bar or menu), tap targets of at least 44px, readable type. Keep the same colours, fonts and components.','- Name frames "<Screen> \u2014 <Device>", e.g. "Settings \u2014 Mobile". New frames go next to the frame they came from.',"- Keep frames consistent with each other: reuse the visual style already on the canvas.",...t.length?["- Other frames on this canvas: "+t.map(n=>`"${n.name}" (${n.image?`reference image, ${n.src}, `:""}${We(n)} ${n.w}\xD7${n.h}${n.kind==="route"?`, app route ${n.src}`:""})`).join("; ")+"."]:[]]}function vn(e,t,n){let i=(t.batch||[]).map(r=>d.comments.find(s=>s.id===r)).filter(Boolean);return i.length?[n,"",`There are ${i.length} more comment${i.length>1?"s":""} on this same screen. Handle them all in this one pass, in order:`,...i.map((r,s)=>`
|
|
10
10
|
--- Comment ${s+2} ---
|
|
11
|
-
${
|
|
12
|
-
`):
|
|
13
|
-
`);if(
|
|
14
|
-
`)
|
|
11
|
+
${Ft(e,r).message.replace(/^On my Loop canvas I'm looking at[^\n]*\n?/,"")}`),"","In your reply, give one short line per comment (1, 2, \u2026) saying what you changed."].join(`
|
|
12
|
+
`):n}function In(e){for(let t=e,n=0;t&&n<6;n++){if(t.kind==="route")return{mode:t===e?"wrap":"replace",route:t.src,frame:t};if(t.draftOf)return{mode:"replace",route:t.draftOf};if(t.optionOf?.live){let i=d.comments.find(s=>s.id===t.optionOf.cid)?.options?.find(s=>s.id===t.optionOf.oid);return{mode:"replace",route:C(t.optionOf.from)?.src,optionDir:i?.dir}}if(t.kind==="frozen"&&t.from)return{mode:"replace",route:t.from};t=t.optionOf?C(t.optionOf.from):null}return{mode:"add"}}function vo(e){let t=e.build,n=t.frames.map(C).filter(Boolean),i=n.length>1,r=[`This is final: build ${i?"these screens":`"${n[0].name}"`} into the real project in the current working directory (${Y}).`,""];e.text&&!/^Build (this|these)/.test(e.text)&&r.push("My note:",'"""',e.text,'"""',""),r.push(i?"The screens (build them together, so anything they share is built once):":"The screen:");for(let s of n){let a=In(s),l=s.id===e.frameId?t.mode:a.mode,m=s.kind==="folder"?`its design is the static page in ${s.src} (entry: ${s.entry})`:s.kind==="route"?`it is the app's live "${s.src}" route`:s.kind==="url"?`its design is the live page at ${s.src}`:`it is in ${s.src}`;r.push(`- "${s.name}" (${We(s)}, ${s.w}\xD7${s.h}): ${m}.${a.optionDir?` It is an option of the app's "${a.route}" screen; the option's files are in ${a.optionDir}, at the same paths as in the project.`:""}`),l==="wrap"?r.push(" It is already the real screen: the changes made through the canvas are in the code. Wrap them up: review what changed for this screen, tidy it to the project's standard (types, components, naming, no leftovers), and make sure it builds."):l==="replace"&&a.route?r.push(` Replace the app's "${a.route}" screen with this design: change that screen's real code to match it exactly. Keep what the screen does (its data, state, navigation, handlers); change how it looks and is laid out.`):l==="replace"?r.push(" Replace the existing screen this design is for (find it in the code) with this design, keeping what that screen does."):r.push(" Add it to the project as a new screen: pick where it belongs (a route, page or component, following how the project is organised) and say where you put it.")}return r.push("","How to build it:","- Build it the project's way: its framework, its components, its styles and tokens, its data. Do not paste the mockup's HTML or inline styles into the code; rebuild it with what the project already has, adding a component only where nothing fits.","- Match the design faithfully: layout, spacing, type, colour, content, and its states and interactions.","- If it isn't clear where a new screen belongs, or replacing would remove something that looks important, ask me in your reply before writing anything.","- When it's built, check it: run the project's type check or build if it's quick, and fix what fails.",d.proxy?`- Then put the real screen on the canvas next to the design so we can compare: \`node ${V} add-route <path> --near ${e.frameId} --dir ${_}\` (skip this if that route is already on the canvas).`:"- There is no dev server connected to the canvas, so just tell me how to open the result.",t.commit?"- Then commit only the files you changed for this, with a short message saying what screen was built. Never push.":"- Don't commit; I'll review the changes first.","","When you're done, tell me in two or three plain lines what you built and where it lives."),r.join(`
|
|
13
|
+
`)}function Ct(e,t){if(t.kind==="build")return vo(t);let n=[];if(t.kind==="create")return n.push(`On my Loop canvas, design a new screen called "${e.name}" (${We(e)}, ${e.w}\xD7${e.h}):`,"",t.text,"","Write it as a complete index.html in the current working directory (self-contained HTML/CSS/JS; CDN imports and web fonts are fine, no build step), real content and working interactions where they make sense.","","Design it the way you would if I had asked you directly in a chat: make real design decisions (layout, hierarchy, type, colour, detail) so it looks finished, not like a wireframe.","Build it in passes I can watch fill in on the canvas (it reloads the frame on every write): first write the page with its overall layout and each main block in place (real headings, the blocks as simple boxes), then fill the blocks one at a time, top to bottom, with one edit each. Never leave the frame empty while you work, and don't write the whole page in one go at the end.",`Look at it as you go: \`node ${V} shot ${e.id} --dir ${_}\` saves a screenshot of the frame and prints its path. Check it after your first pass and iterate until it looks right at ${e.w}\xD7${e.h}.`,...bt(e),"","When you're done, tell me briefly what you made."),n.join(`
|
|
14
|
+
`);if(e.kind==="canvas"){n.push("You are the design agent behind Loop, a canvas of live frames for the project in the current working directory. The user left a general comment on the canvas itself (not on a single frame).","","Frames on the canvas:",...d.frames.map(s=>`- "${s.name}": ${s.image?`an image placed as a reference, in ${s.src}`:s.kind==="folder"?`static files in ${s.src}`:s.kind==="frozen"?`a frozen snapshot of ${s.from||"an app screen"} (read-only)`:s.kind==="route"?`the app's ${s.src} route (dev server ${d.proxy})`:s.src}`));let i=t.anchor?.near,r=t.anchor?.section;return r&&i?.length?n.push("",`The comment is on the section "${String(r.name||"Section").slice(0,80)}", which holds these frames: ${i.map(s=>`"${s}"`).join(", ")}. It is about them together: decide which of them it concerns (often all of them) and make the change in each, keeping them consistent.`):t.anchor?.area&&i?.length?n.push("",`They drew a box on the canvas over: ${i.map(s=>`"${s}"`).join(", ")}. Those frames are the focus; the box is approximate.`):i?.length&&n.push("",`The comment was placed near: ${i.map(s=>`"${s}"`).join(", ")}.`),n.push(...bt(null)),n.push("","Comment:",'"""',t.text,'"""',"",`To add a frame: \`node ${V} new "<Screen> \u2014 <Device>" --w <w> --h <h> --dir ${_}\` prints a folder; write a self-contained index.html there.`,On.slice(2),"Decide which frames or source files it concerns and make the change. If it is a question or a note that needs no change, just answer it. When done, reply to the user the way you would in a chat: a short, plain summary of what you changed (one to three sentences). If they asked a question, answer it properly. If something was ambiguous, say what you assumed."),n.join(`
|
|
15
|
+
`)}return Po(Ft(e,t))}var Io=(e,t)=>{let n=`\`node ${V} shot ${e.id} --dir ${_}\``,i=To(t)||Fe.has(t.id)&&t.shotSoon;return["Work on this the way you would if I had asked you directly in a chat:",i?`- This is the screen as I see it right now: ${i} (look at it first, along with the relevant code). No need to take that screenshot yourself.`:`- Understand it first: read the relevant code, and look at the screen as I see it (${n} saves a screenshot and prints its path).`,`- Match the effort to what I asked. A small, specific fix (wording, a colour, spacing, one element): just make it, precisely, and don't spend time on more screenshots. Design work, a layout change, or anything vague ("make it nicer", "this feels off"): make real design decisions (hierarchy, spacing, type, colour, detail), then check the result with a screenshot (`+n+") and iterate until it looks right.","- Keep it consistent with the rest of the screen and canvas unless I'm asking you to change the style.","- When you're done, reply like you would in a chat: what you changed, briefly, and anything I should know. Answer questions properly.",On]},On="- If a command or tool is refused, don't look for another way to do the same thing. Finish what you can and say in your reply what you needed and why: I'll see it with an Allow button.",he=new Map,Fe=new Map;function Oo(e,t){if(!it||!X||t.kind==="canvas"||t.id===pe)return;let n=he.get(t.id)||0;e.shotSoon=h.join(_,"shots",`${t.id}-${e.id}.png`);let i=me(t,void 0,h.basename(e.shotSoon)).then(r=>{e.shot=r,e.shotRev=n}).catch(()=>{e.shotSoon=null}).finally(()=>Fe.delete(e.id));Fe.set(e.id,i)}var To=e=>e.shot&&e.shotRev===(he.get(e.frameId)||0)&&y.existsSync(e.shot)?e.shot:null,jo=e=>Fe.has(e.id)?Promise.race([Fe.get(e.id),new Promise(t=>setTimeout(t,3e3))]):null,_e=(e,t)=>typeof e=="string"?e.slice(0,t):void 0;function Qt(e){return(Array.isArray(e)?e:[]).slice(0,8).filter(t=>t&&typeof t.frameId=="string"&&C(t.frameId)).map(t=>({frameId:t.frameId,label:_e(t.label,80)||"it",selector:_e(t.selector,400),tag:_e(t.tag,20),text:_e(t.text,300),html:_e(t.html,3e3)}))}function $t(e){return e.kind==="folder"?`static page, files in ${e.src} (entry ${e.entry||"index.html"})`:e.kind==="route"?`the app's ${e.src.replace(/^\/__loop\/o\/[^/]+\/[A-F]/,"")} route`:e.kind==="frozen"?"a frozen snapshot":`live page ${e.src}`}function Ao(e){return e.refs?.length?["","This message points at other things on the canvas (each written as @name in it):",...e.refs.map(t=>{let n=C(t.frameId);return n?t.selector?`- @${t.label}: the ${t.tag||"element"} \`${t.selector}\` in the frame "${n.name}" (${$t(n)})${t.text?`, text: "${t.text}"`:""}${t.html?`
|
|
15
16
|
Its HTML as it is now:
|
|
16
17
|
${t.html.replace(/\n/g,`
|
|
17
|
-
`)}`:""}`:`- @${t.label}: the frame "${
|
|
18
|
+
`)}`:""}`:`- @${t.label}: the frame "${n.name}" (${$t(n)}, ${n.w}\xD7${n.h})`:`- @${t.label}: (no longer on the canvas)`})]:[]}function Ft(e,t){let n=[];e.sessionCwd&&n.push("(You are a background copy of the chat that launched this Loop canvas, carrying on from what was said there, because that chat is not listening right now. Do not start `loop watch`, and do not use `loop reply`, `loop note` or `loop inbox` here: do what the comment asks and answer in your final message. Your working directory is the project; the frame paths below are absolute.)");let i=t.parentId?d.comments.filter(l=>(l.id===t.parentId||l.parentId===t.parentId)&&l.id!==t.id&&l.createdAt<t.createdAt):[];if(n.push(`On my Loop canvas I'm looking at "${e.name}", a live ${We(e)} screen (${e.w}\xD7${e.h}).`),e.image)n.push(`It's an image placed on the canvas as a reference (the file is in the current working directory). Look at it. When the request is about another screen ("make that one look like this"), change that screen, not this image.`);else if(e.kind==="folder"&&e.draftOf)n.push(`It's an editable draft copied from the app's "${e.draftOf}" screen: a static page whose files are in the current working directory (entry: ${e.entry}). Change this copy, not the app. Only when I ask to use it in the app (or "make it real"), build it into the app's source for that screen or as the new screen I describe, matching what this draft shows.`);else if(e.kind==="folder")n.push(`It's a static page: its files are in the current working directory (entry: ${e.entry}).`);else if(e.kind==="frozen")n.push(`It's a frozen snapshot of ${e.from?`the app's "${e.from}" screen`:"an app screen"}, kept as the "before". Leave the snapshot alone and change the app's source for that screen; its live frames show the result.`);else if(e.optionOf?.live){let l=d.comments.find(m=>m.id===e.optionOf.cid)?.options?.find(m=>m.id===e.optionOf.oid);n.push(`It's option ${e.optionOf.oid} of an app screen: the real app running with this option's files in place of the project's. This option's files are in ${l?.dir} (same paths as in the project, ${Y}). Change ONLY this option: edit the files in that folder, and when the change needs a project file the option doesn't have yet, copy it into that folder at the same path first and edit the copy. Never edit the project's own files for this.`)}else e.kind==="route"?n.push(`It's the app's "${e.src}" route, running live from the project in the current working directory (dev server ${d.proxy}, hot reload; don't restart it).`):n.push(`It's a live page at ${e.src}, served from the project in the current working directory.`);if(e.kind==="folder")try{y.readFileSync(h.join(e.src,e.entry),"utf8").includes('name="loop-empty"')&&n.push(`It's empty right now: design the whole screen from scratch at exactly ${e.w}\xD7${e.h} in index.html, and remove the loop-empty meta tag.`)}catch{}if(i.length){n.push("","What we said so far about this:");for(let l of i)n.push(l.kind==="note"?`- You: ${l.text}`:`- Me: ${l.text}${l.reply&&l.status!=="interrupted"?`
|
|
18
19
|
- You: ${l.reply}`:l.status==="interrupted"?`
|
|
19
|
-
- (you were working on that when I interrupted)`:""}`)}t.steeredFrom&&
|
|
20
|
-
`)," ```")}else r?.scope==="frame"?s.push("I mean the whole screen."):r&&r.selector?(s.push(`My comment pin is on <${r.tag}> \`${r.selector}\`${r.text?` ("${r.text}")`:""}. It may be about that element or the area around it.`),r.html&&s.push("```html",r.html,"```")):r&&s.push(`I pointed at x=${Math.round(r.x)}, y=${Math.round(r.y)} in the viewport.`);t.ink?.length&&s.push(`I drew marks over: ${t.ink.map(l=>`\`${l.selector}\`${l.text?` ("${l.text}")`:""}`).join(", ")}.`),t.annotation&&s.push(`A picture of my marks over the screen: ${t.annotation} (look at it).`),t.attachments?.length&&s.push(`I attached ${t.attachments.length===1?"a reference":`${t.attachments.length} references`}; look at ${t.attachments.length===1?"it":"them"} first: ${t.attachments.map(l=>`${l.path} (${l.type})`).join(", ")}.`);let a=
|
|
21
|
-
`),reference:
|
|
22
|
-
`).length)}return r.length?`It is in ${e.entry||"index.html"} at line ${[...new Set(r)].sort((s,a)=>s-a).join(", ")}: open it there, no need to search for it.`:""}function
|
|
23
|
-
`)}function
|
|
20
|
+
- (you were working on that when I interrupted)`:""}`)}t.steeredFrom&&n.push("","I interrupted you to add this. The files may already have part of that work in them: carry on from where things are and do what both messages ask (this one wins where they conflict)."),n.push("",t.text);let r=t.anchor,s=[];if(r?.scope==="area")s.push(`I highlighted an area: x=${Math.round(r.x)}, y=${Math.round(r.y)}, ${Math.round(r.w)}\xD7${Math.round(r.h)}px in the ${e.w}\xD7${e.h} viewport. It's roughly where to look, not a strict boundary.`),r.elements?.length&&s.push("Inside it: "+r.elements.map(l=>`<${l.tag}> \`${l.selector}\`${l.text?` ("${l.text}")`:""}`).join("; ")+"."),r.container&&s.push(`Smallest element wrapping it: <${r.container.tag}> \`${r.container.selector}\`.`);else if(r?.scope==="elements"&&r.elements?.length){s.push(`I picked ${r.elements.length===1?"this exact element":`these ${r.elements.length} exact elements`}:`);for(let l of r.elements.slice(0,10))s.push(`- <${l.tag}> \`${l.selector}\`${l.text?` ("${l.text}")`:""}`),l.html&&s.push(" ```html"," "+l.html.replace(/\n/g,`
|
|
21
|
+
`)," ```")}else r?.scope==="frame"?s.push("I mean the whole screen."):r&&r.selector?(s.push(`My comment pin is on <${r.tag}> \`${r.selector}\`${r.text?` ("${r.text}")`:""}. It may be about that element or the area around it.`),r.html&&s.push("```html",r.html,"```")):r&&s.push(`I pointed at x=${Math.round(r.x)}, y=${Math.round(r.y)} in the viewport.`);t.ink?.length&&s.push(`I drew marks over: ${t.ink.map(l=>`\`${l.selector}\`${l.text?` ("${l.text}")`:""}`).join(", ")}.`),t.annotation&&s.push(`A picture of my marks over the screen: ${t.annotation} (look at it).`),t.attachments?.length&&s.push(`I attached ${t.attachments.length===1?"a reference":`${t.attachments.length} references`}; look at ${t.attachments.length===1?"it":"them"} first: ${t.attachments.map(l=>`${l.path} (${l.type})`).join(", ")}.`);let a=_o(e,r);return a&&s.push(a),s.length&&n.push("",...s),n.push("",...Io(e,t),"",`(This message's id, for Loop commands: ${t.id})`),n.push(...Ao(t)),{message:n.join(`
|
|
22
|
+
`),reference:Tn(e)}}function _o(e,t){if(e.kind!=="folder"||!t)return"";let n;try{n=y.readFileSync(h.join(e.src,e.entry||"index.html"),"utf8")}catch{return""}let i=[...(t.elements||[]).map(s=>s.html),t.html,t.container?.html].filter(Boolean),r=[];for(let s of i){let a=/^<[^>]+>/.exec(s)?.[0];if(!a)continue;let l=n.indexOf(a);l<0||n.indexOf(a,l+1)>=0||r.push(n.slice(0,l).split(`
|
|
23
|
+
`).length)}return r.length?`It is in ${e.entry||"index.html"} at line ${[...new Set(r)].sort((s,a)=>s-a).join(", ")}: open it there, no need to search for it.`:""}function Tn(e){let t=[],[n,i]=be.Mobile;t.push("You are working inside Loop, a canvas of live frames the user reviews and comments on. Their comments reach you as messages."),t.push("","New frames: if they ask for a new frame (a mobile/desktop version, or a separate copy to keep side by side), leave this frame as it is and add one next to it:"),t.push(`- Resize this frame (when what you are building needs another size): \`node ${V} size ${e.id} <width> <height> --dir ${_}\``),e.kind==="route"?t.push(`- The same app screen at another size: \`node ${V} add-route ${e.src} --name "<Screen> \u2014 Mobile" --w ${n} --h ${i} --near ${e.id} --dir ${_}\`. It's the real app, so if it doesn't fit that width, fix the responsive styles in the source.`,`- A brand-new static design: \`node ${V} new "<Screen> \u2014 <Device>" --w <w> --h <h> --near ${e.id} --dir ${_}\` prints a folder; write a complete self-contained index.html there.`):t.push(`- \`node ${V} new "<Screen> \u2014 <Device>" --w <w> --h <h> --near ${e.id} --dir ${_}\` (e.g. --w ${n} --h ${i} for mobile) prints a folder; write a complete, self-contained index.html there, based on this frame and adapted to that size.`);let r=e.kind==="folder"?e.src:Y;return e.kind==="folder"?t.push("",`Options: if they ask for options to choose from (an option, a variation, alternatives, ideas), leave this frame's files alone. How many: exactly what they asked for. "A variation", "another version", "a better one" is ONE. A number is that number. Only a plural with no number ("some options", "ideas") is your call: 2 or 3, each genuinely different. Each message ends with its id; for each option run \`node ${V} option <message id> "<short name>" --dir ${_}\`. It prints a folder that is a full copy of this frame and is already on the canvas as its own frame beside this one: make that option's changes there, editing its files in place. They watch each one fill in as you work, so start the first option early and finish one before starting the next. \`node ${V} shot ${e.id} --option <message id>:A --dir ${_}\` shows how option A looks. Reply with a line per option on how it differs.`):t.push("",`Options: if they ask for options to choose from (an option, a variation, alternatives, ideas), don't change the real files. How many: exactly what they asked for. "A variation", "another version", "a better one" is ONE. A number is that number. Only a plural with no number ("some options", "ideas") is your call: 2 or 3, each genuinely different. Each message ends with its id; for each option, \`node ${V} option <message id> "<short name>" --dir ${_}\` prints an empty folder: write the complete new version of every file that option changes there, at the same path relative to ${r}. Each option shows up running beside this screen as its own frame as you write it (or, for apps that need a build step, they preview it in the frame), and they pick one; reply with a line per option on how it differs.`),e.kind==="folder"&&t.push("","This frame is self-contained: keep its files in its folder (CDN imports are fine, no build step)."),t.push(...bt(e)),t.join(`
|
|
24
|
+
`)}function Po(e){return e.reference?`${e.message}
|
|
24
25
|
|
|
25
26
|
---
|
|
26
27
|
How Loop works (reference):
|
|
27
|
-
${e.reference}`:e.message}var
|
|
28
|
-
`)[0]}catch{await new Promise(s=>setTimeout(s,50))}if(!i.port){try{o.kill("SIGKILL")}catch{}throw new Error("Chrome did not start")}return i})();let e=B;try{let t=await e;return B===e&&(B=t),t}catch(t){throw B===e&&(B=null),t}}var _e=new Map,Ze=new Set;async function bo(e){let t=`${e.w}x${e.h}`,o=_e.get(e.id);if(o&&!(o instanceof Promise)&&o.size===t&&!Ze.has(e.id)&&k.existsSync(o.file))return o.file;if(o instanceof Promise)return(await o).file;Ze.delete(e.id);let i=he(e).then(r=>{let s=_e.get(e.id),a={file:r,size:t};return _e.set(e.id,a),a}).catch(r=>{throw _e.delete(e.id),r});return _e.set(e.id,i),(await i).file}var Kt=Promise.resolve();function he(e,t,o){let i=Kt.then(()=>So(e,t,o));return Kt=i.catch(()=>{}),i}async function So(e,t,o){if(!tt)throw new Error("No Chrome, Edge, Brave or Chromium found for screenshots (set LOOP_CHROME to one).");let i=globalThis.WebSocket;if(!i)throw new Error("Screenshots need Node 22 or newer");let r=h.join(_,"shots");k.mkdirSync(r,{recursive:!0});let s=h.join(r,o||`${e.id}-${Date.now()}${N(3)}.png`),a=Math.round(e.w),l=Math.round(e.h),m=await bn();m.busy=(m.busy||0)+1;let b=null,w=null;try{for(let D=0;D<40&&!b;D++)try{b=await(await fetch(`http://127.0.0.1:${m.port}/json/new?about:blank`,{method:"PUT"})).json()}catch{await new Promise(z=>setTimeout(z,50))}if(!b?.webSocketDebuggerUrl)throw new Error("Chrome tab not found");w=new i(b.webSocketDebuggerUrl),await new Promise((D,z)=>{w.onopen=D,w.onerror=()=>z(new Error("DevTools connection failed"))});let I=0,T=new Map,E=null;w.onmessage=D=>{let z=JSON.parse(D.data);z.id&&T.has(z.id)?(T.get(z.id)(z),T.delete(z.id)):z.method==="Page.loadEventFired"&&E?.()};let j=(D,z={})=>new Promise((U,te)=>{let je=++I;T.set(je,U),setTimeout(()=>te(new Error("Screenshot timed out")),3e4),w.send(JSON.stringify({id:je,method:D,params:z}))});await j("Page.enable"),await j("Page.bringToFront"),await j("Emulation.setDeviceMetricsOverride",{width:a,height:l,deviceScaleFactor:2,mobile:!1});let R=new Promise(D=>{E=D,setTimeout(D,12e3)});await j("Page.navigate",{url:t||ko(e)}),await R,await Promise.race([j("Runtime.evaluate",{awaitPromise:!0,expression:"(async () => { try { await document.fonts.ready; } catch {} await Promise.all([...document.images].filter(i => !i.complete).map(i => new Promise(r => { i.onload = i.onerror = r; }))); await new Promise(r => setTimeout(r, 250)); })()"}),new Promise(D=>setTimeout(D,2500))]);let C=await j("Page.captureScreenshot",{format:"png",clip:{x:0,y:0,width:a,height:l,scale:1}});if(!C.result?.data)throw new Error("Screenshot failed");return k.writeFileSync(s,Buffer.from(C.result.data,"base64")),s}catch(I){throw b||kt(),I}finally{try{w?.close()}catch{}b?.id&&fetch(`http://127.0.0.1:${m.port}/json/close/${b.id}`).catch(()=>{}),m.busy--,clearTimeout(m.idle),m.busy||(m.idle=setTimeout(()=>{B===m&&!m.busy&&kt()},4*6e4))}}function ce(e){if(v.has(e))return;let t=i=>i.frameId===e&&i.status==="queued"&&!i.inBatch&&(d.agent.mode!=="inbox"||i.background),o=d.comments.find(t);if(o){if(delete o.batch,o.kind!=="create"&&e!==be&&!F(e)?.optionOf){let i=d.comments.filter(r=>r!==o&&t(r)&&r.kind!=="create"&&!bt(r.text)).slice(0,5);if(i.length&&!bt(o.text)){o.batch=i.map(r=>r.id);for(let r of i)r.inBatch=o.id,r.status="working"}}Pn(o)}}function Dt(){for(let e of d.frames)ce(e.id);ce(be)}var $o=new Set(["Reading the code","Editing","Writing","Working\u2026","Setting up an option"]);function V(e,t,o){let i=v.get(e);if(!i)return;i.step=t;let r=o==null&&t&&d.comments.find(s=>s.id===i.commentId);if(r&&!/^(Writing…|Reading your comment…|Your chat picked this up|Working…)$/.test(t)){let s=r.steps||=[],a=s[s.length-1];!$o.has(t)&&(!a||a.s!==t)&&(s.push({t:Date.now(),s:t}),s.length>60&&s.splice(0,s.length-60))}J({type:"activity",frameId:e,commentId:i.commentId,step:t,...o!=null?{partial:o}:{}}),H?.liveChanged(v)}async function Sn(e){let t=F(e.frameId);if(!(!t||t.kind!=="folder"||!e.options?.length||!K)){if(!e.origThumb&&!e.optionApplied)try{e.origThumb=`/__loop/shots/${h.basename(await he(t))}`,$()}catch{}for(let o of e.options)try{let i=await he(t,`http://127.0.0.1:${K}/__loop/optview/${e.id}/${o.id}/${encodeURIComponent(t.entry||"index.html")}`);o.thumb=`/__loop/shots/${h.basename(i)}`,$()}catch{}}}var G={GAP:60,PAD:48,TOP:72},Je=(e,t)=>t*e.w+(t-1)*G.GAP+G.PAD*2;function bt(e){let t=String(e||""),o=/\b(\d|two|three|four|five|six|a couple of|couple of|a few|few|some|several|more|other|different)\s+(?:[\w-]+\s+){0,3}?(options?|variations?|variants?|alternatives?|versions|directions|takes|ideas|explorations?)\b/i.exec(t);if(o){let i=o[1].toLowerCase(),r={two:2,three:3,four:4,five:5,six:6,"a couple of":2,"couple of":2,"a few":3,few:3,some:2,several:3,more:2,other:2,different:2}[i]??+i;return Math.max(1,Math.min(4,r))}return/\b(options|variations|variants|alternatives|explorations)\b/i.test(t)&&/\b(give|make|create|show|try|explore|generate|come up|want|need|can (we|you)|let'?s|what about)\b/i.test(t)?2:/\b(another|a new|one more|a different|an alternative|a second)\s+(version|variation|variant|option|take|direction|design|layout)\b|\bduplicate (this|it)\b|\b(make|create) a copy\b/i.test(t)||/\b(a|an|one)\s+(?:[\w-]+\s+){0,2}?(variation|variant|alternative|option)\b/i.test(t)?1:0}function St(e,t,o=new Set){let i=a=>a.y<e.y+e.h&&a.y+a.h>e.y&&a.x+a.w/2>t.x+t.w,r=[...d.frames.filter(a=>a.id!==t.id&&!o.has(a.id)&&i(a)),...d.sections.filter(a=>!o.has(a.id)&&i(a))];if(!r.length)return;let s=e.x+e.w+G.GAP-Math.min(...r.map(a=>a.x));if(s>0)for(let a of r)a.x+=s}function nt(e,t,o){let i=d.sections.find(r=>r.id===e.optionSection);if(i){if(o>(i.slots||0)){let r=new Set([i.id,...(e.options||[]).map(s=>s.frameId)]);St({x:i.x,y:i.y,w:Je(t,o),h:i.h},t,r),i.w=Je(t,o),i.slots=o}}else{let r={x:t.x+t.w+G.GAP+20,y:t.y-G.TOP,w:Je(t,o),h:t.h+G.TOP+G.PAD};St(r,t),i={id:N(6),name:`Options \xB7 ${t.name}`,...r,optionsFor:e.id,slots:o,createdAt:Date.now()},d.sections.push(i),e.optionSection=i.id}return i}function xo(){let e=[...v.entries()].filter(([s])=>s!==be);if(e.length!==1)return null;let[t,o]=e[0],i=F(t),r=d.comments.find(s=>s.id===o.commentId);return i&&r&&i.kind==="folder"&&!i.optionOf?{c:r,f:i}:null}function vo(e,t,o,i){e.options||=[];let r=String.fromCharCode(65+e.options.length),s=e.options.length,a={id:r,name:i||`Option ${r}`};e.options.push(a);let l=nt(e,t,Math.max(s+1,d.sections.find(b=>b.id===e.optionSection)?.slots||0)),m=W({src:o,name:re(i||`Option ${r}`),w:t.w,h:t.h,x:l.x+G.PAD+s*(t.w+G.GAP),y:t.y});return m.optionOf={cid:e.id,oid:r,from:t.id},m.building=!0,a.dir=o,a.frameId=m.id,a.madeAt=Date.now(),a.touched=!0,$(),m}async function Yt(e,t,o){if(e.options||=[],e.options.length>=6)throw new Error("up to 6 options");let i=String.fromCharCode(65+e.options.length),r=e.options.length,s={id:i,name:o||`Option ${i}`,placeholder:!o};e.options.push(s);let a=nt(e,t,Math.max(r+1,d.sections.find(b=>b.id===e.optionSection)?.slots||0)),l=we(`${t.name} option ${i} ${N(3)}`);await fe(t.src,l);let m=W({src:h.join(l,t.entry||"index.html"),name:re(o?`${i} \xB7 ${o}`:`Option ${i}`),w:t.w,h:t.h,x:a.x+G.PAD+r*(t.w+G.GAP),y:t.y});return m.optionOf={cid:e.id,oid:i,from:t.id},m.building=!0,s.dir=l,s.frameId=m.id,s.madeAt=Date.now(),$(),s}function Io(e){if(e.touched)return!0;let t=F(d.comments.find(o=>o.options?.includes(e))?.frameId)?.src;try{let o=new Set;return qe(e.dir,e.dir,o),[...o].some(i=>{let r=t&&h.join(t,i);try{return!r||!k.readFileSync(h.join(e.dir,i)).equals(k.readFileSync(r))}catch{return!0}})}catch{return!1}}function Xt(e){let t=(e.options||[]).filter(a=>a.frameId);if(!t.length)return;let o=F(e.frameId),i=t.filter(a=>!a.placeholder&&Io(a)),r=new Set(t.filter(a=>!i.includes(a)).map(a=>a.frameId));for(let a of r)De(a);d.frames=d.frames.filter(a=>!r.has(a.id)),e.options=e.options.filter(a=>!a.frameId||i.includes(a));let s=d.sections.find(a=>a.id===e.optionSection);i.forEach((a,l)=>{let m=d.frames.find(b=>b.id===a.frameId);m&&(delete m.building,s&&o&&(m.x=s.x+G.PAD+l*(o.w+G.GAP)))}),s&&!i.length?(d.sections=d.sections.filter(a=>a!==s),delete e.optionSection):s&&o&&(s.w=Je(o,i.length),s.slots=i.length)}async function $n(e){let t=F(e.frameId),o=(e.options||[]).filter(s=>s.files?.length&&!s.frameId);if(!t||!o.length)return!1;if(t.kind!=="folder"){if(e.optionApplied)return!1;let s=0;for(let a of o)await xt(e,t,null,a).catch(()=>null)&&s++;return s>0}let i=nt(e,t,o.length),r=0;for(let s of o){let a=we(`${t.name} ${s.id} ${s.name}`);try{await fe(t.src,a),await fe(s.dir,a)}catch{continue}let l=W({src:h.join(a,t.entry||"index.html"),name:re(`${s.id} \xB7 ${s.name}`),w:t.w,h:t.h,x:i.x+G.PAD+r++*(t.w+G.GAP),y:t.y});l.optionOf={cid:e.id,oid:s.id,from:t.id},s.frameId=l.id}return $(),r>0}var $t=/^\/__loop\/o\/([A-Za-z0-9_-]+)\/([A-F])(\/.*)?$/,xn=(e,t)=>`${X}/o/${e.id}/${t.id}`,Vt=(e,t)=>{let o=d.comments.find(i=>i.id===e)?.options?.find(i=>i.id===t);return o?.live&&o.root?o:null};function Oo(e,t,o,i){let r;try{r=decodeURIComponent(i.split("?")[0])}catch{return t.writeHead(400),t.end()}let s=h.join(o.root,r),a=h.join(o.dir,h.relative(Z,s)),l=$t.exec(new URL(e.url,"http://x").pathname),m=l?`${X}/o/${l[1]}/${l[2]}`:"",b=(I,T)=>/html|css/.test(T)&&m?I.replace(/(\s(?:href|src|action|poster)\s*=\s*["']?)\/(?!\/|__loop\/)/gi,`$1${m}/`).replace(/(url\(\s*["']?|@import\s+["'])\/(?!\/|__loop\/)/gi,`$1${m}/`):I,w=(I,T,E=200)=>{let j=/html|css/.test(T||"");t.writeHead(E,{"content-type":T||"application/octet-stream","cache-control":"no-store"}),t.end(j?b(I.toString("utf8"),T):I)};if(ie(o.root,s)&&ie(o.dir,a))try{let I=k.statSync(a).isDirectory()?h.join(a,"index.html"):a;if(k.statSync(I).isFile())return w(k.readFileSync(I),Dn[h.extname(I).toLowerCase()])}catch{}if(e.method!=="GET")return ut(e,t,o.origin,i);fetch(o.origin+i,{signal:AbortSignal.timeout(15e3),redirect:"manual"}).then(async I=>{if(I.status>=300&&I.status<400&&I.headers.get("location")){let T=I.headers.get("location");return T.startsWith(o.origin)&&(T=T.slice(o.origin.length)||"/"),t.writeHead(I.status,{location:T.startsWith("/")?m+T:T}),t.end()}w(Buffer.from(await I.arrayBuffer()),I.headers.get("content-type"),I.status)}).catch(()=>{t.headersSent||ut(e,t,o.origin,i)})}var Qe=e=>e.kind==="route"?d.proxy:e.kind==="url"?At(e.src):null,vn=e=>{if(e.kind==="route")return e.src.replace(/^\/__loop\/o\/[A-Za-z0-9_-]+\/[A-F](?=\/)/,"");let t=new URL(e.src);return t.pathname+t.search},ct=new Map;async function To(e){let t=Qe(e);if(!t)return null;if(ct.has(t))return ct.get(t);try{let o=new URL(vn(e),t),i=decodeURIComponent(o.pathname),r=i.endsWith("/")?i+"index.html":i,s=await fetch(t+o.pathname,{signal:AbortSignal.timeout(3e3)});if(!s.ok)return null;let a=Buffer.from(await s.arrayBuffer()),l=k.readdirSync(Z,{withFileTypes:!0}).filter(m=>m.isDirectory()&&!m.name.startsWith(".")&&m.name!=="node_modules").map(m=>h.join(Z,m.name));for(let m of[Z,...l]){let b=h.join(m,r);try{if(ie(m,b)&&k.statSync(b).isFile()&&k.readFileSync(b).equals(a))return ct.set(t,m),m}catch{}}}catch{}return null}function In(e,t){let o=null;try{ve.get(t.id)?.close(),ve.set(t.id,k.watch(e.dir,{recursive:!0},()=>{Date.now()-(e.madeAt||0)<1200||(t.building&&!e.touched&&(e.touched=!0,t.building="filling",$(),v.has(t.optionOf.from)&&V(t.optionOf.from,`Making option ${e.id} \xB7 ${e.name}`)),clearTimeout(o),o=setTimeout(()=>J({type:"frame-changed",frameId:t.id,live:!0}),450))}))}catch{}}async function xt(e,t,o,i){let r=Qe(t),s=await To(t);if(!r||!s)return null;e.options||=[];let a=!i;if(a){if(e.options.length>=6)throw new Error("up to 6 options");let w=String.fromCharCode(65+e.options.length);i={id:w,name:o||`Option ${w}`,dir:h.join(_,"options",e.id,w),...o?{}:{placeholder:!0}},e.options.push(i),await M.rm(i.dir,{recursive:!0,force:!0}),await M.mkdir(i.dir,{recursive:!0})}Object.assign(i,{live:!0,origin:r,root:s});let l=e.options.filter(w=>w.frameId).length,m=nt(e,t,Math.max(l+1,d.sections.find(w=>w.id===e.optionSection)?.slots||0)),b=W({route:xn(e,i)+vn(t),dup:!0,name:re(i.placeholder?i.name:`${i.id} \xB7 ${i.name}`),w:t.w,h:t.h,x:m.x+G.PAD+l*(t.w+G.GAP),y:t.y});return b.optionOf={cid:e.id,oid:i.id,from:t.id,live:!0},a?b.building=!0:i.touched=!0,i.frameId=b.id,i.madeAt=Date.now(),In(i,b),$(),i}async function jo(){for(let e of d.comments){for(let t of e.options||[]){let o=t.live&&t.frameId&&d.frames.find(i=>i.id===t.frameId);if(o){if(o.kind==="url")try{let i=new URL(o.src);Object.assign(o,{kind:"route",src:xn(e,t)+i.pathname+i.search,entry:""}),delete t.port,$()}catch{}In(t,o)}}e.status==="done"&&!e.optionChosen&&!e.optionsCleared&&!e.optionApplied&&e.options?.some(t=>t.files?.length&&!t.frameId)&&await $n(e).catch(()=>{})}}function Zt(e){let t=new Set((e.options||[]).map(o=>o.frameId).filter(Boolean));for(let o of t){let i=v.get(o);i&&(i.canceled=!0,i.child?.kill("SIGTERM"),v.delete(o)),De(o)}d.frames=d.frames.filter(o=>!t.has(o.id)),d.comments=d.comments.filter(o=>!t.has(o.frameId)),d.sections=d.sections.filter(o=>o.id!==e.optionSection);for(let o of e.options||[])delete o.frameId;delete e.optionSection}function oe(e,t,o){if(e.auto==="allow"&&t==="done"&&!v.get(e.frameId)?.canceled&&/^\W*nothing more to do\W*$/i.test(String(o||"").trim())){v.delete(e.frameId),d.comments=d.comments.filter(s=>s!==e),$(),H?.liveChanged(v),setTimeout(()=>ce(e.frameId),50);return}Xt(e);for(let s of d.comments)s!==e&&(s.id===e.parentId||s.frameId===e.frameId)&&s.options?.some(a=>a.frameId&&d.frames.find(l=>l.id===a.frameId)?.building)&&Xt(s);if(e.options?.length)for(let s of e.options)s.files=(()=>{try{let a=new Set;return qe(s.dir,s.dir,a),[...a]}catch{return[]}})();e.options?.length&&(e.options=e.options.filter(s=>s.files.length)),e.options?.some(s=>!s.frameId)&&t==="done"&&setTimeout(async()=>{await $n(e).catch(()=>!1)||Sn(e)},50);let i=v.get(e.frameId);v.delete(e.frameId),e.status=i?.steered?"interrupted":i?.canceled?"canceled":t,e.reply=i?.steered?"Interrupted to take your next message.":i?.canceled?"Stopped.":o,e.finishedAt=Date.now();for(let s of e.batch||[]){let a=d.comments.find(l=>l.id===s);if(a){if(delete a.inBatch,e.status==="interrupted"){a.status="queued";continue}Object.assign(a,{status:e.status,reply:(e.status==="done",e.reply),finishedAt:e.finishedAt,startedAt:e.startedAt,together:e.id})}}ue.set(e.frameId,(ue.get(e.frameId)||0)+1),setTimeout(zn,300),Ze.add(e.frameId),$(),J({type:"frame-changed",frameId:e.frameId,done:!0,commentId:e.id,status:e.status});let r=d.frames.find(s=>s.id===e.frameId);r&&H?.frameChanged(r),H?.liveChanged(v),setTimeout(()=>ce(e.frameId),50)}function Oe(){let e=d.agent.runner;return e&&pe[e]?.bin?e:Re?"claude":jt?"codex":"claude"}var q=new Map,Ao=3,_o=10*6e4;function Se(e){clearTimeout(e.idle),e.dead=!0;try{e.child.kill("SIGTERM")}catch{}q.get(e.frameId)===e&&q.delete(e.frameId)}function On(e){clearTimeout(e.idle),e.idle=setTimeout(()=>{e.turn||Se(e)},_o)}function vt(e,t=!1){let o=q.get(e.id),i=Me("claude"),r=`${i.model}|${i.effort}`;if(o&&!o.dead){if(o.turn||o.cfgKey===r)return o;!o.turns&&(!o.resuming||o.forked)&&delete e.sessionId,Se(o)}let s=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--include-partial-messages","--permission-mode",Do(),"--allowedTools",[`Read,Edit,MultiEdit,Write,Glob,Grep,TodoWrite,WebFetch,WebSearch,Bash(node ${Q} new:*),Bash(node ${Q} add-route:*),Bash(node ${Q} option:*),Bash(node ${Q} shot:*)`,..._n,...Po()].join(","),"--add-dir",_,...Co().flatMap(E=>["--add-dir",E])],a=!!(e.sessionId&&!t),l=!a&&!t?An():null;a?s.push("--resume",e.sessionId):l&&s.push("--resume",l.session,"--fork-session"),l?e.sessionCwd=l.cwd:a||delete e.sessionCwd,i.model&&s.push("--model",i.model),i.effort&&s.push("--effort",i.effort),e.kind!=="canvas"&&s.push("--append-system-prompt",wn(e));let m=e.sessionCwd&&k.existsSync(e.sessionCwd)?e.sessionCwd:e.kind==="folder"?e.src:Z,b=Te(Re,s,{cwd:m,env:process.env,stdio:["pipe","pipe","pipe"]}),w={frameId:e.id,child:b,turn:null,turns:0,resuming:a||!!l,forked:l?.session||null,idle:null,dead:!1,stderr:"",cfgKey:r};q.set(e.id,w),b.stdin.on("error",()=>{});let I="";b.stdout.on("data",E=>{I+=E;let j;for(;(j=I.indexOf(`
|
|
29
|
-
`))
|
|
30
|
-
`)}async function En(e,t,o=!1){v.set(t.id,{commentId:e.id,step:"Starting Codex\u2026",startedAt:Date.now()}),e.startedAt=Date.now(),e.status="working",$(),!o&&!e.snapshot&&(e.snapshot=await _t(t,e.id));let i=pn(t,e,Pt(t,e)),r=t.kind==="folder"?t.src:Z,{model:s,effort:a}=Me("codex"),l=["--json","-c","sandbox_workspace_write.network_access=true",...s?["-m",s]:[],...a?["-c",`model_reasoning_effort="${a}"`]:[]],m=!!(t.codexSession&&!o&&e.kind!=="create"),b=m?["exec","resume",...l,"--skip-git-repo-check","-c",'sandbox_mode="workspace-write"',"-c",`sandbox_workspace_write.writable_roots=${JSON.stringify([r,_])}`,t.codexSession,"-"]:["exec",...l,"-s","workspace-write","--skip-git-repo-check","-C",r,"--add-dir",_,"-"];s&&(e.model=s,d.agent.lastModel=s,$());let w;try{w=Te(jt,b,{cwd:r,env:process.env,stdio:["pipe","pipe","pipe"]})}catch(C){return oe(e,"error",`Couldn't start Codex: ${C.message}`)}v.get(t.id).child=w,w.stdin.on("error",()=>{}),w.stdin.end(i);let I="",T="",E=null,j=!1,R="";w.stdout.on("data",C=>{I+=C;let D;for(;(D=I.indexOf(`
|
|
31
|
-
`))>=0;){let
|
|
28
|
+
${e.reference}`:e.message}var pe="__canvas";function C(e){return e!==pe?d.frames.find(t=>t.id===e):(d.canvasFrame||={id:pe,name:"Canvas",kind:"canvas",src:Y,entry:"",w:0,h:0},d.canvasFrame)}var Ye=0,St=h.join(te.homedir(),".loop","model-windows.json"),Je=null;function et(){if(!Je)try{Je=new Set(JSON.parse(y.readFileSync(St,"utf8")))}catch{Je=new Set}return Je}function Eo(e){let t=et(),n=String(e||"").replace(/\[1m\]$/,"");if(!(!n||t.has(n))){t.add(n);try{y.mkdirSync(h.dirname(St),{recursive:!0}),y.writeFileSync(St,JSON.stringify([...t]))}catch{}}}function jn(e,t=6e5){let n=y.statSync(e),i=Math.min(n.size,t),r=y.openSync(e,"r"),s=Buffer.alloc(i);try{y.readSync(r,s,0,i,n.size-i)}finally{y.closeSync(r)}let a=s.toString("utf8");return i<n.size?a.slice(a.indexOf(`
|
|
29
|
+
`)+1):a}function An(e){let t=null,n=!1,i=0;for(let r of e.split(`
|
|
30
|
+
`)){if(r.includes('"compact_boundary"')){t&&(n=!0);continue}if(!r.includes('"usage"')||!r.includes('"assistant"'))continue;let s;try{s=JSON.parse(r)}catch{continue}let a=s.message,l=a?.usage;if(s.type!=="assistant"||s.isSidechain||!l||!a.model||a.model==="<synthetic>")continue;let m=(l.input_tokens||0)+(l.cache_creation_input_tokens||0)+(l.cache_read_input_tokens||0);m&&(t={used:m+(l.output_tokens||0),model:a.model},n=!1,i=Math.max(i,m),m>2e5&&Eo(a.model))}return t&&{...t,compacted:n,peak:i}}var qt=!1;function Do(){qt||(qt=!0,setTimeout(()=>{try{let e=h.join(te.homedir(),".claude","projects"),t=[];for(let i of y.readdirSync(e))try{for(let r of y.readdirSync(h.join(e,i)))if(r.endsWith(".jsonl")){let s=h.join(e,i,r);t.push([y.statSync(s).mtimeMs,s])}}catch{}let n=et().size;for(let[,i]of t.sort((r,s)=>s[0]-r[0]).slice(0,40))try{An(jn(i,4e5))}catch{}et().size!==n&&(ve.at=0,Nt())}catch{}},1500).unref?.())}var ve={at:0,file:null,val:null},Ke=null;function _n(){if(d.agent?.chat?.runner==="codex")return null;let e=zn();if(!e)return null;if(ve.file===e&&Date.now()-ve.at<5e3)return ve.val;Mo(e),Do();let t=null;try{let n=An(jn(e));if(n){let i=/\[1m\]/.test(n.model)||n.used>2e5||n.peak>2e5||et().has(n.model.replace(/\[1m\]$/,""));t={used:n.used,window:i?1e6:2e5,model:n.model,...n.compacted?{compacted:!0}:{}}}}catch{}return ve={at:Date.now(),file:e,val:t},t}function Mo(e){Ke!==e&&(Ke&&y.unwatchFile(Ke),Ke=e,y.watchFile(e,{interval:1e3,persistent:!1},(t,n)=>{(t.size!==n.size||t.mtimeMs!==n.mtimeMs)&&(ve.at=0,Nt())}))}var Ee=0,Re=()=>Ee>0||Date.now()-Ye<6e3;function Lo(e){let t=v.get(e.frameId),n=t&&d.comments.find(s=>s.id===t.commentId),i=e.parentId||e.id;if(e.status!=="queued"||!n||n.id!==i&&n.parentId!==i)return!1;e.steeredFrom=n.id,d.comments.splice(d.comments.indexOf(e),1);let r=d.comments.findIndex(s=>s.frameId===e.frameId&&s.status==="queued");return d.comments.splice(r<0?d.comments.length:r,0,e),t.steered=!0,t.canceled=!0,t.child?t.child.kill("SIGTERM"):ie(n,"canceled","Stopped."),x(),!0}function Pn(e){return e.kind==="folder"?e.src:Y}async function en(e){let t=new Set;try{ot(e,e,t)}catch{}return[...t]}async function lt(e,t){let n=C(e.frameId);if(!n)throw new Error("no frame");if(e.optionChosen)throw new Error("an option was already chosen");let i=Pn(n),r=h.join(_,"options",e.id,"_original"),s=new Set;for(let m of e.options||[])for(let $ of await en(m.dir))s.add($);if(!y.existsSync(r)){await D.mkdir(r,{recursive:!0});let m=[];for(let $ of s){let b=h.join(i,$);re(i,b)&&(y.existsSync(b)?(await D.mkdir(h.dirname(h.join(r,$)),{recursive:!0}),await D.copyFile(b,h.join(r,$))):m.push($))}await D.writeFile(h.join(r,".missing.json"),JSON.stringify(m))}let a=JSON.parse(await D.readFile(h.join(r,".missing.json"),"utf8").catch(()=>"[]"));for(let m of s){let $=h.join(i,m);re(i,$)&&(a.includes(m)?await D.rm($,{force:!0}):y.existsSync(h.join(r,m))&&await D.copyFile(h.join(r,m),$))}let l=t&&(e.options||[]).find(m=>m.id===t);if(t&&!l)throw new Error("no such option");if(l)for(let m of await en(l.dir)){let $=h.join(i,m);re(i,$)&&(await D.mkdir(h.dirname($),{recursive:!0}),await D.copyFile(h.join(l.dir,m),$))}e.optionApplied=l?l.id:null,x(),K({type:"frame-changed",frameId:n.id})}var it=process.env.LOOP_CHROME||["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",h.join(te.homedir(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome")].find(e=>y.existsSync(e))||$e("google-chrome")||$e("chromium")||$e("chromium-browser");function Co(e){return e.kind==="folder"||e.kind==="frozen"?`http://127.0.0.1:${X}/__loop/f/${e.id}/${encodeURIComponent(e.entry||"index.html")}`:e.kind==="route"?`http://127.0.0.1:${X}${e.src}`:e.src}var J=null;function xt(){let e=J;if(J=null,!!e){clearTimeout(e.idle);try{e.child.kill("SIGKILL")}catch{}y.rm(e.profile,{recursive:!0,force:!0},()=>{})}}async function En(){if(J)return clearTimeout((await J).idle),J;J=(async()=>{let t=y.mkdtempSync(h.join(te.tmpdir(),"loop-shot-")),n=je(it,["--headless=new","--use-angle=swiftshader","--enable-unsafe-swiftshader","--ignore-gpu-blocklist","--hide-scrollbars","--no-first-run","--no-default-browser-check","--mute-audio",`--user-data-dir=${t}`,"--remote-debugging-port=0","--window-size=1280,900","about:blank"],{stdio:"ignore"}),i={child:n,profile:t,port:null,idle:null};n.on("exit",()=>{J&&(J===e||J===i)&&(J=null,y.rm(t,{recursive:!0,force:!0},()=>{}))});for(let r=0;r<100&&!i.port;r++)try{i.port=y.readFileSync(h.join(t,"DevToolsActivePort"),"utf8").split(`
|
|
31
|
+
`)[0]}catch{await new Promise(s=>setTimeout(s,50))}if(!i.port){try{n.kill("SIGKILL")}catch{}throw new Error("Chrome did not start")}return i})();let e=J;try{let t=await e;return J===e&&(J=t),t}catch(t){throw J===e&&(J=null),t}}var Pe=new Map,tt=new Set;async function Fo(e){let t=`${e.w}x${e.h}`,n=Pe.get(e.id);if(n&&!(n instanceof Promise)&&n.size===t&&!tt.has(e.id)&&y.existsSync(n.file))return n.file;if(n instanceof Promise)return(await n).file;tt.delete(e.id);let i=me(e).then(r=>{let s=Pe.get(e.id),a={file:r,size:t};return Pe.set(e.id,a),a}).catch(r=>{throw Pe.delete(e.id),r});return Pe.set(e.id,i),(await i).file}var Ro="https://www.apple.com/105/media/us/iphone-duo/2026/9305e4b9-72d9-4c05-9381-b572adadd5e5/ar/iPhone_Duo_e-sim_Star-White_Variant.usdz",tn=null;function No(){let e=h.join(te.homedir(),".loop","duo-model"),t=h.join(e,"iPhone_Duo.usdz");return y.existsSync(t)?Promise.resolve(t):tn||=(async()=>{try{let n=await fetch(Ro,{signal:AbortSignal.timeout(9e4)});if(!n.ok)throw new Error(`apple.com answered ${n.status}`);let i=Buffer.from(await n.arrayBuffer());if(i.length<1e5||i[0]!==80||i[1]!==75)throw new Error("that was not the model");await D.mkdir(e,{recursive:!0});let r=`${t}.part`;return await D.writeFile(r,i),await D.rename(r,t),t}finally{tn=null}})()}var nn=Promise.resolve();function me(e,t,n){let i=nn.then(()=>zo(e,t,n));return nn=i.catch(()=>{}),i}async function zo(e,t,n){if(!it)throw new Error("No Chrome, Edge, Brave or Chromium found for screenshots (set LOOP_CHROME to one).");let i=globalThis.WebSocket;if(!i)throw new Error("Screenshots need Node 22 or newer");let r=h.join(_,"shots");y.mkdirSync(r,{recursive:!0});let s=h.join(r,n||`${e.id}-${Date.now()}${N(3)}.png`),a=Math.round(e.w),l=Math.round(e.h),m=await En();m.busy=(m.busy||0)+1;let $=null,b=null;try{for(let M=0;M<40&&!$;M++)try{$=await(await fetch(`http://127.0.0.1:${m.port}/json/new?about:blank`,{method:"PUT"})).json()}catch{await new Promise(W=>setTimeout(W,50))}if(!$?.webSocketDebuggerUrl)throw new Error("Chrome tab not found");b=new i($.webSocketDebuggerUrl),await new Promise((M,W)=>{b.onopen=M,b.onerror=()=>W(new Error("DevTools connection failed"))});let I=0,j=new Map,E=null;b.onmessage=M=>{let W=JSON.parse(M.data);W.id&&j.has(W.id)?(j.get(W.id)(W),j.delete(W.id)):W.method==="Page.loadEventFired"&&E?.()};let T=(M,W={})=>new Promise((U,ne)=>{let Ae=++I;j.set(Ae,U),setTimeout(()=>ne(new Error("Screenshot timed out")),3e4),b.send(JSON.stringify({id:Ae,method:M,params:W}))});await T("Page.enable"),await T("Page.bringToFront"),await T("Emulation.setDeviceMetricsOverride",{width:a,height:l,deviceScaleFactor:2,mobile:!1});let R=new Promise(M=>{E=M,setTimeout(M,12e3)});await T("Page.navigate",{url:t||Co(e)}),await R,await Promise.race([T("Runtime.evaluate",{awaitPromise:!0,expression:"(async () => { try { await document.fonts.ready; } catch {} await Promise.all([...document.images].filter(i => !i.complete).map(i => new Promise(r => { i.onload = i.onerror = r; }))); await new Promise(r => setTimeout(r, 250)); })()"}),new Promise(M=>setTimeout(M,2500))]);let L=await T("Page.captureScreenshot",{format:"png",clip:{x:0,y:0,width:a,height:l,scale:1}});if(!L.result?.data)throw new Error("Screenshot failed");return y.writeFileSync(s,Buffer.from(L.result.data,"base64")),s}catch(I){throw $||xt(),I}finally{try{b?.close()}catch{}$?.id&&fetch(`http://127.0.0.1:${m.port}/json/close/${$.id}`).catch(()=>{}),m.busy--,clearTimeout(m.idle),m.busy||(m.idle=setTimeout(()=>{J===m&&!m.busy&&xt()},4*6e4))}}function ce(e){if(v.has(e))return;let t=i=>i.frameId===e&&i.status==="queued"&&!i.inBatch&&(d.agent.mode!=="inbox"||i.background),n=d.comments.find(t);if(n){if(delete n.batch,n.kind!=="create"&&n.kind!=="build"&&e!==pe&&!C(e)?.optionOf){let i=d.comments.filter(r=>r!==n&&t(r)&&r.kind!=="create"&&r.kind!=="build"&&!vt(r.text)).slice(0,5);if(i.length&&!vt(n.text)){n.batch=i.map(r=>r.id);for(let r of i)r.inBatch=n.id,r.status="working"}}Hn(n)}}function Rt(){for(let e of d.frames)ce(e.id);ce(pe)}var Wo=new Set(["Reading the code","Editing","Writing","Working\u2026","Setting up an option"]);function Q(e,t,n){let i=v.get(e);if(!i)return;i.step=t;let r=n==null&&t&&d.comments.find(s=>s.id===i.commentId);if(r&&!/^(Writing…|Reading your comment…|Your chat picked this up|Working…)$/.test(t)){let s=r.steps||=[],a=s[s.length-1];!Wo.has(t)&&(!a||a.s!==t)&&(s.push({t:Date.now(),s:t}),s.length>60&&s.splice(0,s.length-60))}K({type:"activity",frameId:e,commentId:i.commentId,step:t,...n!=null?{partial:n}:{}}),H?.liveChanged(v)}async function Dn(e){let t=C(e.frameId);if(!(!t||t.kind!=="folder"||!e.options?.length||!X)){if(!e.origThumb&&!e.optionApplied)try{e.origThumb=`/__loop/shots/${h.basename(await me(t))}`,x()}catch{}for(let n of e.options)try{let i=await me(t,`http://127.0.0.1:${X}/__loop/optview/${e.id}/${n.id}/${encodeURIComponent(t.entry||"index.html")}`);n.thumb=`/__loop/shots/${h.basename(i)}`,x()}catch{}}}var G={GAP:60,PAD:48,TOP:72},Xe=(e,t)=>t*e.w+(t-1)*G.GAP+G.PAD*2;function vt(e){let t=String(e||""),n=/\b(\d|two|three|four|five|six|a couple of|couple of|a few|few|some|several|more|other|different)\s+(?:[\w-]+\s+){0,3}?(options?|variations?|variants?|alternatives?|versions|directions|takes|ideas|explorations?)\b/i.exec(t);if(n){let i=n[1].toLowerCase(),r={two:2,three:3,four:4,five:5,six:6,"a couple of":2,"couple of":2,"a few":3,few:3,some:2,several:3,more:2,other:2,different:2}[i]??+i;return Math.max(1,Math.min(4,r))}return/\b(options|variations|variants|alternatives|explorations)\b/i.test(t)&&/\b(give|make|create|show|try|explore|generate|come up|want|need|can (we|you)|let'?s|what about)\b/i.test(t)?2:/\b(another|a new|one more|a different|an alternative|a second)\s+(version|variation|variant|option|take|direction|design|layout)\b|\bduplicate (this|it)\b|\b(make|create) a copy\b/i.test(t)||/\b(a|an|one)\s+(?:[\w-]+\s+){0,2}?(variation|variant|alternative|option)\b/i.test(t)?1:0}function It(e,t,n=new Set){let i=a=>a.y<e.y+e.h&&a.y+a.h>e.y&&a.x+a.w/2>t.x+t.w,r=[...d.frames.filter(a=>a.id!==t.id&&!n.has(a.id)&&i(a)),...d.sections.filter(a=>!n.has(a.id)&&i(a))];if(!r.length)return;let s=e.x+e.w+G.GAP-Math.min(...r.map(a=>a.x));if(s>0)for(let a of r)a.x+=s}function rt(e,t,n){let i=d.sections.find(r=>r.id===e.optionSection);if(i){if(n>(i.slots||0)){let r=new Set([i.id,...(e.options||[]).map(s=>s.frameId)]);It({x:i.x,y:i.y,w:Xe(t,n),h:i.h},t,r),i.w=Xe(t,n),i.slots=n}}else{let r={x:t.x+t.w+G.GAP+20,y:t.y-G.TOP,w:Xe(t,n),h:t.h+G.TOP+G.PAD};It(r,t),i={id:N(6),name:`Options \xB7 ${t.name}`,...r,optionsFor:e.id,slots:n,createdAt:Date.now()},d.sections.push(i),e.optionSection=i.id}return i}function Bo(){let e=[...v.entries()].filter(([s])=>s!==pe);if(e.length!==1)return null;let[t,n]=e[0],i=C(t),r=d.comments.find(s=>s.id===n.commentId);return i&&r&&i.kind==="folder"&&!i.optionOf?{c:r,f:i}:null}function Ho(e,t,n,i){e.options||=[];let r=String.fromCharCode(65+e.options.length),s=e.options.length,a={id:r,name:i||`Option ${r}`};e.options.push(a);let l=rt(e,t,Math.max(s+1,d.sections.find($=>$.id===e.optionSection)?.slots||0)),m=z({src:n,name:se(i||`Option ${r}`),w:t.w,h:t.h,x:l.x+G.PAD+s*(t.w+G.GAP),y:t.y});return m.optionOf={cid:e.id,oid:r,from:t.id},m.building=!0,a.dir=n,a.frameId=m.id,a.madeAt=Date.now(),a.touched=!0,x(),m}async function on(e,t,n){if(e.options||=[],e.options.length>=6)throw new Error("up to 6 options");let i=String.fromCharCode(65+e.options.length),r=e.options.length,s={id:i,name:n||`Option ${i}`,placeholder:!n};e.options.push(s);let a=rt(e,t,Math.max(r+1,d.sections.find($=>$.id===e.optionSection)?.slots||0)),l=ke(`${t.name} option ${i} ${N(3)}`);await fe(t.src,l);let m=z({src:h.join(l,t.entry||"index.html"),name:se(n?`${i} \xB7 ${n}`:`Option ${i}`),w:t.w,h:t.h,x:a.x+G.PAD+r*(t.w+G.GAP),y:t.y});return m.optionOf={cid:e.id,oid:i,from:t.id},m.building=!0,s.dir=l,s.frameId=m.id,s.madeAt=Date.now(),x(),s}function Go(e){if(e.touched)return!0;let t=C(d.comments.find(n=>n.options?.includes(e))?.frameId)?.src;try{let n=new Set;return ot(e.dir,e.dir,n),[...n].some(i=>{let r=t&&h.join(t,i);try{return!r||!y.readFileSync(h.join(e.dir,i)).equals(y.readFileSync(r))}catch{return!0}})}catch{return!1}}function rn(e){let t=(e.options||[]).filter(a=>a.frameId);if(!t.length)return;let n=C(e.frameId),i=t.filter(a=>!a.placeholder&&Go(a)),r=new Set(t.filter(a=>!i.includes(a)).map(a=>a.frameId));for(let a of r)Me(a);d.frames=d.frames.filter(a=>!r.has(a.id)),e.options=e.options.filter(a=>!a.frameId||i.includes(a));let s=d.sections.find(a=>a.id===e.optionSection);i.forEach((a,l)=>{let m=d.frames.find($=>$.id===a.frameId);m&&(delete m.building,s&&n&&(m.x=s.x+G.PAD+l*(n.w+G.GAP)))}),s&&!i.length?(d.sections=d.sections.filter(a=>a!==s),delete e.optionSection):s&&n&&(s.w=Xe(n,i.length),s.slots=i.length)}async function Mn(e){let t=C(e.frameId),n=(e.options||[]).filter(s=>s.files?.length&&!s.frameId);if(!t||!n.length)return!1;if(t.kind!=="folder"){if(e.optionApplied)return!1;let s=0;for(let a of n)await Tt(e,t,null,a).catch(()=>null)&&s++;return s>0}let i=rt(e,t,n.length),r=0;for(let s of n){let a=ke(`${t.name} ${s.id} ${s.name}`);try{await fe(t.src,a),await fe(s.dir,a)}catch{continue}let l=z({src:h.join(a,t.entry||"index.html"),name:se(`${s.id} \xB7 ${s.name}`),w:t.w,h:t.h,x:i.x+G.PAD+r++*(t.w+G.GAP),y:t.y});l.optionOf={cid:e.id,oid:s.id,from:t.id},s.frameId=l.id}return x(),r>0}var Ot=/^\/__loop\/o\/([A-Za-z0-9_-]+)\/([A-F])(\/.*)?$/,Ln=(e,t)=>`${Z}/o/${e.id}/${t.id}`,sn=(e,t)=>{let n=d.comments.find(i=>i.id===e)?.options?.find(i=>i.id===t);return n?.live&&n.root?n:null};function Uo(e,t,n,i){let r;try{r=decodeURIComponent(i.split("?")[0])}catch{return t.writeHead(400),t.end()}let s=h.join(n.root,r),a=h.join(n.dir,h.relative(Y,s)),l=Ot.exec(new URL(e.url,"http://x").pathname),m=l?`${Z}/o/${l[1]}/${l[2]}`:"",$=(I,j)=>/html|css/.test(j)&&m?I.replace(/(\s(?:href|src|action|poster)\s*=\s*["']?)\/(?!\/|__loop\/)/gi,`$1${m}/`).replace(/(url\(\s*["']?|@import\s+["'])\/(?!\/|__loop\/)/gi,`$1${m}/`):I,b=(I,j,E=200)=>{let T=/html|css/.test(j||"");t.writeHead(E,{"content-type":j||"application/octet-stream","cache-control":"no-store"}),t.end(T?$(I.toString("utf8"),j):I)};if(re(n.root,s)&&re(n.dir,a))try{let I=y.statSync(a).isDirectory()?h.join(a,"index.html"):a;if(y.statSync(I).isFile())return b(y.readFileSync(I),Un[h.extname(I).toLowerCase()])}catch{}if(e.method!=="GET")return pt(e,t,n.origin,i);fetch(n.origin+i,{signal:AbortSignal.timeout(15e3),redirect:"manual"}).then(async I=>{if(I.status>=300&&I.status<400&&I.headers.get("location")){let j=I.headers.get("location");return j.startsWith(n.origin)&&(j=j.slice(n.origin.length)||"/"),t.writeHead(I.status,{location:j.startsWith("/")?m+j:j}),t.end()}b(Buffer.from(await I.arrayBuffer()),I.headers.get("content-type"),I.status)}).catch(()=>{t.headersSent||pt(e,t,n.origin,i)})}var nt=e=>e.kind==="route"?d.proxy:e.kind==="url"?Dt(e.src):null,Cn=e=>{if(e.kind==="route")return e.src.replace(/^\/__loop\/o\/[A-Za-z0-9_-]+\/[A-F](?=\/)/,"");let t=new URL(e.src);return t.pathname+t.search},ft=new Map;async function Jo(e){let t=nt(e);if(!t)return null;if(ft.has(t))return ft.get(t);try{let n=new URL(Cn(e),t),i=decodeURIComponent(n.pathname),r=i.endsWith("/")?i+"index.html":i,s=await fetch(t+n.pathname,{signal:AbortSignal.timeout(3e3)});if(!s.ok)return null;let a=Buffer.from(await s.arrayBuffer()),l=y.readdirSync(Y,{withFileTypes:!0}).filter(m=>m.isDirectory()&&!m.name.startsWith(".")&&m.name!=="node_modules").map(m=>h.join(Y,m.name));for(let m of[Y,...l]){let $=h.join(m,r);try{if(re(m,$)&&y.statSync($).isFile()&&y.readFileSync($).equals(a))return ft.set(t,m),m}catch{}}}catch{}return null}function Fn(e,t){let n=null;try{Ie.get(t.id)?.close(),Ie.set(t.id,y.watch(e.dir,{recursive:!0},()=>{Date.now()-(e.madeAt||0)<1200||(t.building&&!e.touched&&(e.touched=!0,t.building="filling",x(),v.has(t.optionOf.from)&&Q(t.optionOf.from,`Making option ${e.id} \xB7 ${e.name}`)),clearTimeout(n),n=setTimeout(()=>K({type:"frame-changed",frameId:t.id,live:!0}),450))}))}catch{}}async function Tt(e,t,n,i){let r=nt(t),s=await Jo(t);if(!r||!s)return null;e.options||=[];let a=!i;if(a){if(e.options.length>=6)throw new Error("up to 6 options");let b=String.fromCharCode(65+e.options.length);i={id:b,name:n||`Option ${b}`,dir:h.join(_,"options",e.id,b),...n?{}:{placeholder:!0}},e.options.push(i),await D.rm(i.dir,{recursive:!0,force:!0}),await D.mkdir(i.dir,{recursive:!0})}Object.assign(i,{live:!0,origin:r,root:s});let l=e.options.filter(b=>b.frameId).length,m=rt(e,t,Math.max(l+1,d.sections.find(b=>b.id===e.optionSection)?.slots||0)),$=z({route:Ln(e,i)+Cn(t),dup:!0,name:se(i.placeholder?i.name:`${i.id} \xB7 ${i.name}`),w:t.w,h:t.h,x:m.x+G.PAD+l*(t.w+G.GAP),y:t.y});return $.optionOf={cid:e.id,oid:i.id,from:t.id,live:!0},a?$.building=!0:i.touched=!0,i.frameId=$.id,i.madeAt=Date.now(),Fn(i,$),x(),i}async function Ko(){for(let e of d.comments){for(let t of e.options||[]){let n=t.live&&t.frameId&&d.frames.find(i=>i.id===t.frameId);if(n){if(n.kind==="url")try{let i=new URL(n.src);Object.assign(n,{kind:"route",src:Ln(e,t)+i.pathname+i.search,entry:""}),delete t.port,x()}catch{}Fn(t,n)}}e.status==="done"&&!e.optionChosen&&!e.optionsCleared&&!e.optionApplied&&e.options?.some(t=>t.files?.length&&!t.frameId)&&await Mn(e).catch(()=>{})}}function an(e){let t=new Set((e.options||[]).map(n=>n.frameId).filter(Boolean));for(let n of t){let i=v.get(n);i&&(i.canceled=!0,i.child?.kill("SIGTERM"),v.delete(n)),Me(n)}d.frames=d.frames.filter(n=>!t.has(n.id)),d.comments=d.comments.filter(n=>!t.has(n.frameId)),d.sections=d.sections.filter(n=>n.id!==e.optionSection);for(let n of e.options||[])delete n.frameId;delete e.optionSection}function ie(e,t,n){if(e.auto==="allow"&&t==="done"&&!v.get(e.frameId)?.canceled&&/^\W*nothing more to do\W*$/i.test(String(n||"").trim())){v.delete(e.frameId),d.comments=d.comments.filter(s=>s!==e),x(),H?.liveChanged(v),setTimeout(()=>ce(e.frameId),50);return}rn(e);for(let s of d.comments)s!==e&&(s.id===e.parentId||s.frameId===e.frameId)&&s.options?.some(a=>a.frameId&&d.frames.find(l=>l.id===a.frameId)?.building)&&rn(s);if(e.options?.length)for(let s of e.options)s.files=(()=>{try{let a=new Set;return ot(s.dir,s.dir,a),[...a]}catch{return[]}})();e.options?.length&&(e.options=e.options.filter(s=>s.files.length)),e.options?.some(s=>!s.frameId)&&t==="done"&&setTimeout(async()=>{await Mn(e).catch(()=>!1)||Dn(e)},50);let i=v.get(e.frameId);v.delete(e.frameId),e.status=i?.steered?"interrupted":i?.canceled?"canceled":t,e.reply=i?.steered?"Interrupted to take your next message.":i?.canceled?"Stopped.":n,e.finishedAt=Date.now();for(let s of e.batch||[]){let a=d.comments.find(l=>l.id===s);if(a){if(delete a.inBatch,e.status==="interrupted"){a.status="queued";continue}Object.assign(a,{status:e.status,reply:(e.status==="done",e.reply),finishedAt:e.finishedAt,startedAt:e.startedAt,together:e.id})}}he.set(e.frameId,(he.get(e.frameId)||0)+1),setTimeout(qn,300),tt.add(e.frameId),x(),K({type:"frame-changed",frameId:e.frameId,done:!0,commentId:e.id,status:e.status});let r=d.frames.find(s=>s.id===e.frameId);r&&H?.frameChanged(r),H?.liveChanged(v),setTimeout(()=>ce(e.frameId),50)}function Te(){let e=d.agent.runner;return e&&we[e]?.bin?e:Ne?"claude":Et?"codex":"claude"}var q=new Map,Yo=3,Xo=10*6e4;function Se(e){clearTimeout(e.idle),e.dead=!0;try{e.child.kill("SIGTERM")}catch{}q.get(e.frameId)===e&&q.delete(e.frameId)}function Rn(e){clearTimeout(e.idle),e.idle=setTimeout(()=>{e.turn||Se(e)},Xo)}function jt(e,t=!1){let n=q.get(e.id),i=Ce("claude"),r=`${i.model}|${i.effort}`;if(n&&!n.dead){if(n.turn||n.cfgKey===r)return n;!n.turns&&(!n.resuming||n.forked)&&delete e.sessionId,Se(n)}let s=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--include-partial-messages","--permission-mode",Qo(),"--allowedTools",[`Read,Edit,MultiEdit,Write,Glob,Grep,TodoWrite,WebFetch,WebSearch,Bash(node ${V} new:*),Bash(node ${V} add-route:*),Bash(node ${V} option:*),Bash(node ${V} shot:*)`,...Bn,...Vo()].join(","),"--add-dir",_,...qo().flatMap(E=>["--add-dir",E])],a=!!(e.sessionId&&!t),l=!a&&!t?Wn():null;a?s.push("--resume",e.sessionId):l&&s.push("--resume",l.session,"--fork-session"),l?e.sessionCwd=l.cwd:a||delete e.sessionCwd,i.model&&s.push("--model",i.model),i.effort&&s.push("--effort",i.effort),e.kind!=="canvas"&&s.push("--append-system-prompt",Tn(e));let m=e.sessionCwd&&y.existsSync(e.sessionCwd)?e.sessionCwd:e.kind==="folder"?e.src:Y,$=je(Ne,s,{cwd:m,env:process.env,stdio:["pipe","pipe","pipe"]}),b={frameId:e.id,child:$,turn:null,turns:0,resuming:a||!!l,forked:l?.session||null,idle:null,dead:!1,stderr:"",cfgKey:r};q.set(e.id,b),$.stdin.on("error",()=>{});let I="";$.stdout.on("data",E=>{I+=E;let T;for(;(T=I.indexOf(`
|
|
32
|
+
`))>=0;){let R=I.slice(0,T);if(I=I.slice(T+1),!R.trim())continue;let L;try{L=JSON.parse(R)}catch{continue}process.env.LOOP_DEBUG&&console.log(Date.now()%1e6,L.type,L.subtype||L.event?.type||"",L.event?.content_block?.type||L.event?.delta?.type||"");try{oi(b,e,L)}catch(M){console.error(M)}}}),$.stderr.on("data",E=>{b.stderr=(b.stderr+E).slice(-2e3)}),$.on("error",E=>{b.stderr+=E.message}),$.on("close",E=>{b.dead=!0,clearTimeout(b.idle),q.get(e.id)===b&&q.delete(e.id);let T=b.turn;b.turn=null;let R=b.resuming&&!b.turns;if(R&&b.forked&&b.turn&&(Nn=b.forked),!T){R&&(e.sessionId=null);return}let L=T.c,M=v.get(e.id);if(M?.commentId===L.id){if(!M.canceled&&R)return e.sessionId=null,v.delete(e.id),Hn(L,!0);M.canceled&&!M.steered&&!b.turns&&!b.resuming&&(e.sessionId=null),ie(L,"error",String(T.lastText&&M.canceled?T.lastText:b.stderr.trim()||`Agent exited with code ${E}`).slice(-400))}}),Rn(b);let j=[...q.values()].filter(E=>!E.turn&&E!==b);for(;q.size>Yo&&j.length;)Se(j.shift());return b}var Vo=()=>(d.agent.allow||[]).filter(e=>!e.startsWith("dir:")),Nn=null,Zo=6e6,cn=0;function zn(){let e=d.agent?.chat;if(!e?.session)return e?.transcript||null;if(e.transcript&&y.existsSync(e.transcript))return e.transcript;if(Date.now()-cn<1e4)return null;cn=Date.now();try{let t=h.join(te.homedir(),".claude","projects");for(let n of y.readdirSync(t)){let i=h.join(t,n,`${e.session}.jsonl`);if(y.existsSync(i)){e.transcript=i;try{let r=y.statSync(i),s=Math.min(r.size,2e5),a=y.openSync(i,"r"),l=Buffer.alloc(s);y.readSync(a,l,0,s,r.size-s),y.closeSync(a);let m=[...l.toString("utf8").matchAll(/"cwd":"((?:[^"\\]|\\.)*)"/g)];m.length&&(e.cwd=JSON.parse(`"${m[m.length-1][1]}"`))}catch{}return x(),i}}}catch{}return null}function Wn(){let e=d.agent.chat;if(zn(),d.agent.mode!=="inbox"||e?.runner!=="claude"||!e.session||!e.cwd||!e.transcript||Nn===e.session)return null;try{return!e.transcript.startsWith(h.join(te.homedir(),".claude","projects")+h.sep)||h.basename(e.transcript)!==`${e.session}.jsonl`||!y.statSync(e.cwd).isDirectory()||y.statSync(e.transcript).size>Zo?null:{session:e.session,cwd:e.cwd}}catch{return null}}var Qo=()=>{let e=d.agent.chat?.runner==="claude"?d.agent.chat.permission:null;return e==="auto"||e==="bypassPermissions"?e:"acceptEdits"},Bn=["ls","cat","head","tail","wc","pwd","echo","date","grep","rg","diff","file","stat","du","which","sort","uniq","cut","tr","basename","dirname","realpath","mkdir","cp","touch"].map(e=>`Bash(${e}:*)`),qo=()=>(d.agent.allow||[]).filter(e=>e.startsWith("dir:")).map(e=>e.slice(4)),ei=/^(cd|tail|head|grep|sort|uniq|wc|cat|echo|true|sleep|tee|xargs)$/;function ti(e){let t=String(e.tool_name||""),n=e.tool_input||{};if(t==="Bash"){let r=String(n.command||"").split(/&&|\|\||;|\|/).map(m=>m.trim()).filter(Boolean),s=r.find(m=>!ei.test(m.split(/\s+/)[0]))||r[0];if(!s)return null;let a=[];for(let m of s.split(/\s+/)){if(a.length===3||/^\d*[<>]|[<>&|$`'"*(){};]/.test(m))break;a.push(m)}if(!a.length)return null;let l=a.join(" ");return{tool:t,label:l,rule:`Bash(${l}:*)`,cmd:String(n.command).slice(0,300)}}let i=n.file_path||n.notebook_path||n.path;if(/^(Read|Edit|MultiEdit|Write|NotebookEdit|Glob|Grep)$/.test(t)&&i){let r=h.resolve(String(i)),s=/^(Glob|Grep)$/.test(t)?r:h.dirname(r);return{tool:t,label:`${/^(Read|Glob|Grep)$/.test(t)?"Read":"Edit"} files in ${s.replace(te.homedir(),"~")}`,rule:`dir:${s}`,cmd:String(i)}}return t?{tool:t,label:t.replace(/^mcp__/,"").replace(/__/g," \xB7 "),rule:t}:null}function ni(e){let t=[],n=new Set([...d.agent.allow||[],...Bn]);for(let i of e||[]){let r=ti(i);r&&!n.has(r.rule)&&!t.some(s=>s.rule===r.rule)&&t.push(r)}return t}function oi(e,t,n){n.session_id&&(t.sessionId=n.session_id);let i=e.turn;if(!i)return;let r=i.c,s=n.type==="system"&&n.model||n.type==="assistant"&&n.message?.model;if(s&&r.model!==s&&(r.model=s,d.agent.lastModel=s,x()),r.t&&r.t.first==null&&n.type==="stream_event"&&(r.t.first=Date.now()-r.createdAt),r.t&&r.t.tool==null&&n.type==="stream_event"&&n.event?.content_block?.type==="tool_use"&&(r.t.tool=Date.now()-r.createdAt),n.type==="stream_event"){let a=n.event||{};if(a.type==="message_start"&&v.get(t.id)?.step==="Reading your comment\u2026"&&Q(t.id,"Thinking\u2026"),a.type==="content_block_start"){let l=a.content_block||{};l.type==="thinking"?Q(t.id,"Thinking\u2026"):l.type==="tool_use"?(i.partial="",Q(t.id,Zt(l.name,{}))):l.type==="text"&&(i.partial="")}else a.type==="content_block_delta"&&a.delta?.type==="text_delta"&&(i.partial+=a.delta.text,i.flush||(i.flush=setTimeout(()=>{i.flush=null,e.turn===i&&Q(t.id,"Writing\u2026",i.partial.slice(-4e3))},90)))}else if(n.type==="assistant"){for(let a of n.message?.content||[])if(a.type==="tool_use")Q(t.id,Zt(a.name,a.input));else if(a.type==="text"&&a.text.trim()){i.lastText=a.text.trim();let l=r.steps||=[];l.push({t:Date.now(),s:i.lastText.slice(0,600),say:!0}),l.length>60&&l.splice(0,l.length-60),i.partial="",x()}}else if(n.type==="result"){clearTimeout(i.flush),e.turn=null,e.turns++,Rn(e);let a=n.result??i.lastText,l=r.steps?.[r.steps.length-1];l?.say&&String(a||"").trim().startsWith(l.s.slice(0,80))&&r.steps.pop();let m=!!n.is_error||(n.permission_denials||[]).some(b=>/^(Edit|MultiEdit|Write)$/.test(b.tool_name)),$=ni(n.permission_denials);if($.length?r.blocked=$:delete r.blocked,e.restart&&Se(e),v.get(t.id)?.commentId!==r.id)return;a!=null&&!m?ie(r,"done",String(a).trim().slice(0,4e3)||"Done."):ie(r,"error",String(a||e.stderr.trim()||"Something went wrong.").slice(-400))}}function ii(e){if(!Ne||Te()!=="claude"||v.has(e.id)||d.agent.mode==="inbox"&&Re())return!1;try{return jt(e),!0}catch{return!1}}async function Hn(e,t=!1){let n=C(e.frameId);if(!n)return;if(Te()==="codex")return Gn(e,n,t);if(!Ne)return v.set(n.id,{commentId:e.id,step:"",startedAt:Date.now()}),ie(e,"error",'No agent found to run this. Install Claude Code or Codex, or switch to "Your agent session" in the top-right menu.');let i={commentId:e.id,step:"Reading your comment\u2026",startedAt:e.startedAt&&t?e.startedAt:Date.now()};v.set(n.id,i),e.startedAt=i.startedAt,e.status="working",x();let r,s=!!q.get(n.id)&&!q.get(n.id).dead;try{r=jt(n,t)}catch(m){return ie(e,"error",`Couldn't start the agent: ${m.message}`)}r.warmed=s,i.child=r.child;let a=!t&&!e.snapshot?await Mt(n,e.id):e.snapshot;if(e.snapshot=a,v.get(n.id)!==i)return;if(i.canceled)return ie(e,"canceled","Stopped.");if(r.dead){try{r=jt(n,!0)}catch(m){return ie(e,"error",`Couldn't start the agent: ${m.message}`)}i.child=r.child}let l=e.kind==="create"||e.kind==="build"||n.kind==="canvas"?Ct(n,e):vn(n,e,Ft(n,e).message);r.turn={c:e,lastText:"",partial:"",flush:null},clearTimeout(r.idle),e.t={sent:Date.now()-e.createdAt,warm:!!r.warmed},r.child.stdin.write(JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:l}]}})+`
|
|
33
|
+
`)}async function Gn(e,t,n=!1){v.set(t.id,{commentId:e.id,step:"Starting Codex\u2026",startedAt:Date.now()}),e.startedAt=Date.now(),e.status="working",x(),!n&&!e.snapshot&&(e.snapshot=await Mt(t,e.id));let i=vn(t,e,Ct(t,e)),r=t.kind==="folder"?t.src:Y,{model:s,effort:a}=Ce("codex"),l=["--json","-c","sandbox_workspace_write.network_access=true",...s?["-m",s]:[],...a?["-c",`model_reasoning_effort="${a}"`]:[]],m=!!(t.codexSession&&!n&&e.kind!=="create"),$=m?["exec","resume",...l,"--skip-git-repo-check","-c",'sandbox_mode="workspace-write"',"-c",`sandbox_workspace_write.writable_roots=${JSON.stringify([r,_])}`,t.codexSession,"-"]:["exec",...l,"-s","workspace-write","--skip-git-repo-check","-C",r,"--add-dir",_,"-"];s&&(e.model=s,d.agent.lastModel=s,x());let b;try{b=je(Et,$,{cwd:r,env:process.env,stdio:["pipe","pipe","pipe"]})}catch(L){return ie(e,"error",`Couldn't start Codex: ${L.message}`)}v.get(t.id).child=b,b.stdin.on("error",()=>{}),b.stdin.end(i);let I="",j="",E=null,T=!1,R="";b.stdout.on("data",L=>{I+=L;let M;for(;(M=I.indexOf(`
|
|
34
|
+
`))>=0;){let W=I.slice(0,M);I=I.slice(M+1);let U;try{U=JSON.parse(W)}catch{continue}let ne=U.item||{};U.type==="thread.started"&&U.thread_id&&e.kind!=="create"?t.codexSession=U.thread_id:ne.type==="command_execution"&&U.type==="item.started"?Q(t.id,/\bcat |sed -n|rg |ls\b|grep /.test(ne.command||"")?"Reading the code":"Running a command"):ne.type==="file_change"?Q(t.id,`Editing ${h.basename(ne.changes?.[0]?.path||"")}`.trim()):ne.type==="agent_message"&&ne.text?.trim()?(j=ne.text.trim(),Q(t.id,"Thinking\u2026")):ne.type==="reasoning"?Q(t.id,"Thinking\u2026"):U.type==="turn.completed"?T=!0:(U.type==="turn.failed"||U.type==="error")&&(E=U.error?.message||U.message||"Codex failed")}}),b.stderr.on("data",L=>{R=(R+L).slice(-2e3)}),b.on("error",L=>{R+=L.message}),b.on("close",L=>{if(!v.get(t.id)?.canceled&&!T&&m)return t.codexSession=null,v.delete(t.id),Gn(e,t,!0);T&&!E?ie(e,"done",j.slice(0,4e3)||"Done."):ie(e,"error",String(E||R.trim()||`Codex exited with code ${L}`).slice(-400))})}function ri(){for(let e of Object.values(te.networkInterfaces()))for(let t of e||[])if(t.family==="IPv4"&&!t.internal)return t.address;return null}var X=0;function At(){let e=ri();return{lan:e?`http://${e}:${X}${Z}/?t=${d.token}`:null,public:ae?`${ae}${Z}/?t=${d.token}`:null,tunnelAvailable:!!$e("cloudflared")}}function si(){return new Promise((e,t)=>{if(ae)return e(ae);let n=$e("cloudflared");if(!n)return t(new Error("Public links need cloudflared. Install it with: brew install cloudflared"));ge=je(n,["tunnel","--no-autoupdate","--url",`http://localhost:${X}`],{stdio:["ignore","pipe","pipe"]});let i=r=>{let s=String(r).match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);s&&!ae&&(ae=s[0],x(),e(ae))};ge.stdout.on("data",i),ge.stderr.on("data",i),ge.on("close",()=>{ae=null,ge=null,x()}),setTimeout(()=>t(new Error("The tunnel took too long to start")),2e4)})}var Un={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".ico":"image/x-icon",".mp4":"video/mp4",".txt":"text/plain; charset=utf-8"};function Jn(e,t){let n=e.socket.remoteAddress||"",i=n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1",r=e.headers["x-forwarded-for"]||e.headers["cf-connecting-ip"];if(i&&!r)return/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(String(e.headers.host||""))?"owner":null;let s=/(?:^|;\s*)loop_t=([^;]+)/.exec(e.headers.cookie||"")?.[1];return t.searchParams.get("t")===d.token||s===d.token?"guest":null}function ai(e){let t=e.headers;if(t.origin){let n=null;try{n=new URL(t.origin).host}catch{}if(n!==String(t.host||""))return!0}return t["sec-fetch-site"]==="cross-site"&&t["sec-fetch-mode"]!=="navigate"}async function F(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>15e6)throw new Error("too large");t.push(r)}let i=Buffer.concat(t).toString("utf8");return i?JSON.parse(i):{}}function f(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(n))}async function de(e,t,n={}){try{if((await D.stat(t)).isDirectory())return de(e,h.join(t,"index.html"),n);e.writeHead(200,{"content-type":Un[h.extname(t).toLowerCase()]||"application/octet-stream","cache-control":"no-store",...n}),y.createReadStream(t).pipe(e)}catch{e.writeHead(404),e.end("Not found")}}var re=(e,t)=>t===e||t.startsWith(e+h.sep),Ve=hn.createServer(async(e,t)=>{let n=new URL(e.url,"http://x"),i;try{i=decodeURIComponent(n.pathname)}catch{return t.writeHead(400),t.end()}let r=Jn(e,n);if(!r)return t.writeHead(403,{"content-type":"text/plain"}),t.end("This Loop canvas is private. Ask the host for a share link.");if((i===Z||i.startsWith(Z+"/"))&&ai(e))return t.writeHead(403,{"content-type":"text/plain"}),t.end("Refused: this request came from another website.");let s=r==="owner";if(i!==Z&&!i.startsWith(Z+"/")){if(e.method==="GET"||e.method==="HEAD"){let a=null;try{a=Ot.exec(new URL(e.headers.referer).pathname)}catch{}if(a&&sn(a[1],a[2]))return t.writeHead(307,{location:`${Z}/o/${a[1]}/${a[2]}${e.url}`,"cache-control":"no-store",vary:"Referer"}),t.end()}return d.proxy?pt(e,t,d.proxy):e.headers["sec-fetch-dest"]==="iframe"?Kt(t,"No app is connected to this canvas yet","Run <code>loop scan</code> in the project, or give Loop the running app with <code>loop scan --url http://localhost:<port></code>."):i==="/"?(t.writeHead(302,{location:`${Z}/${n.search}`}),t.end()):(t.writeHead(404),t.end("Not found"))}if(i=i.slice(Z.length)||"/",i==="/"&&e.headers["sec-fetch-dest"]==="iframe")return Kt(t,"A frame can\u2019t show the canvas itself","This frame points at Loop\u2019s own address. Point it at your app instead.");try{if(i==="/"||i==="/index.html"){let o=n.searchParams.get("t")?{"set-cookie":`loop_t=${d.token}; Path=/; HttpOnly; SameSite=Lax`}:{};return de(t,h.join(at,"index.html"),o)}if(i.startsWith("/app/")){let o=h.join(at,h.normalize(i.slice(5)));return re(at,o)?de(t,o):(t.writeHead(400),t.end())}{let o=Ot.exec(n.pathname),c=o&&sn(o[1],o[2]);if(o)return c?Uo(e,t,c,(o[3]||"/")+n.search):(t.writeHead(404),t.end("This option is gone."))}let a=/^\/optview\/([A-Za-z0-9_-]+)\/([A-F])\/(.*)$/.exec(i);if(a){let o=d.comments.find(k=>k.id===a[1]),c=o&&C(o.frameId),u=o?.options?.find(k=>k.id===a[2]);if(!c||!u||c.kind!=="folder")return t.writeHead(404),t.end();let p=h.normalize(decodeURIComponent(a[3]||c.entry)),S=h.join(u.dir,p),w=h.join(c.src,p);return!re(u.dir,S)||!re(c.src,w)?(t.writeHead(400),t.end()):de(t,y.existsSync(S)?S:w)}let l=/^\/hist\/([A-Za-z0-9_-]+)\/(.*)$/.exec(i);if(l){let o=h.join(_,"history",l[1]),c=h.join(o,h.normalize(l[2]||"index.html"));return re(o,c)?de(t,c):(t.writeHead(400),t.end())}let m=/^\/poster\/([A-Za-z0-9_-]+)$/.exec(i);if(m){let o=d.frames.find(c=>c.id===m[1]);if(!o)return t.writeHead(404),t.end();try{return de(t,await Fo(o),{"cache-control":"private, max-age=3600"})}catch{return t.writeHead(404),t.end()}}let $=/^\/shots\/([\w.-]+\.png)$/.exec(i);if($)return de(t,h.join(_,"shots",$[1]));let b=/^\/attachments\/([A-Za-z0-9_-]+)\/([^/]+)$/.exec(i);if(b){let o=h.join(_,"attachments",b[1]),c=h.join(o,decodeURIComponent(b[2]));return re(o,c)?de(t,c):(t.writeHead(400),t.end())}let I=/^\/f\/([^/]+)\/(.*)$/.exec(i);if(I){let o=d.frames.find(u=>u.id===I[1]);if(!o||o.kind!=="folder"&&o.kind!=="frozen")return t.writeHead(404),t.end();let c=h.join(o.src,h.normalize(I[2]||o.entry));return re(o.src,c)?de(t,c):(t.writeHead(400),t.end())}if(i==="/api/ping")return f(t,200,{ok:!0,name:d.name,pid:process.pid});if(i==="/api/state")return f(t,200,kn(r));if(i==="/api/events"){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-store",connection:"keep-alive"});let o={res:t,role:r};qe.add(o),gt(t,$n(o));let c=setInterval(()=>t.write(`: ka
|
|
32
35
|
|
|
33
|
-
`),2e4);e.on("close",()=>{clearInterval(c),Ve.delete(n)});return}if(e.method==="POST"&&i==="/api/presence"){let n=await L(e);return J({type:"presence",id:String(n.id).slice(0,32),name:String(n.name||"Guest").slice(0,32),color:String(n.color||"#888").slice(0,16),x:+n.x,y:+n.y,leave:!!n.leave}),u(t,200,{ok:!0})}if(e.method==="POST"&&i==="/api/comments"){let n=await L(e),c=F(n.frameId);if(!c||!String(n.text||"").trim())return u(t,400,{error:"frame and text required"});let f=typeof n.id=="string"&&/^[A-Za-z0-9_-]{8}$/.test(n.id)&&!d.comments.some(g=>g.id===n.id)?n.id:N(8),p=null;typeof n.annotationPng=="string"&&n.annotationPng.startsWith("data:image/png;base64,")&&(await M.mkdir(h.join(_,"annotations"),{recursive:!0}),p=h.join(_,"annotations",`${f}.png`),await M.writeFile(p,Buffer.from(n.annotationPng.split(",")[1],"base64")));let x=[];for(let g of(Array.isArray(n.attachments)?n.attachments:[]).slice(0,6)){let O=/^data:([\w.+-]+\/[\w.+-]+)?(;[^,]*)?;base64,(.*)$/s.exec(String(g?.data||""));if(!O)continue;let P=String(g.name||"file").replace(/[^\w.\- ]+/g,"_").replace(/^\.+/,"").slice(-80)||"file",A=h.join(_,"attachments",f);await M.mkdir(A,{recursive:!0});let ne=P,ze=1;for(;x.some(Y=>Y.name===ne);)ne=`${ze++}-${P}`;await M.writeFile(h.join(A,ne),Buffer.from(O[3],"base64")),x.push({name:ne,type:O[1]||"application/octet-stream",path:h.join(A,ne),url:`/__loop/attachments/${f}/${encodeURIComponent(ne)}`})}let y=n.parentId?d.comments.find(g=>g.id===n.parentId):null,S={id:f,frameId:c.id,parentId:y?y.parentId||y.id:null,text:String(n.text).slice(0,4e3),anchor:n.anchor||y?.anchor||null,ink:Array.isArray(n.ink)?n.ink.slice(0,20):[],inkStrokes:Array.isArray(n.inkStrokes)?n.inkStrokes.map(String):[],annotation:p,author:{name:String(n.author?.name||(s?"You":"Guest")).slice(0,32),color:String(n.author?.color||"#2F5BFF").slice(0,16),guest:!s},status:s?"queued":"waiting",reply:null,createdAt:Date.now(),...x.length?{attachments:x}:{},...Bt(n.refs).length?{refs:Bt(n.refs)}:{}};d.comments.push(S);for(let g of d.strokes)S.inkStrokes.includes(g.id)&&(g.commentId=S.id);if(s&&uo(S,c),$(),s&&S.kind!=="create"&&(c.kind==="folder"||(c.kind==="route"||c.kind==="url")&&!c.optionOf)){let g=bt(S.text);for(let O=0;O<g;O++)try{if(!(c.kind==="folder"?await Yt(S,c):await xt(S,c)))break}catch{break}}return ce(c.id),u(t,200,S)}let T=/^\/api\/comments\/([^/]+)(?:\/(\w+))?$/.exec(i);if(T){let n=d.comments.find(f=>f.id===T[1]);if(!n)return u(t,404,{error:"no such comment"});let c=T[2];if(e.method==="DELETE"&&!c){if(!s&&!n.author?.guest)return u(t,403,{});let f=new Set([n.id,...d.comments.filter(x=>x.parentId===n.id).map(x=>x.id)]),p=v.get(n.frameId);return p&&f.has(p.commentId)&&(p.canceled=!0,p.child?p.child.kill("SIGTERM"):v.delete(n.frameId)),d.comments=d.comments.filter(x=>!f.has(x.id)),d.strokes=d.strokes.filter(x=>!f.has(x.commentId)),$(),u(t,200,{ok:!0})}if(!s)return u(t,403,{error:"host only"});if(c==="send")return["waiting","error","canceled"].includes(n.status)&&(n.status="queued",n.snapshot=null,n.undone=!1,n.redoSnap=null,$(),ce(n.frameId)),u(t,200,n);if(c==="background"){if(!s)return u(t,403,{});if(n.status!=="queued")return u(t,409,{error:"It already started"});n.background=!0;for(let f of d.comments)f.frameId===n.frameId&&f.status==="queued"&&!f.local&&(f.background=!0);return $(),ce(n.frameId),u(t,200,{ok:!0})}if(c==="steer")return s?yo(n)?u(t,200,{ok:!0}):u(t,409,{error:"Nothing to steer into: the run already finished"}):u(t,403,{});if(c==="cancel"){let f=v.get(n.frameId);return f?.commentId===n.id?(f.canceled=!0,f.child?f.child.kill("SIGTERM"):oe(n,"canceled","Stopped.")):n.status==="queued"&&(n.status="canceled",$()),u(t,200,{ok:!0})}if(c==="undo"){let f=F(n.frameId);if(!n.snapshot||!f||f.kind!=="folder")return u(t,400,{error:"nothing to undo"});if(v.has(f.id))return u(t,409,{error:"The agent is still working on this frame \u2014 wait for it to finish (or stop it) first."});let p=d.comments.filter(y=>y.id!==n.id&&y.frameId===n.frameId&&y.snapshot&&y.status==="done"&&!y.undone&&(y.startedAt||y.createdAt)>(n.startedAt||n.createdAt)),x=await L(e);if(p.length&&!x.force)return u(t,409,{error:"newer",newer:p.length});n.redoSnap=await He(f,`${n.id}-after`),await Ge(f,n.snapshot),n.undone=!0;for(let y of p)y.undone=!0;return $(),J({type:"frame-changed",frameId:f.id}),u(t,200,{ok:!0,reverted:1+p.length})}if(c==="redo"){let f=F(n.frameId);return!n.redoSnap||!n.undone||!f?u(t,400,{error:"nothing to redo"}):v.has(f.id)?u(t,409,{error:"The agent is still working on this frame \u2014 wait for it to finish first."}):(await Ge(f,n.redoSnap),n.undone=!1,$(),J({type:"frame-changed",frameId:f.id}),u(t,200,{ok:!0}))}if(c==="resolve")return n.resolved=!n.resolved,$(),u(t,200,n);if(c==="allow"&&e.method==="POST"){let f=await L(e),p=(f.all?n.blocked||[]:[n.blocked?.[+f.i]]).filter(P=>P&&!P.allowed);if(!p.length)return u(t,400,{error:"Nothing to allow"});let x=d.agent.allow||=[];for(let P of p)x.includes(P.rule)||x.push(P.rule),P.allowed=!0;let y=q.get(n.frameId);y&&!y.turn?Se(y):y&&(y.restart=!0);let S=d.comments.find(P=>P.id===(n.parentId||n.id)),g=p.map(P=>P.tool==="Bash"?`\`${P.label}\``:P.label.charAt(0).toLowerCase()+P.label.slice(1)),O=g.length>1?`${g.slice(0,-1).join(", ")} and ${g[g.length-1]}`:g[0];return d.comments.push({id:N(8),frameId:n.frameId,parentId:S?.id||n.id,anchor:n.anchor,ink:[],inkStrokes:[],auto:"allow",text:`Allowed ${O}. If you still need ${g.length>1?"them":"it"} to finish what was asked, use ${g.length>1?"them":"it"} now and say what changed. If the work is already complete without ${g.length>1?"them":"it"}, change nothing and reply with exactly: Nothing more to do.`,author:S?.author||{name:"You",color:"#2F5BFF"},status:"queued",reply:null,createdAt:Date.now()}),$(),ce(n.frameId),u(t,200,{ok:!0})}if(c==="note"){let f=await L(e),p=String(f.text||"").trim().slice(0,2e3);if(!p)return u(t,400,{error:"text required"});let x={id:N(8),kind:"note",frameId:n.frameId,parentId:n.parentId||n.id,text:p,anchor:n.anchor,author:{name:pe[Oe()].label,agent:!0,color:"#17171A"},model:f.model?String(f.model).slice(0,60):void 0,status:"done",createdAt:Date.now()};return d.comments.push(x),$(),J({type:"frame-changed",frameId:n.frameId}),u(t,200,x)}if(c==="step"){let f=await L(e);return V(n.frameId,String(f.text||"").slice(0,120)),u(t,200,{ok:!0})}if(c==="option"&&e.method==="POST"){let f=await L(e),p=F(n.frameId);if(!p)return u(t,404,{error:"no frame"});if(n.options=n.options||[],p.kind==="folder"){let S=String(f.name||"").trim().slice(0,60),g=n.options.find(O=>O.placeholder&&O.frameId);try{if(g){g.placeholder=!1,g.name=S||g.name;let O=d.frames.find(P=>P.id===g.frameId);O&&S&&(O.name=re(`${g.id} \xB7 ${S}`)),g.madeAt=Date.now(),$()}else g=await Yt(n,p,S||`Option ${String.fromCharCode(65+n.options.length)}`)}catch(O){return u(t,400,{error:O.message})}return u(t,200,{id:g.id,dir:g.dir,root:p.src,frame:!0})}{let S=String(f.name||"").trim().slice(0,60),g=n.options.find(P=>P.placeholder&&P.live&&P.frameId),O=g&&d.frames.find(P=>P.id===g.frameId);if(O)return g.placeholder=!1,S&&(g.name=S,O.name=re(`${g.id} \xB7 ${S}`)),g.madeAt=Date.now(),$(),u(t,200,{id:g.id,dir:g.dir,root:Z,beside:!0})}try{let S=await xt(n,p,String(f.name||"").trim().slice(0,60)||`Option ${String.fromCharCode(65+n.options.length)}`);if(S)return u(t,200,{id:S.id,dir:S.dir,root:Z,beside:!0})}catch(S){return u(t,400,{error:S.message})}if(n.options.length>=6)return u(t,400,{error:"up to 6 options"});let x=String.fromCharCode(65+n.options.length),y=h.join(_,"options",n.id,x);return await M.rm(y,{recursive:!0,force:!0}),await M.mkdir(y,{recursive:!0}),n.options.push({id:x,name:String(f.name||`Option ${x}`).slice(0,60),dir:y}),$(),u(t,200,{id:x,dir:y,root:kn(p)})}if(c==="thumbs"&&e.method==="POST")return Sn(n),u(t,200,{ok:!0});if(c==="preview"&&e.method==="POST"){if(!s)return u(t,403,{});let f=await L(e);try{await at(n,f.option||null)}catch(p){return u(t,400,{error:p.message})}return u(t,200,{ok:!0})}if(c==="clearoptions"&&e.method==="POST")return Zt(n),n.optionsCleared=!0,$(),u(t,200,{ok:!0});if(c==="choose"&&e.method==="POST"){if(!s)return u(t,403,{});let f=await L(e),p=n.options?.find(y=>y.id===f.option&&y.frameId),x=p&&d.frames.find(y=>y.id===p.frameId);if(x&&!p.live){let y=F(n.frameId);if(!y||y.kind!=="folder")return u(t,404,{error:"The original frame is gone."});if(v.has(y.id))return u(t,409,{error:"The agent is still working on the original frame. Wait for it to finish (or stop it) first."});let S=`r${N(7)}`;return await He(y,S)?((y.restores||=[]).push({id:S,at:Date.now()}),await Ge(y,x.src),n.optionChosen=p.id,ue.set(y.id,(ue.get(y.id)||0)+1),$(),J({type:"frame-changed",frameId:y.id}),u(t,200,{ok:!0})):u(t,500,{error:"Could not keep the current version, so nothing was changed."})}if(p?.live){let y=F(n.frameId),S=y&&Qe(y);if(y&&v.has(y.id))return u(t,409,{error:"The agent is still working on this screen. Wait for it to finish (or stop it) first."});try{await at(n,f.option)}catch(g){return u(t,400,{error:g.message})}n.optionChosen=f.option,Zt(n),$();for(let g of d.frames)S&&Qe(g)===S&&J({type:"frame-changed",frameId:g.id});return u(t,200,{ok:!0})}try{await at(n,f.option)}catch(y){return u(t,400,{error:y.message})}return n.optionChosen=f.option,$(),await M.rm(h.join(_,"options",n.id,"_original"),{recursive:!0,force:!0}).catch(()=>{}),u(t,200,{ok:!0})}if(c==="reply"){let f=await L(e);return v.has(n.frameId)||v.set(n.frameId,{commentId:n.id,step:"",startedAt:Date.now()}),f.model&&(n.model=String(f.model).slice(0,60),d.agent.lastModel=n.model),n.startedAt||(n.startedAt=v.get(n.frameId)?.startedAt),oe(n,f.error?"error":"done",String(f.text||"Done.").slice(0,4e3)),u(t,200,n)}}if(!s)return u(t,403,{error:"host only"});if(i==="/api/inbox"){let n=Date.now()+(o.searchParams.get("wait")?25e3:0),c=Fe(),f=!1,p=!!o.searchParams.get("wait");p&&Pe++;let x=!1,y=()=>{x||!p||(x=!0,Pe=Math.max(0,Pe-1),Be=Date.now(),Pe||setTimeout(()=>{Fe()||$(!0)},6200))};for(e.on("close",()=>{f=!0,y()}),t.on("finish",y),Be=Date.now(),c||$(!0);;){if(f)return;Be=Date.now();let S=d.comments.find(g=>g.status==="queued"&&!g.background&&!v.has(g.frameId));if(S){let g=F(S.frameId),O={commentId:S.id,step:"Your chat picked this up",startedAt:Date.now(),inbox:!0};return v.set(g.id,O),setTimeout(()=>{v.get(g.id)===O&&O.step==="Your chat picked this up"&&V(g.id,"Working\u2026")},3e3),S.status="working",$(),[S.snapshot]=await Promise.all([S.snapshot||_t(g,S.id),mo(S)]),u(t,200,{comment:{id:S.id,kind:S.kind||"comment",text:S.text,anchor:S.anchor,ink:S.ink,annotation:S.annotation,attachments:S.attachments},frame:{id:g.id,name:g.name,kind:g.kind,src:g.src,entry:g.entry,w:g.w,h:g.h},prompt:Pt(g,S)})}if(Date.now()>n)return u(t,200,{comment:null});await new Promise(g=>{let O=()=>{clearTimeout(P),mt.delete(O),g()},P=setTimeout(O,2e3);mt.add(O)})}}if(e.method==="POST"&&i==="/api/frames"){let n=await L(e);if(n.image||n.imageUrl){let c,f;try{if(n.image){let g=/^data:(image\/(?:png|jpeg|gif|webp|svg\+xml));base64,(.+)$/s.exec(String(n.image));if(!g)throw new Error("That is not an image Loop can show (PNG, JPEG, GIF, WebP or SVG).");f=g[1],c=Buffer.from(g[2],"base64")}else{let g=new URL(String(n.imageUrl));if(!/^https?:$/.test(g.protocol))throw new Error("Not a web address");let O=await fetch(g,{signal:AbortSignal.timeout(15e3),headers:{accept:"image/*"}});if(f=(O.headers.get("content-type")||"").split(";")[0].trim(),!O.ok||!/^image\/(png|jpeg|gif|webp|svg\+xml)$/.test(f))throw new Error("That address isn't an image Loop can show.");c=Buffer.from(await O.arrayBuffer())}}catch(g){return u(t,400,{error:g.message})}if(c.length>12e6)return u(t,400,{error:"That image is too big (over 12 MB)."});let p={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg"}[f],x=String(n.name||"Image").replace(/\.[a-z0-9]+$/i,"").slice(0,60)||"Image",y=we(x);k.mkdirSync(y,{recursive:!0}),k.writeFileSync(h.join(y,`image.${p}`),c),k.writeFileSync(h.join(y,"index.html"),`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="loop-image" content="image.${p}"><title>${Ie(x)}</title><style>html,body{margin:0;height:100%;background:transparent}img{display:block;width:100%;height:100%;object-fit:contain}</style></head><body><img src="image.${p}" alt="${Ie(x)}"></body></html>`);let S=W({src:y,name:re(x),w:Math.max(40,Math.round(+n.w||800)),h:Math.max(40,Math.round(+n.h||600)),x:n.x,y:n.y});return S.image=!0,S.fill="none",$(),u(t,200,S)}if(n.prompt){let c=n.name||n.prompt.split(/[.\n]/)[0].slice(0,40),f=Ht(c),p=W({src:f,name:c,w:n.w,h:n.h,x:n.x,y:n.y});return typeof n.source=="string"&&/^https?:\/\//.test(n.source)&&(p.source=n.source.slice(0,2e3)),d.comments.push({id:N(8),kind:"create",frameId:p.id,text:n.prompt,author:{name:"You",color:"#2F5BFF"},status:"queued",createdAt:Date.now()}),$(),ce(p.id),u(t,200,{...p,dir:f})}if(n.new){let c=Ht(n.name||"Untitled",!!n.blank);typeof n.html=="string"&&n.html.length<4e6&&k.writeFileSync(h.join(c,"index.html"),n.html);let f=n.x==null&&xo();if(f)return u(t,200,{...vo(f.c,f.f,c,n.name),dir:c});let p=W({...n,src:c});return n.parent&&d.frames.some(x=>x.id===n.parent&&x.id!==p.id)&&(p.parent=n.parent,$()),(n.fill==="none"||/^#[0-9a-f]{6}$/i.test(n.fill||""))&&(p.fill=n.fill.toLowerCase(),$()),u(t,200,{...p,dir:c})}return n.route!=null?u(t,200,W(n)):n.src?!/^https?:\/\//.test(n.src)&&!k.existsSync(h.resolve(Z,n.src))?u(t,400,{error:`No such file or folder: ${n.src}`}):u(t,200,W(n)):u(t,400,{error:"src, route, new or prompt required"})}let E=/^\/api\/frames\/([^/]+)\/versions(\/restore|\/duplicate)?$/.exec(i);if(E&&e.method==="POST"){let n=d.frames.find(g=>g.id===E[1]);if(!n||n.kind!=="folder")return u(t,400,{error:"Only static frames keep versions."});let c=encodeURIComponent(n.entry||"index.html");if(!E[2]){let g=[...d.comments.filter(A=>A.frameId===n.id&&A.snapshot&&!A.snapThumb&&k.existsSync(A.snapshot)),...(n.restores||[]).filter(A=>!A.thumb)].slice(-14),O=async A=>{try{let ne=await he(n,`http://127.0.0.1:${K}/__loop/hist/${A.id}/${c}`);A["frameId"in A?"snapThumb":"thumb"]=`/__loop/shots/${h.basename(ne)}`,$()}catch{}},[P]=await Promise.all([he(n).catch(()=>null),...g.map(O)]);return u(t,200,{now:P?`/__loop/shots/${h.basename(P)}`:null})}let f=await L(e),p=String(f.id||"");if(!/^[A-Za-z0-9_-]+$/.test(p))return u(t,400,{error:"no such version"});let x=d.comments.some(g=>g.id===p&&g.frameId===n.id&&g.snapshot)||(n.restores||[]).some(g=>g.id===p),y=h.join(_,"history",p);if(!x||!k.existsSync(y))return u(t,404,{error:"That version is no longer kept."});if(E[2]==="/duplicate"){let g=re(String(f.name||`${n.name} \xB7 earlier version`).slice(0,80)),O=we(g);return await fe(y,O),u(t,200,W({src:h.join(O,n.entry||"index.html"),name:g,w:n.w,h:n.h,near:n.id}))}if(v.has(n.id))return u(t,409,{error:"The agent is still working on this frame. Wait for it to finish (or stop it) first."});let S=`r${N(7)}`;return await He(n,S)?((n.restores||=[]).push({id:S,at:Date.now()}),await Ge(n,y),ue.set(n.id,(ue.get(n.id)||0)+1),$(),J({type:"frame-changed",frameId:n.id}),u(t,200,{ok:!0})):u(t,500,{error:"Could not keep the current version, so nothing was changed."})}let j=/^\/api\/frames\/([^/]+)\/(source|edit)$/.exec(i);if(j){let n=d.frames.find(p=>p.id===j[1]);if(!n||!s)return u(t,404,{error:"no such frame"});if(n.kind!=="folder")return u(t,400,{error:"Only static frames can be edited directly."});let c=h.join(n.src,n.entry||"index.html"),f;try{f=await M.readFile(c,"utf8")}catch{return u(t,404,{error:"The frame has no page to edit."})}if(j[2]==="source"&&e.method==="GET")return u(t,200,{text:f});if(j[2]==="edit"&&e.method==="POST"){if(v.has(n.id))return u(t,409,{error:"The agent is working on this frame. Try again when it is done."});let p=await L(e),x=(Array.isArray(p.edits)?p.edits:[]).map(A=>({a:A.a|0,b:A.b|0,before:String(A.before??""),text:String(A.text??"")})).sort((A,ne)=>A.a-ne.a);if(!x.length||x.length>40)return u(t,400,{error:"nothing to change"});let y=0;for(let A of x){if(A.a<y||A.b<A.a||A.b>f.length||f.slice(A.a,A.b)!==A.before)return u(t,409,{error:"The page changed since you started editing. Try again."});y=A.b}let S=Gt.get(n.id)||0,g=Date.now();if(g-S>9e4){let A=`e${N(7)}`;await He(n,A)&&(n.restores||=[]).push({id:A,at:g,what:String(p.what||"Edited by hand").slice(0,80)})}Gt.set(n.id,g);let O="",P=0;for(let A of x)O+=f.slice(P,A.a)+A.text,P=A.b;return O+=f.slice(P),await M.writeFile(c,O),$(),u(t,200,{ok:!0})}}let R=/^\/api\/frames\/([^/]+)\/warm$/.exec(i);if(R&&e.method==="POST"){let n=F(R[1]);return tt&&n?.kind!=="canvas"&&bn().catch(()=>{}),u(t,200,{warm:!!(n&&No(n))})}let C=/^\/api\/frames\/([^/]+)\/sizes$/.exec(i);if(C&&e.method==="POST"){if(!s)return u(t,403,{});let n=F(C[1]);if(!n||!["route","url","folder"].includes(n.kind)||n.image)return u(t,400,{error:"Sizes work for screens: an app page, a web page or a static page."});let c=d.sections.find(Y=>Y.sizesOf===n.id&&d.frames.some($e=>$e.sizeOf===n.id));if(c)return u(t,200,{section:c.id,frames:d.frames.filter(Y=>Y.sizeOf===n.id).map(Y=>Y.id),existing:!0});let f=et(n),p=Object.entries(ye).filter(([Y])=>Y!==f),x=60,y=48,S=72,g=p.reduce((Y,[,[$e]])=>Y+$e,0)+x*(p.length-1)+y*2,O=Math.max(...p.map(([,[,Y]])=>Y))+S+y,P={x:n.x+n.w+x+20,y:n.y-S,w:g,h:O};St(P,n);let A={id:N(6),name:`Sizes \xB7 ${n.name}`,...P,sizesOf:n.id,createdAt:Date.now()};d.sections.push(A);let ne=P.x+y,ze=[];for(let[Y,[$e,Hn]]of p){let Gn=re(`${n.name} \xB7 ${Y}`),ot={w:$e,h:Hn,x:ne,y:n.y,name:Gn},Ft=n.kind==="route"?W({route:n.src,dup:!0,...ot}):n.kind==="url"?W({src:n.src,...ot}):W({src:h.join(n.src,n.entry||"index.html"),...ot});Ft.sizeOf=n.id,ze.push(Ft.id),ne+=$e+x}return $(),u(t,200,{section:A.id,frames:ze})}let D=/^\/api\/frames\/([^/]+)\/asset$/.exec(i);if(D&&e.method==="POST"){if(!s)return u(t,403,{});let n=F(D[1]);if(!n||n.kind!=="folder")return u(t,400,{error:"Only static frames keep their own files."});let c=await L(e),f=/^data:(image\/(?:png|jpeg|gif|webp|svg\+xml));base64,(.+)$/s.exec(String(c.image||""));if(!f)return u(t,400,{error:"That is not an image Loop can use (PNG, JPEG, GIF, WebP or SVG)."});let p={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg"}[f[1]],x=hn(String(c.name||"image").replace(/\.[a-z0-9]+$/i,""))||"image",y=h.join(n.src,"assets");k.mkdirSync(y,{recursive:!0});let S=`${x}.${p}`,g=2;for(;k.existsSync(h.join(y,S));)S=`${x}-${g++}.${p}`;return k.writeFileSync(h.join(y,S),Buffer.from(f[2],"base64")),u(t,200,{path:`assets/${S}`})}let z=/^\/api\/frames\/([^/]+)\/shot$/.exec(i);if(z&&e.method==="POST"){let n=d.frames.find(p=>p.id===z[1]);if(!n||!s)return u(t,404,{error:"no such frame"});let c=await L(e),f;if(c.option){let[p,x]=String(c.option).split(":"),y=d.comments.find(g=>g.id===p);if(!y?.options?.some(g=>g.id===x))return u(t,400,{error:"no such option"});let S=d.frames.find(g=>g.id===y.options.find(O=>O.id===x)?.frameId);if(S)try{return u(t,200,{path:await he(S)})}catch(g){return u(t,500,{error:g.message})}if(n.kind!=="folder")return u(t,400,{error:"Options on app screens can't be screenshotted before they're applied. Describe them clearly instead."});f=`http://127.0.0.1:${K}/__loop/optview/${p}/${x}/${encodeURIComponent(n.entry||"index.html")}`}v.get(n.id)?.inbox&&V(n.id,"Looking at the screen");try{return u(t,200,{path:await he(n,f)})}catch(p){return u(t,500,{error:p.message})}}let U=/^\/api\/frames\/([^/]+)\/freeze$/.exec(i);if(U&&e.method==="POST"){let n=d.frames.find(S=>S.id===U[1]);if(!n)return u(t,404,{error:"no such frame"});let c=await L(e);if(typeof c.html!="string"||!c.html)return u(t,400,{error:"nothing captured"});let f=re(`${n.name.replace(/ · (frozen|draft)( \d+)?$/,"")} \xB7 ${c.editable?"draft":"frozen"}`),p=we(f);await M.mkdir(p,{recursive:!0}),await M.writeFile(h.join(p,"index.html"),c.html);let x=typeof c.from=="string"&&c.from.startsWith("/")&&!c.from.startsWith("/__loop/")?c.from.slice(0,2e3):n.kind==="frozen"?n.from:n.kind==="route"?n.src:void 0,y={id:N(6),name:f,kind:c.editable?"folder":"frozen",src:p,entry:"index.html",from:x,frozenAt:Date.now(),...c.editable?{draftOf:x||n.src}:{},w:n.w,h:n.h,keyboard:n.keyboard,...c.x!=null&&c.y!=null?{x:+c.x,y:+c.y}:pt(n.w,n.h,n.id),createdAt:Date.now()};return d.frames.push(y),c.editable&&Ee(y),$(),u(t,200,y)}let te=/^\/api\/frames\/([^/]+)\/duplicate$/.exec(i);if(te&&e.method==="POST"){let n=d.frames.find(g=>g.id===te[1]);if(!n)return u(t,404,{error:"no such frame"});let c=await L(e),f=n.kind==="route"&&typeof c.route=="string"&&c.route.startsWith("/")&&!c.route.startsWith("/__loop/")?c.route.slice(0,2e3):null,p=f&&f!==n.src,x=re(p?ao(f):`${n.name.replace(/ copy( \d+)?$/,"")} copy`),y=c.x!=null&&c.y!=null?{x:c.x,y:c.y}:{near:n.id},S;if(n.kind==="folder"||n.kind==="frozen"){let g=we(x);await fe(n.src,g),S=W({src:h.join(g,n.entry),name:x,w:n.w,h:n.h,...y}),n.kind==="frozen"&&(De(S.id),Object.assign(S,{kind:"frozen",from:n.from,frozenAt:n.frozenAt}),$())}else n.kind==="route"?S=W({route:f||n.src,name:x,w:n.w,h:n.h,dup:!0,...y}):S=W({src:n.src,name:x,w:n.w,h:n.h,...y});return u(t,200,S)}let je=/^\/api\/frames\/([^/]+)$/.exec(i);if(je){let n=d.frames.find(c=>c.id===je[1]);if(!n)return u(t,404,{});if(e.method==="PATCH"){let c=await L(e);for(let f of["x","y","w","h"])c[f]!=null&&isFinite(c[f])&&(n[f]=Math.round(+c[f]));return c.name&&(n.name=String(c.name).slice(0,80)),typeof c.keyboard=="boolean"&&(n.keyboard=c.keyboard||void 0),"fill"in c&&(n.fill=c.fill==="none"?"none":typeof c.fill=="string"&&/^#[0-9a-f]{6}$/i.test(c.fill)?c.fill.toLowerCase():void 0),"parent"in c&&(n.parent=c.parent&&c.parent!==n.id&&d.frames.some(f=>f.id===c.parent)?c.parent:void 0),$(),u(t,200,n)}if(e.method==="DELETE"){let c=v.get(n.id);return c&&(c.canceled=!0,c.child?.kill("SIGTERM"),v.delete(n.id)),d.frames=d.frames.filter(f=>f.id!==n.id),d.comments=d.comments.filter(f=>f.frameId!==n.id),De(n.id),$(),u(t,200,{ok:!0})}}if(e.method==="POST"&&i==="/api/sections"){let n=await L(e);if(![n.x,n.y,n.w,n.h].every(Number.isFinite))return u(t,400,{error:"x, y, w and h required"});let c=d.sections.length+1;for(;d.sections.some(p=>p.name===`Section ${c}`);)c++;let f={id:N(6),name:String(n.name||`Section ${c}`).slice(0,80),x:Math.round(n.x),y:Math.round(n.y),w:Math.max(120,Math.round(n.w)),h:Math.max(120,Math.round(n.h)),createdAt:Date.now()};return d.sections.push(f),$(),u(t,200,f)}let Ct=/^\/api\/sections\/([^/]+)$/.exec(i);if(Ct){let n=d.sections.find(c=>c.id===Ct[1]);if(!n)return u(t,404,{});if(e.method==="PATCH"){let c=await L(e);for(let f of["x","y","w","h"])c[f]!=null&&isFinite(c[f])&&(n[f]=Math.round(+c[f]));return c.name&&(n.name=String(c.name).slice(0,80)),$(),u(t,200,n)}if(e.method==="DELETE")return d.sections=d.sections.filter(c=>c.id!==n.id),$(),u(t,200,{ok:!0})}if(e.method==="GET"&&i==="/api/site-icon"){let n="";try{n=new URL(o.searchParams.get("u")||"").hostname}catch{}if(!n)return t.writeHead(404),t.end();let c=await io(n);return c?(t.writeHead(200,{"content-type":c.type,"cache-control":"max-age=86400"}),t.end(c.buf)):(t.writeHead(404),t.end())}if(e.method==="GET"&&i==="/api/resolve"){let n=F(o.searchParams.get("f")||"");return n?u(t,200,{frame:{id:n.id,name:n.name,kind:n.kind,where:yt(n),w:n.w,h:n.h,src:n.src,entry:n.entry},selector:o.searchParams.get("e")||null,label:o.searchParams.get("n")||null}):u(t,404,{error:"That frame is no longer on this canvas."})}if(e.method==="GET"&&i==="/api/canvas-history")return u(t,200,{items:to()});let Mt=/^\/api\/canvas-history\/(\d+)\/restore$/.exec(i);if(Mt&&e.method==="POST"){if(!s)return u(t,403,{});if(v.size)return u(t,409,{error:"An agent is working. Restore when it has finished (or stop it)."});let n;try{n=JSON.parse(k.readFileSync(h.join(ge,`${Mt[1]}.json`),"utf8"))}catch{return u(t,404,{error:"That moment is no longer kept."})}Ne(),dn("before restoring",!0);for(let c of d.frames)De(c.id);d.frames=n.state.frames,d.sections=n.state.sections,d.strokes=n.state.strokes,d.comments=n.state.comments.map(c=>["working","queued"].includes(c.status)?{...c,status:"canceled",reply:c.reply||"Stopped."}:c);for(let c of d.frames)delete c.building,Ee(c);return lt=cn(d),$(),J({type:"state"}),u(t,200,{ok:!0,frames:d.frames.length})}if(e.method==="POST"&&i==="/api/probe-url"){let n=await L(e),c;try{if(c=new URL(String(n.url)),!/^https?:$/.test(c.protocol))throw 0}catch{return u(t,400,{error:"Not a web address"})}try{let f=await fetch(c,{redirect:"follow",signal:AbortSignal.timeout(8e3),headers:{"user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15",accept:"text/html"}}),p=f.headers.get("x-frame-options")||"",x=/frame-ancestors([^;]*)/i.exec(f.headers.get("content-security-policy")||"")?.[1]?.trim()||"",y=/deny|sameorigin/i.test(p)||x&&!/(^|\s)\*(\s|$)/.test(x);return u(t,200,{embeddable:f.ok&&!y,status:f.status,blocked:y})}catch{return u(t,200,{embeddable:!1,status:0})}}if(e.method==="POST"&&i==="/api/restore"){let n=await L(e);for(let c of n.sections||[])c?.id&&!d.sections.find(f=>f.id===c.id)&&d.sections.push(c);for(let c of n.frames||[])c?.id&&!d.frames.find(f=>f.id===c.id)&&(d.frames.push(c),Ee(c));for(let c of n.strokes||[])c?.id&&!d.strokes.find(f=>f.id===c.id)&&d.strokes.push(c);for(let c of n.comments||[])c?.id&&!d.comments.find(f=>f.id===c.id)&&d.comments.push({...c,status:["working","queued"].includes(c.status)?"canceled":c.status});return $(),u(t,200,{ok:!0})}if(e.method==="POST"&&i==="/api/strokes"){let n=await L(e),c={id:N(8),points:(n.points||[]).slice(0,6e3).map(p=>Math.round(p*10)/10),color:String(n.color||"#E5484D").slice(0,16),width:+n.width||3,frameId:n.frameId||null,createdAt:Date.now()},f=c.frameId&&d.frames.find(p=>p.id===c.frameId);return f&&(c.fx=Number.isFinite(+n.fx)?+n.fx:f.x,c.fy=Number.isFinite(+n.fy)?+n.fy:f.y),d.strokes.push(c),$(),u(t,200,c)}let Lt=/^\/api\/strokes\/([^/]+)$/.exec(i);if(Lt&&e.method==="DELETE")return d.strokes=d.strokes.filter(n=>n.id!==Lt[1]),$(),u(t,200,{ok:!0});if(e.method==="POST"&&i==="/api/update")return!ee||ee.how!=="restart"?u(t,400,{error:"No update to apply here"}):ee.state==="updating"?u(t,200,{ok:!0}):v.size?(ee.state="queued",$(),u(t,200,{ok:!0,queued:!0})):(Ln(),u(t,200,{ok:!0}));if(e.method==="POST"&&i==="/api/settings"){let n=await L(e);if((n.mode==="headless"||n.mode==="inbox")&&(d.agent.mode=n.mode),n.runner&&pe[n.runner]){if(!pe[n.runner].bin)return u(t,400,{error:`${pe[n.runner].label} isn't installed on this computer`});d.agent.runner=n.runner}if(n.proxy!==void 0){if(n.proxy&&!/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(n.proxy))return u(t,400,{error:"proxy must be a local dev server origin, e.g. http://localhost:3000"});d.proxy=n.proxy||null}if(n.chat&&typeof n.chat=="object"){let c=p=>typeof p=="string"&&/^[\w.:\-\[\]]{1,60}$/.test(p)?p:null,f=p=>typeof p=="string"&&p.length<600&&h.isAbsolute(p)?p:void 0;d.agent.chat={runner:n.chat.runner==="codex"?"codex":"claude",model:c(n.chat.model),effort:c(n.chat.effort),permission:c(n.chat.permission),session:c(n.chat.session),cwd:f(n.chat.cwd),transcript:f(n.chat.transcript)}}if(n.pick&&typeof n.pick=="object"){let c=Oe(),f=Me(c),p=(d.agent.pick||={})[c]||={};if("model"in n.pick){if(n.pick.model&&!f.models.includes(n.pick.model))return u(t,400,{error:"No such model"});p.model=n.pick.model||void 0}if("effort"in n.pick){if(n.pick.effort&&!Me(c).efforts.includes(n.pick.effort))return u(t,400,{error:"No such effort level"});p.effort=n.pick.effort||void 0}}if(n.disallow){d.agent.allow=(d.agent.allow||[]).filter(c=>c!==n.disallow);for(let c of[...q.values()])c.turn?c.restart=!0:Se(c)}return n.name&&(d.name=String(n.name).slice(0,80)),n.hostName!==void 0&&(d.hostName=String(n.hostName).trim().slice(0,32)||void 0),$(),Dt(),u(t,200,{ok:!0})}if(e.method==="POST"&&i==="/api/share/public")try{return await zo(),u(t,200,It())}catch(n){return u(t,400,{error:n.message})}if(e.method==="POST"&&i==="/api/share/stop")return me?.kill(),se=null,$(),u(t,200,{ok:!0});if(e.method==="POST"&&i==="/api/share/rotate")return d.token=N(16),$(),u(t,200,It());if(i.startsWith("/api/cloud")&&!H)return u(t,404,{error:"Email sharing is not available in this version of Loop."});if(i==="/api/cloud"&&e.method==="GET")return u(t,200,await H.status());if(e.method==="POST"&&i==="/api/cloud/session"){let n=await L(e);return u(t,200,{user:await H.setSession(n)})}if(e.method==="POST"&&i==="/api/cloud/signout")return H.signOut(),u(t,200,{ok:!0});if(e.method==="POST"&&i==="/api/cloud/publish")return u(t,200,{link:await H.publish()});if(e.method==="POST"&&i==="/api/cloud/snapshot"){let n=await L(e),c=d.frames.find(p=>p.id===n.frameId);if(!c||c.kind!=="route"||typeof n.html!="string")return u(t,400,{error:"route frame and html required"});let f=await H.publishSnapshot(c,n.html);return H.schedulePush(200),u(t,200,f)}if(e.method==="POST"&&i==="/api/cloud/invite"){let n=await L(e);return u(t,200,await H.invite(n.emails||[],n.role))}if(e.method==="DELETE"&&i.startsWith("/api/cloud/members/"))return await H.removeMember(decodeURIComponent(i.slice(19))),u(t,200,{ok:!0});if(e.method==="POST"&&i==="/api/shutdown")return u(t,200,{ok:!0}),setTimeout(We,50);u(t,404,{error:"not found"})}catch(a){u(t,500,{error:a.message})}});Ke.on("upgrade",(e,t,o)=>{let i=new URL(e.url,"http://x");if(!d.proxy||i.pathname.startsWith(X)||!Cn(e,i))return t.destroy();let r=new URL(d.proxy),s=sn.connect(+(r.port||80),r.hostname,()=>{let a=`${e.method} ${e.url} HTTP/1.1\r
|
|
34
|
-
`;for(let l=0;l<e.rawHeaders.length;l+=2){let m=e.rawHeaders[l]
|
|
36
|
+
`),2e4);e.on("close",()=>{clearInterval(c),qe.delete(o)});return}if(e.method==="POST"&&i==="/api/presence"){let o=await F(e);return K({type:"presence",id:String(o.id).slice(0,32),name:String(o.name||"Guest").slice(0,32),color:String(o.color||"#888").slice(0,16),x:+o.x,y:+o.y,leave:!!o.leave}),f(t,200,{ok:!0})}let j=/^\/api\/frames\/([^/]+)\/build-target$/.exec(i);if(j&&e.method==="GET"){let o=C(j[1]);if(!o)return f(t,404,{error:"no such frame"});let c=In(o);return f(t,200,{mode:c.mode,route:c.route||null})}if(e.method==="POST"&&i==="/api/comments"){let o=await F(e),c=C(o.frameId);if(!c||!String(o.text||"").trim())return f(t,400,{error:"frame and text required"});let u=typeof o.id=="string"&&/^[A-Za-z0-9_-]{8}$/.test(o.id)&&!d.comments.some(g=>g.id===o.id)?o.id:N(8),p=null;typeof o.annotationPng=="string"&&o.annotationPng.startsWith("data:image/png;base64,")&&(await D.mkdir(h.join(_,"annotations"),{recursive:!0}),p=h.join(_,"annotations",`${u}.png`),await D.writeFile(p,Buffer.from(o.annotationPng.split(",")[1],"base64")));let S=[];for(let g of(Array.isArray(o.attachments)?o.attachments:[]).slice(0,6)){let O=/^data:([\w.+-]+\/[\w.+-]+)?(;[^,]*)?;base64,(.*)$/s.exec(String(g?.data||""));if(!O)continue;let P=String(g.name||"file").replace(/[^\w.\- ]+/g,"_").replace(/^\.+/,"").slice(-80)||"file",A=h.join(_,"attachments",u);await D.mkdir(A,{recursive:!0});let oe=P,He=1;for(;S.some(B=>B.name===oe);)oe=`${He++}-${P}`;await D.writeFile(h.join(A,oe),Buffer.from(O[3],"base64")),S.push({name:oe,type:O[1]||"application/octet-stream",path:h.join(A,oe),url:`/__loop/attachments/${u}/${encodeURIComponent(oe)}`})}let w=o.parentId?d.comments.find(g=>g.id===o.parentId):null,k={id:u,frameId:c.id,parentId:w?w.parentId||w.id:null,text:String(o.text).slice(0,4e3),anchor:o.anchor||w?.anchor||null,ink:Array.isArray(o.ink)?o.ink.slice(0,20):[],inkStrokes:Array.isArray(o.inkStrokes)?o.inkStrokes.map(String):[],annotation:p,author:{name:String(o.author?.name||(s?"You":"Guest")).slice(0,32),color:String(o.author?.color||"#2F5BFF").slice(0,16),guest:!s},status:s?"queued":"waiting",reply:null,createdAt:Date.now(),...S.length?{attachments:S}:{},...Qt(o.refs).length?{refs:Qt(o.refs)}:{}};if(s&&o.kind==="build"){let g=[...new Set([c.id,...Array.isArray(o.build?.frames)?o.build.frames:[]])].filter(O=>C(O)&&O!==pe).slice(0,12);k.kind="build",k.build={mode:["replace","add","wrap"].includes(o.build?.mode)?o.build.mode:"add",commit:!!o.build?.commit,frames:g}}d.comments.push(k);for(let g of d.strokes)k.inkStrokes.includes(g.id)&&(g.commentId=k.id);if(s&&Oo(k,c),x(),s&&k.kind!=="create"&&(c.kind==="folder"||(c.kind==="route"||c.kind==="url")&&!c.optionOf)){let g=vt(k.text);for(let O=0;O<g;O++)try{if(!(c.kind==="folder"?await on(k,c):await Tt(k,c)))break}catch{break}}return ce(c.id),f(t,200,k)}let E=/^\/api\/comments\/([^/]+)(?:\/(\w+))?$/.exec(i);if(E){let o=d.comments.find(u=>u.id===E[1]);if(!o)return f(t,404,{error:"no such comment"});let c=E[2];if(e.method==="DELETE"&&!c){if(!s&&!o.author?.guest)return f(t,403,{});let u=new Set([o.id,...d.comments.filter(S=>S.parentId===o.id).map(S=>S.id)]),p=v.get(o.frameId);return p&&u.has(p.commentId)&&(p.canceled=!0,p.child?p.child.kill("SIGTERM"):v.delete(o.frameId)),d.comments=d.comments.filter(S=>!u.has(S.id)),d.strokes=d.strokes.filter(S=>!u.has(S.commentId)),x(),f(t,200,{ok:!0})}if(!s)return f(t,403,{error:"host only"});if(c==="send")return["waiting","error","canceled"].includes(o.status)&&(o.status="queued",o.snapshot=null,o.undone=!1,o.redoSnap=null,x(),ce(o.frameId)),f(t,200,o);if(c==="background"){if(!s)return f(t,403,{});if(o.status!=="queued")return f(t,409,{error:"It already started"});o.background=!0;for(let u of d.comments)u.frameId===o.frameId&&u.status==="queued"&&!u.local&&(u.background=!0);return x(),ce(o.frameId),f(t,200,{ok:!0})}if(c==="steer")return s?Lo(o)?f(t,200,{ok:!0}):f(t,409,{error:"Nothing to steer into: the run already finished"}):f(t,403,{});if(c==="cancel"){let u=v.get(o.frameId);return u?.commentId===o.id?(u.canceled=!0,u.child?u.child.kill("SIGTERM"):ie(o,"canceled","Stopped.")):o.status==="queued"&&(o.status="canceled",x()),f(t,200,{ok:!0})}if(c==="undo"){let u=C(o.frameId);if(!o.snapshot||!u||u.kind!=="folder")return f(t,400,{error:"nothing to undo"});if(v.has(u.id))return f(t,409,{error:"The agent is still working on this frame \u2014 wait for it to finish (or stop it) first."});let p=d.comments.filter(w=>w.id!==o.id&&w.frameId===o.frameId&&w.snapshot&&w.status==="done"&&!w.undone&&(w.startedAt||w.createdAt)>(o.startedAt||o.createdAt)),S=await F(e);if(p.length&&!S.force)return f(t,409,{error:"newer",newer:p.length});o.redoSnap=await Ge(u,`${o.id}-after`),await Ue(u,o.snapshot),o.undone=!0;for(let w of p)w.undone=!0;return x(),K({type:"frame-changed",frameId:u.id}),f(t,200,{ok:!0,reverted:1+p.length})}if(c==="redo"){let u=C(o.frameId);return!o.redoSnap||!o.undone||!u?f(t,400,{error:"nothing to redo"}):v.has(u.id)?f(t,409,{error:"The agent is still working on this frame \u2014 wait for it to finish first."}):(await Ue(u,o.redoSnap),o.undone=!1,x(),K({type:"frame-changed",frameId:u.id}),f(t,200,{ok:!0}))}if(c==="resolve")return o.resolved=!o.resolved,x(),f(t,200,o);if(c==="allow"&&e.method==="POST"){let u=await F(e),p=(u.all?o.blocked||[]:[o.blocked?.[+u.i]]).filter(P=>P&&!P.allowed);if(!p.length)return f(t,400,{error:"Nothing to allow"});let S=d.agent.allow||=[];for(let P of p)S.includes(P.rule)||S.push(P.rule),P.allowed=!0;let w=q.get(o.frameId);w&&!w.turn?Se(w):w&&(w.restart=!0);let k=d.comments.find(P=>P.id===(o.parentId||o.id)),g=p.map(P=>P.tool==="Bash"?`\`${P.label}\``:P.label.charAt(0).toLowerCase()+P.label.slice(1)),O=g.length>1?`${g.slice(0,-1).join(", ")} and ${g[g.length-1]}`:g[0];return d.comments.push({id:N(8),frameId:o.frameId,parentId:k?.id||o.id,anchor:o.anchor,ink:[],inkStrokes:[],auto:"allow",text:`Allowed ${O}. If you still need ${g.length>1?"them":"it"} to finish what was asked, use ${g.length>1?"them":"it"} now and say what changed. If the work is already complete without ${g.length>1?"them":"it"}, change nothing and reply with exactly: Nothing more to do.`,author:k?.author||{name:"You",color:"#2F5BFF"},status:"queued",reply:null,createdAt:Date.now()}),x(),ce(o.frameId),f(t,200,{ok:!0})}if(c==="note"){let u=await F(e),p=String(u.text||"").trim().slice(0,2e3);if(!p)return f(t,400,{error:"text required"});let S={id:N(8),kind:"note",frameId:o.frameId,parentId:o.parentId||o.id,text:p,anchor:o.anchor,author:{name:we[Te()].label,agent:!0,color:"#17171A"},model:u.model?String(u.model).slice(0,60):void 0,status:"done",createdAt:Date.now()};return d.comments.push(S),x(),K({type:"frame-changed",frameId:o.frameId}),f(t,200,S)}if(c==="step"){let u=await F(e);return Q(o.frameId,String(u.text||"").slice(0,120)),f(t,200,{ok:!0})}if(c==="option"&&e.method==="POST"){let u=await F(e),p=C(o.frameId);if(!p)return f(t,404,{error:"no frame"});if(o.options=o.options||[],p.kind==="folder"){let k=String(u.name||"").trim().slice(0,60),g=o.options.find(O=>O.placeholder&&O.frameId);try{if(g){g.placeholder=!1,g.name=k||g.name;let O=d.frames.find(P=>P.id===g.frameId);O&&k&&(O.name=se(`${g.id} \xB7 ${k}`)),g.madeAt=Date.now(),x()}else g=await on(o,p,k||`Option ${String.fromCharCode(65+o.options.length)}`)}catch(O){return f(t,400,{error:O.message})}return f(t,200,{id:g.id,dir:g.dir,root:p.src,frame:!0})}{let k=String(u.name||"").trim().slice(0,60),g=o.options.find(P=>P.placeholder&&P.live&&P.frameId),O=g&&d.frames.find(P=>P.id===g.frameId);if(O)return g.placeholder=!1,k&&(g.name=k,O.name=se(`${g.id} \xB7 ${k}`)),g.madeAt=Date.now(),x(),f(t,200,{id:g.id,dir:g.dir,root:Y,beside:!0})}try{let k=await Tt(o,p,String(u.name||"").trim().slice(0,60)||`Option ${String.fromCharCode(65+o.options.length)}`);if(k)return f(t,200,{id:k.id,dir:k.dir,root:Y,beside:!0})}catch(k){return f(t,400,{error:k.message})}if(o.options.length>=6)return f(t,400,{error:"up to 6 options"});let S=String.fromCharCode(65+o.options.length),w=h.join(_,"options",o.id,S);return await D.rm(w,{recursive:!0,force:!0}),await D.mkdir(w,{recursive:!0}),o.options.push({id:S,name:String(u.name||`Option ${S}`).slice(0,60),dir:w}),x(),f(t,200,{id:S,dir:w,root:Pn(p)})}if(c==="thumbs"&&e.method==="POST")return Dn(o),f(t,200,{ok:!0});if(c==="preview"&&e.method==="POST"){if(!s)return f(t,403,{});let u=await F(e);try{await lt(o,u.option||null)}catch(p){return f(t,400,{error:p.message})}return f(t,200,{ok:!0})}if(c==="clearoptions"&&e.method==="POST")return an(o),o.optionsCleared=!0,x(),f(t,200,{ok:!0});if(c==="choose"&&e.method==="POST"){if(!s)return f(t,403,{});let u=await F(e),p=o.options?.find(w=>w.id===u.option&&w.frameId),S=p&&d.frames.find(w=>w.id===p.frameId);if(S&&!p.live){let w=C(o.frameId);if(!w||w.kind!=="folder")return f(t,404,{error:"The original frame is gone."});if(v.has(w.id))return f(t,409,{error:"The agent is still working on the original frame. Wait for it to finish (or stop it) first."});let k=`r${N(7)}`;return await Ge(w,k)?((w.restores||=[]).push({id:k,at:Date.now()}),await Ue(w,S.src),o.optionChosen=p.id,he.set(w.id,(he.get(w.id)||0)+1),x(),K({type:"frame-changed",frameId:w.id}),f(t,200,{ok:!0})):f(t,500,{error:"Could not keep the current version, so nothing was changed."})}if(p?.live){let w=C(o.frameId),k=w&&nt(w);if(w&&v.has(w.id))return f(t,409,{error:"The agent is still working on this screen. Wait for it to finish (or stop it) first."});try{await lt(o,u.option)}catch(g){return f(t,400,{error:g.message})}o.optionChosen=u.option,an(o),x();for(let g of d.frames)k&&nt(g)===k&&K({type:"frame-changed",frameId:g.id});return f(t,200,{ok:!0})}try{await lt(o,u.option)}catch(w){return f(t,400,{error:w.message})}return o.optionChosen=u.option,x(),await D.rm(h.join(_,"options",o.id,"_original"),{recursive:!0,force:!0}).catch(()=>{}),f(t,200,{ok:!0})}if(c==="reply"){let u=await F(e);return v.has(o.frameId)||v.set(o.frameId,{commentId:o.id,step:"",startedAt:Date.now()}),u.model&&(o.model=String(u.model).slice(0,60),d.agent.lastModel=o.model),o.startedAt||(o.startedAt=v.get(o.frameId)?.startedAt),ie(o,u.error?"error":"done",String(u.text||"Done.").slice(0,4e3)),f(t,200,o)}}if(!s)return f(t,403,{error:"host only"});if(i==="/api/inbox"){let o=Date.now()+(n.searchParams.get("wait")?25e3:0),c=Re(),u=!1,p=!!n.searchParams.get("wait");p&&Ee++;let S=!1,w=()=>{S||!p||(S=!0,Ee=Math.max(0,Ee-1),Ye=Date.now(),Ee||setTimeout(()=>{Re()||x(!0)},6200))};for(e.on("close",()=>{u=!0,w()}),t.on("finish",w),Ye=Date.now(),c||x(!0);;){if(u)return;Ye=Date.now();let k=d.comments.find(g=>g.status==="queued"&&!g.background&&!v.has(g.frameId));if(k){let g=C(k.frameId),O={commentId:k.id,step:"Your chat picked this up",startedAt:Date.now(),inbox:!0};return v.set(g.id,O),setTimeout(()=>{v.get(g.id)===O&&O.step==="Your chat picked this up"&&Q(g.id,"Working\u2026")},3e3),k.status="working",x(),[k.snapshot]=await Promise.all([k.snapshot||Mt(g,k.id),jo(k)]),f(t,200,{comment:{id:k.id,kind:k.kind||"comment",text:k.text,anchor:k.anchor,ink:k.ink,annotation:k.annotation,attachments:k.attachments},frame:{id:g.id,name:g.name,kind:g.kind,src:g.src,entry:g.entry,w:g.w,h:g.h},prompt:Ct(g,k)})}if(Date.now()>o)return f(t,200,{comment:null});await new Promise(g=>{let O=()=>{clearTimeout(P),wt.delete(O),g()},P=setTimeout(O,2e3);wt.add(O)})}}if(e.method==="POST"&&i==="/api/frames"){let o=await F(e);if(o.image||o.imageUrl){let c,u;try{if(o.image){let g=/^data:(image\/(?:png|jpeg|gif|webp|svg\+xml));base64,(.+)$/s.exec(String(o.image));if(!g)throw new Error("That is not an image Loop can show (PNG, JPEG, GIF, WebP or SVG).");u=g[1],c=Buffer.from(g[2],"base64")}else{let g=new URL(String(o.imageUrl));if(!/^https?:$/.test(g.protocol))throw new Error("Not a web address");let O=await fetch(g,{signal:AbortSignal.timeout(15e3),headers:{accept:"image/*"}});if(u=(O.headers.get("content-type")||"").split(";")[0].trim(),!O.ok||!/^image\/(png|jpeg|gif|webp|svg\+xml)$/.test(u))throw new Error("That address isn't an image Loop can show.");c=Buffer.from(await O.arrayBuffer())}}catch(g){return f(t,400,{error:g.message})}if(c.length>12e6)return f(t,400,{error:"That image is too big (over 12 MB)."});let p={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg"}[u],S=String(o.name||"Image").replace(/\.[a-z0-9]+$/i,"").slice(0,60)||"Image",w=ke(S);y.mkdirSync(w,{recursive:!0}),y.writeFileSync(h.join(w,`image.${p}`),c),y.writeFileSync(h.join(w,"index.html"),`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="loop-image" content="image.${p}"><title>${Oe(S)}</title><style>html,body{margin:0;height:100%;background:transparent}img{display:block;width:100%;height:100%;object-fit:contain}</style></head><body><img src="image.${p}" alt="${Oe(S)}"></body></html>`);let k=z({src:w,name:se(S),w:Math.max(40,Math.round(+o.w||800)),h:Math.max(40,Math.round(+o.h||600)),x:o.x,y:o.y});return k.image=!0,k.fill="none",x(),f(t,200,k)}if(o.prompt){let c=o.name||o.prompt.split(/[.\n]/)[0].slice(0,40),u=Xt(c),p=z({src:u,name:c,w:o.w,h:o.h,x:o.x,y:o.y});return typeof o.source=="string"&&/^https?:\/\//.test(o.source)&&(p.source=o.source.slice(0,2e3)),o.shapeless&&(p.shapeless=!0),d.comments.push({id:N(8),kind:"create",frameId:p.id,text:o.prompt,author:{name:"You",color:"#2F5BFF"},status:"queued",createdAt:Date.now()}),x(),ce(p.id),f(t,200,{...p,dir:u})}if(o.new){let c=Xt(o.name||"Untitled",!!o.blank);typeof o.html=="string"&&o.html.length<4e6&&y.writeFileSync(h.join(c,"index.html"),o.html);let u=o.x==null&&Bo();if(u)return f(t,200,{...Ho(u.c,u.f,c,o.name),dir:c});let p=z({...o,src:c});return o.parent&&d.frames.some(S=>S.id===o.parent&&S.id!==p.id)&&(p.parent=o.parent,x()),(o.fill==="none"||/^#[0-9a-f]{6}$/i.test(o.fill||""))&&(p.fill=o.fill.toLowerCase(),x()),f(t,200,{...p,dir:c})}return o.route!=null?f(t,200,z(o)):o.src?!/^https?:\/\//.test(o.src)&&!y.existsSync(h.resolve(Y,o.src))?f(t,400,{error:`No such file or folder: ${o.src}`}):f(t,200,z(o)):f(t,400,{error:"src, route, new or prompt required"})}let T=/^\/api\/frames\/([^/]+)\/versions(\/restore|\/duplicate)?$/.exec(i);if(T&&e.method==="POST"){let o=d.frames.find(g=>g.id===T[1]);if(!o||o.kind!=="folder")return f(t,400,{error:"Only static frames keep versions."});let c=encodeURIComponent(o.entry||"index.html");if(!T[2]){let g=[...d.comments.filter(A=>A.frameId===o.id&&A.snapshot&&!A.snapThumb&&y.existsSync(A.snapshot)),...(o.restores||[]).filter(A=>!A.thumb)].slice(-14),O=async A=>{try{let oe=await me(o,`http://127.0.0.1:${X}/__loop/hist/${A.id}/${c}`);A["frameId"in A?"snapThumb":"thumb"]=`/__loop/shots/${h.basename(oe)}`,x()}catch{}},[P]=await Promise.all([me(o).catch(()=>null),...g.map(O)]);return f(t,200,{now:P?`/__loop/shots/${h.basename(P)}`:null})}let u=await F(e),p=String(u.id||"");if(!/^[A-Za-z0-9_-]+$/.test(p))return f(t,400,{error:"no such version"});let S=d.comments.some(g=>g.id===p&&g.frameId===o.id&&g.snapshot)||(o.restores||[]).some(g=>g.id===p),w=h.join(_,"history",p);if(!S||!y.existsSync(w))return f(t,404,{error:"That version is no longer kept."});if(T[2]==="/duplicate"){let g=se(String(u.name||`${o.name} \xB7 earlier version`).slice(0,80)),O=ke(g);return await fe(w,O),f(t,200,z({src:h.join(O,o.entry||"index.html"),name:g,w:o.w,h:o.h,near:o.id}))}if(v.has(o.id))return f(t,409,{error:"The agent is still working on this frame. Wait for it to finish (or stop it) first."});let k=`r${N(7)}`;return await Ge(o,k)?((o.restores||=[]).push({id:k,at:Date.now()}),await Ue(o,w),he.set(o.id,(he.get(o.id)||0)+1),x(),K({type:"frame-changed",frameId:o.id}),f(t,200,{ok:!0})):f(t,500,{error:"Could not keep the current version, so nothing was changed."})}let R=/^\/api\/frames\/([^/]+)\/(source|edit)$/.exec(i);if(R){let o=d.frames.find(p=>p.id===R[1]);if(!o||!s)return f(t,404,{error:"no such frame"});if(o.kind!=="folder")return f(t,400,{error:"Only static frames can be edited directly."});let c=h.join(o.src,o.entry||"index.html"),u;try{u=await D.readFile(c,"utf8")}catch{return f(t,404,{error:"The frame has no page to edit."})}if(R[2]==="source"&&e.method==="GET")return f(t,200,{text:u});if(R[2]==="edit"&&e.method==="POST"){if(v.has(o.id))return f(t,409,{error:"The agent is working on this frame. Try again when it is done."});let p=await F(e),S=(Array.isArray(p.edits)?p.edits:[]).map(A=>({a:A.a|0,b:A.b|0,before:String(A.before??""),text:String(A.text??"")})).sort((A,oe)=>A.a-oe.a);if(!S.length||S.length>40)return f(t,400,{error:"nothing to change"});let w=0;for(let A of S){if(A.a<w||A.b<A.a||A.b>u.length||u.slice(A.a,A.b)!==A.before)return f(t,409,{error:"The page changed since you started editing. Try again."});w=A.b}let k=Vt.get(o.id)||0,g=Date.now();if(g-k>9e4){let A=`e${N(7)}`;await Ge(o,A)&&(o.restores||=[]).push({id:A,at:g,what:String(p.what||"Edited by hand").slice(0,80)})}Vt.set(o.id,g);let O="",P=0;for(let A of S)O+=u.slice(P,A.a)+A.text,P=A.b;return O+=u.slice(P),await D.writeFile(c,O),x(),f(t,200,{ok:!0})}}let L=/^\/api\/frames\/([^/]+)\/warm$/.exec(i);if(L&&e.method==="POST"){let o=C(L[1]);return it&&o?.kind!=="canvas"&&En().catch(()=>{}),f(t,200,{warm:!!(o&&ii(o))})}let M=/^\/api\/frames\/([^/]+)\/sizes$/.exec(i);if(M&&e.method==="POST"){if(!s)return f(t,403,{});let o=C(M[1]);if(!o||!["route","url","folder"].includes(o.kind)||o.image)return f(t,400,{error:"Sizes work for screens: an app page, a web page or a static page."});let c=d.sections.find(B=>B.sizesOf===o.id&&d.frames.some(ue=>ue.sizeOf===o.id));if(c)return f(t,200,{section:c.id,frames:d.frames.filter(B=>B.sizeOf===o.id).map(B=>B.id),existing:!0});let u=We(o),p=[...Object.entries(be).filter(([B])=>B!==u),["iPhone Duo",[466,678]],["iPhone Duo open",[951,669]]].filter(([,[B,ue]])=>B!==o.w||ue!==o.h),S=60,w=48,k=72,g=p.reduce((B,[,[ue]])=>B+ue,0)+S*(p.length-1)+w*2,O=Math.max(...p.map(([,[,B]])=>B))+k+w,P={x:o.x+o.w+S+20,y:o.y-k,w:g,h:O};It(P,o);let A={id:N(6),name:`Sizes \xB7 ${o.name}`,...P,sizesOf:o.id,createdAt:Date.now()};d.sections.push(A);let oe=P.x+w,He=[];for(let[B,[ue,eo]]of p){let to=se(`${o.name} \xB7 ${B}`),st={w:ue,h:eo,x:oe,y:o.y,name:to},Gt=o.kind==="route"?z({route:o.src,dup:!0,...st}):o.kind==="url"?z({src:o.src,...st}):z({src:h.join(o.src,o.entry||"index.html"),...st});Gt.sizeOf=o.id,He.push(Gt.id),oe+=ue+S}return x(),f(t,200,{section:A.id,frames:He})}let W=/^\/api\/frames\/([^/]+)\/asset$/.exec(i);if(W&&e.method==="POST"){if(!s)return f(t,403,{});let o=C(W[1]);if(!o||o.kind!=="folder")return f(t,400,{error:"Only static frames keep their own files."});let c=await F(e),u=/^data:(image\/(?:png|jpeg|gif|webp|svg\+xml));base64,(.+)$/s.exec(String(c.image||""));if(!u)return f(t,400,{error:"That is not an image Loop can use (PNG, JPEG, GIF, WebP or SVG)."});let p={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg"}[u[1]],S=Sn(String(c.name||"image").replace(/\.[a-z0-9]+$/i,""))||"image",w=h.join(o.src,"assets");y.mkdirSync(w,{recursive:!0});let k=`${S}.${p}`,g=2;for(;y.existsSync(h.join(w,k));)k=`${S}-${g++}.${p}`;return y.writeFileSync(h.join(w,k),Buffer.from(u[2],"base64")),f(t,200,{path:`assets/${k}`})}let U=/^\/api\/frames\/([^/]+)\/shot$/.exec(i);if(U&&e.method==="POST"){let o=d.frames.find(S=>S.id===U[1]);if(!o||!s)return f(t,404,{error:"no such frame"});let c=await F(e),u;if(c.option){let[S,w]=String(c.option).split(":"),k=d.comments.find(O=>O.id===S);if(!k?.options?.some(O=>O.id===w))return f(t,400,{error:"no such option"});let g=d.frames.find(O=>O.id===k.options.find(P=>P.id===w)?.frameId);if(g)try{return f(t,200,{path:await me(g)})}catch(O){return f(t,500,{error:O.message})}if(o.kind!=="folder")return f(t,400,{error:"Options on app screens can't be screenshotted before they're applied. Describe them clearly instead."});u=`http://127.0.0.1:${X}/__loop/optview/${S}/${w}/${encodeURIComponent(o.entry||"index.html")}`}v.get(o.id)?.inbox&&Q(o.id,"Looking at the screen");let p=+c.w>0&&+c.h>0?{...o,w:Math.min(3e3,Math.round(+c.w)),h:Math.min(3e3,Math.round(+c.h))}:o;try{return f(t,200,{path:await me(p,u)})}catch(S){return f(t,500,{error:S.message})}}let ne=/^\/api\/frames\/([^/]+)\/freeze$/.exec(i);if(ne&&e.method==="POST"){let o=d.frames.find(k=>k.id===ne[1]);if(!o)return f(t,404,{error:"no such frame"});let c=await F(e);if(typeof c.html!="string"||!c.html)return f(t,400,{error:"nothing captured"});let u=se(`${o.name.replace(/ · (frozen|draft)( \d+)?$/,"")} \xB7 ${c.editable?"draft":"frozen"}`),p=ke(u);await D.mkdir(p,{recursive:!0}),await D.writeFile(h.join(p,"index.html"),c.html);let S=typeof c.from=="string"&&c.from.startsWith("/")&&!c.from.startsWith("/__loop/")?c.from.slice(0,2e3):o.kind==="frozen"?o.from:o.kind==="route"?o.src:void 0,w={id:N(6),name:u,kind:c.editable?"folder":"frozen",src:p,entry:"index.html",from:S,frozenAt:Date.now(),...c.editable?{draftOf:S||o.src}:{},w:o.w,h:o.h,keyboard:o.keyboard,...c.x!=null&&c.y!=null?{x:+c.x,y:+c.y}:yt(o.w,o.h,o.id),createdAt:Date.now()};return d.frames.push(w),c.editable&&De(w),x(),f(t,200,w)}let Ae=/^\/api\/frames\/([^/]+)\/duplicate$/.exec(i);if(Ae&&e.method==="POST"){let o=d.frames.find(g=>g.id===Ae[1]);if(!o)return f(t,404,{error:"no such frame"});let c=await F(e),u=o.kind==="route"&&typeof c.route=="string"&&c.route.startsWith("/")&&!c.route.startsWith("/__loop/")?c.route.slice(0,2e3):null,p=u&&u!==o.src,S=se(p?bo(u):`${o.name.replace(/ copy( \d+)?$/,"")} copy`),w=c.x!=null&&c.y!=null?{x:c.x,y:c.y}:{near:o.id},k;if(o.kind==="folder"||o.kind==="frozen"){let g=ke(S);await fe(o.src,g),k=z({src:h.join(g,o.entry),name:S,w:o.w,h:o.h,...w}),o.kind==="frozen"&&(Me(k.id),Object.assign(k,{kind:"frozen",from:o.from,frozenAt:o.frozenAt}),x())}else o.kind==="route"?k=z({route:u||o.src,name:S,w:o.w,h:o.h,dup:!0,...w}):k=z({src:o.src,name:S,w:o.w,h:o.h,...w});return f(t,200,k)}let zt=/^\/api\/frames\/([^/]+)$/.exec(i);if(zt){let o=d.frames.find(c=>c.id===zt[1]);if(!o)return f(t,404,{});if(e.method==="PATCH"){let c=await F(e),u=o.x+o.w/2,p=o.y+o.h/2,S=o.shapeless&&(c.w!=null||c.h!=null)&&c.x==null&&c.y==null;for(let w of["x","y","w","h"])c[w]!=null&&isFinite(c[w])&&(o[w]=Math.round(+c[w]));return S&&(o.x=Math.round(u-o.w/2),o.y=Math.round(p-o.h/2)),o.shapeless&&(c.w!=null||c.h!=null)&&delete o.shapeless,c.name&&(o.name=String(c.name).slice(0,80)),typeof c.keyboard=="boolean"&&(o.keyboard=c.keyboard||void 0),"fill"in c&&(o.fill=c.fill==="none"?"none":typeof c.fill=="string"&&/^#[0-9a-f]{6}$/i.test(c.fill)?c.fill.toLowerCase():void 0),"parent"in c&&(o.parent=c.parent&&c.parent!==o.id&&d.frames.some(w=>w.id===c.parent)?c.parent:void 0),x(),f(t,200,o)}if(e.method==="DELETE"){let c=v.get(o.id);return c&&(c.canceled=!0,c.child?.kill("SIGTERM"),v.delete(o.id)),d.frames=d.frames.filter(u=>u.id!==o.id),d.comments=d.comments.filter(u=>u.frameId!==o.id),Me(o.id),x(),f(t,200,{ok:!0})}}if(e.method==="POST"&&i==="/api/sections"){let o=await F(e);if(![o.x,o.y,o.w,o.h].every(Number.isFinite))return f(t,400,{error:"x, y, w and h required"});let c=d.sections.length+1;for(;d.sections.some(p=>p.name===`Section ${c}`);)c++;let u={id:N(6),name:String(o.name||`Section ${c}`).slice(0,80),x:Math.round(o.x),y:Math.round(o.y),w:Math.max(120,Math.round(o.w)),h:Math.max(120,Math.round(o.h)),createdAt:Date.now()};return d.sections.push(u),x(),f(t,200,u)}let Wt=/^\/api\/sections\/([^/]+)$/.exec(i);if(Wt){let o=d.sections.find(c=>c.id===Wt[1]);if(!o)return f(t,404,{});if(e.method==="PATCH"){let c=await F(e);for(let u of["x","y","w","h"])c[u]!=null&&isFinite(c[u])&&(o[u]=Math.round(+c[u]));return c.name&&(o.name=String(c.name).slice(0,80)),x(),f(t,200,o)}if(e.method==="DELETE")return d.sections=d.sections.filter(c=>c.id!==o.id),x(),f(t,200,{ok:!0})}if(e.method==="GET"&&i==="/api/duo-model")try{let o=await No();return t.writeHead(200,{"content-type":"model/vnd.usdz+zip","cache-control":"max-age=86400"}),t.end(await D.readFile(o))}catch(o){return f(t,503,{error:o.message})}if(e.method==="GET"&&i==="/api/site-icon"){let o="";try{o=new URL(n.searchParams.get("u")||"").hostname}catch{}if(!o)return t.writeHead(404),t.end();let c=await wo(o);return c?(t.writeHead(200,{"content-type":c.type,"cache-control":"max-age=86400"}),t.end(c.buf)):(t.writeHead(404),t.end())}if(e.method==="GET"&&i==="/api/resolve"){let o=C(n.searchParams.get("f")||"");return o?f(t,200,{frame:{id:o.id,name:o.name,kind:o.kind,where:$t(o),w:o.w,h:o.h,src:o.src,entry:o.entry},selector:n.searchParams.get("e")||null,label:n.searchParams.get("n")||null}):f(t,404,{error:"That frame is no longer on this canvas."})}if(e.method==="GET"&&i==="/api/canvas-history")return f(t,200,{items:mo()});let Bt=/^\/api\/canvas-history\/(\d+)\/restore$/.exec(i);if(Bt&&e.method==="POST"){if(!s)return f(t,403,{});if(v.size)return f(t,409,{error:"An agent is working. Restore when it has finished (or stop it)."});let o;try{o=JSON.parse(y.readFileSync(h.join(ye,`${Bt[1]}.json`),"utf8"))}catch{return f(t,404,{error:"That moment is no longer kept."})}ze(),yn("before restoring",!0);for(let c of d.frames)Me(c.id);d.frames=o.state.frames,d.sections=o.state.sections,d.strokes=o.state.strokes,d.comments=o.state.comments.map(c=>["working","queued"].includes(c.status)?{...c,status:"canceled",reply:c.reply||"Stopped."}:c);for(let c of d.frames)delete c.building,De(c);return ht=wn(d),x(),K({type:"state"}),f(t,200,{ok:!0,frames:d.frames.length})}if(e.method==="POST"&&i==="/api/probe-url"){let o=await F(e),c;try{if(c=new URL(String(o.url)),!/^https?:$/.test(c.protocol))throw 0}catch{return f(t,400,{error:"Not a web address"})}try{let u=await fetch(c,{redirect:"follow",signal:AbortSignal.timeout(8e3),headers:{"user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15",accept:"text/html"}}),p=u.headers.get("x-frame-options")||"",S=/frame-ancestors([^;]*)/i.exec(u.headers.get("content-security-policy")||"")?.[1]?.trim()||"",w=/deny|sameorigin/i.test(p)||S&&!/(^|\s)\*(\s|$)/.test(S);return f(t,200,{embeddable:u.ok&&!w,status:u.status,blocked:w})}catch{return f(t,200,{embeddable:!1,status:0})}}if(e.method==="POST"&&i==="/api/restore"){let o=await F(e);for(let c of o.sections||[])c?.id&&!d.sections.find(u=>u.id===c.id)&&d.sections.push(c);for(let c of o.frames||[])c?.id&&!d.frames.find(u=>u.id===c.id)&&(d.frames.push(c),De(c));for(let c of o.strokes||[])c?.id&&!d.strokes.find(u=>u.id===c.id)&&d.strokes.push(c);for(let c of o.comments||[])c?.id&&!d.comments.find(u=>u.id===c.id)&&d.comments.push({...c,status:["working","queued"].includes(c.status)?"canceled":c.status});return x(),f(t,200,{ok:!0})}if(e.method==="POST"&&i==="/api/strokes"){let o=await F(e),c={id:N(8),points:(o.points||[]).slice(0,6e3).map(p=>Math.round(p*10)/10),color:String(o.color||"#E5484D").slice(0,16),width:+o.width||3,frameId:o.frameId||null,createdAt:Date.now()},u=c.frameId&&d.frames.find(p=>p.id===c.frameId);return u&&(c.fx=Number.isFinite(+o.fx)?+o.fx:u.x,c.fy=Number.isFinite(+o.fy)?+o.fy:u.y),d.strokes.push(c),x(),f(t,200,c)}let Ht=/^\/api\/strokes\/([^/]+)$/.exec(i);if(Ht&&e.method==="DELETE")return d.strokes=d.strokes.filter(o=>o.id!==Ht[1]),x(),f(t,200,{ok:!0});if(e.method==="POST"&&i==="/api/update")return!ee||ee.how!=="restart"?f(t,400,{error:"No update to apply here"}):ee.state==="updating"?f(t,200,{ok:!0}):v.size?(ee.state="queued",x(),f(t,200,{ok:!0,queued:!0})):(Yn(),f(t,200,{ok:!0}));if(e.method==="POST"&&i==="/api/settings"){let o=await F(e);if((o.mode==="headless"||o.mode==="inbox")&&(d.agent.mode=o.mode),o.runner&&we[o.runner]){if(!we[o.runner].bin)return f(t,400,{error:`${we[o.runner].label} isn't installed on this computer`});d.agent.runner=o.runner}if(o.proxy!==void 0){if(o.proxy&&!/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(o.proxy))return f(t,400,{error:"proxy must be a local dev server origin, e.g. http://localhost:3000"});d.proxy=o.proxy||null}if(o.chat&&typeof o.chat=="object"){let c=p=>typeof p=="string"&&/^[\w.:\-\[\]]{1,60}$/.test(p)?p:null,u=p=>typeof p=="string"&&p.length<600&&h.isAbsolute(p)?p:void 0;d.agent.chat={runner:o.chat.runner==="codex"?"codex":"claude",model:c(o.chat.model),effort:c(o.chat.effort),permission:c(o.chat.permission),session:c(o.chat.session),cwd:u(o.chat.cwd),transcript:u(o.chat.transcript)}}if(o.pick&&typeof o.pick=="object"){let c=Te(),u=Ce(c),p=(d.agent.pick||={})[c]||={};if("model"in o.pick){if(o.pick.model&&!u.models.includes(o.pick.model))return f(t,400,{error:"No such model"});p.model=o.pick.model||void 0}if("effort"in o.pick){if(o.pick.effort&&!Ce(c).efforts.includes(o.pick.effort))return f(t,400,{error:"No such effort level"});p.effort=o.pick.effort||void 0}}if(o.disallow){d.agent.allow=(d.agent.allow||[]).filter(c=>c!==o.disallow);for(let c of[...q.values()])c.turn?c.restart=!0:Se(c)}return o.name&&(d.name=String(o.name).slice(0,80)),o.hostName!==void 0&&(d.hostName=String(o.hostName).trim().slice(0,32)||void 0),x(),Rt(),f(t,200,{ok:!0})}if(e.method==="POST"&&i==="/api/share/public")try{return await si(),f(t,200,At())}catch(o){return f(t,400,{error:o.message})}if(e.method==="POST"&&i==="/api/share/stop")return ge?.kill(),ae=null,x(),f(t,200,{ok:!0});if(e.method==="POST"&&i==="/api/share/rotate")return d.token=N(16),x(),f(t,200,At());if(i.startsWith("/api/cloud")&&!H)return f(t,404,{error:"Email sharing is not available in this version of Loop."});if(i==="/api/cloud"&&e.method==="GET")return f(t,200,await H.status());if(e.method==="POST"&&i==="/api/cloud/session"){let o=await F(e);return f(t,200,{user:await H.setSession(o)})}if(e.method==="POST"&&i==="/api/cloud/signout")return H.signOut(),f(t,200,{ok:!0});if(e.method==="POST"&&i==="/api/cloud/publish")return f(t,200,{link:await H.publish()});if(e.method==="POST"&&i==="/api/cloud/snapshot"){let o=await F(e),c=d.frames.find(p=>p.id===o.frameId);if(!c||c.kind!=="route"||typeof o.html!="string")return f(t,400,{error:"route frame and html required"});let u=await H.publishSnapshot(c,o.html);return H.schedulePush(200),f(t,200,u)}if(e.method==="POST"&&i==="/api/cloud/invite"){let o=await F(e);return f(t,200,await H.invite(o.emails||[],o.role))}if(e.method==="DELETE"&&i.startsWith("/api/cloud/members/"))return await H.removeMember(decodeURIComponent(i.slice(19))),f(t,200,{ok:!0});if(e.method==="POST"&&i==="/api/shutdown")return f(t,200,{ok:!0}),setTimeout(Be,50);f(t,404,{error:"not found"})}catch(a){f(t,500,{error:a.message})}});Ve.on("upgrade",(e,t,n)=>{let i=new URL(e.url,"http://x");if(!d.proxy||i.pathname.startsWith(Z)||!Jn(e,i))return t.destroy();let r=new URL(d.proxy),s=pn.connect(+(r.port||80),r.hostname,()=>{let a=`${e.method} ${e.url} HTTP/1.1\r
|
|
37
|
+
`;for(let l=0;l<e.rawHeaders.length;l+=2){let m=e.rawHeaders[l],$=e.rawHeaders[l+1];m.toLowerCase()==="host"&&($=r.host),a+=`${m}: ${$}\r
|
|
35
38
|
`}s.write(a+`\r
|
|
36
|
-
`),
|
|
37
|
-
`).slice(-3).join(" "))):e()))}catch(e){ee.state="failed",ee.error=e.message.slice(0,300)
|
|
39
|
+
`),n?.length&&s.write(n),s.pipe(t),t.pipe(s)});s.on("error",()=>t.destroy()),t.on("error",()=>s.destroy())});io&&(H={createCloud:()=>null}.createCloud({state:d,changed:x,pump:ce,broadcast:K,log:e=>console.log(e)}));var dn=!1,ln="";function Nt(){let e=JSON.stringify(_n()||null);e!==ln&&(ln=e,x(!0))}setInterval(Nt,15e3).unref?.();setInterval(()=>{let e=Re();e!==dn&&(dn=e,x(!0));for(let t of[...q.values()])!t.turn&&t.frameId!==pe&&!d.frames.some(n=>n.id===t.frameId)&&Se(t);if(d.agent.mode==="inbox"&&!e){for(let[t,n]of v)if(n.inbox){v.delete(t);let i=d.comments.find(r=>r.id===n.commentId);i&&i.status==="working"&&(i.status="queued",x())}if(d.agent.mode==="inbox"&&fn>=0){let t=!1;for(let n of d.comments)n.status==="queued"&&!n.background&&Date.now()-(n.queuedAt||n.createdAt)>fn&&C(n.frameId)&&(n.background=!0,t=!0);t&&(x(),Rt())}}},5e3);var fn=Number(process.env.LOOP_CHAT_WAIT??15e3),_t=(()=>{try{return JSON.parse(y.readFileSync(h.join(le,"package.json"),"utf8")).version||null}catch{return null}})(),Pt=process.env.LOOP_UPDATE_TEST?"test":/[\\/]_npx[\\/]/.test(le)?"npx":/[\\/]node_modules[\\/]/.test(le)?"global":null,ee=null,ci=(e,t)=>{let n=String(e).split(".").map(Number),i=String(t).split(".").map(Number);for(let r=0;r<3;r++)if((n[r]||0)!==(i[r]||0))return(n[r]||0)>(i[r]||0);return!1};async function Kn(){if(!(!Pt||!_t||ee?.state==="updating"))try{let e=process.env.LOOP_UPDATE_TEST||(await(await fetch("https://registry.npmjs.org/loop-canvas/latest",{signal:AbortSignal.timeout(8e3),headers:{accept:"application/json"}})).json()).version;e&&ci(e,_t)&&ee?.latest!==e&&(ee={latest:e,how:Pt==="npx"?"next-start":"restart",state:"available"},x())}catch{}}setTimeout(Kn,4e3).unref?.();setInterval(Kn,3*36e5).unref?.();async function Yn(){if(ee.state="updating",delete ee.error,x(),Pt==="global")try{await new Promise((e,t)=>mn("npm",["install","-g",`loop-canvas@${ee.latest}`],{timeout:18e4},(n,i,r)=>n?t(new Error(String(r||n.message).trim().split(`
|
|
40
|
+
`).slice(-3).join(" "))):e()))}catch(e){ee.state="failed",ee.error=e.message.slice(0,300),x();return}ze(),je(process.execPath,[h.join(le,"server.mjs"),"--dir",_,"--port",String(X)],{detached:!0,stdio:"ignore",env:{...process.env,LOOP_SAME_PORT:"1",LOOP_UPDATE_TEST:""}}).unref(),setTimeout(()=>Be(!0),150)}var Xn=["server.mjs","cli.mjs","public/app.js","public/app.css","public/index.html","public/duo3d.js"].map(e=>h.join(le,e)),Vn=()=>Xn.map(e=>{try{return Math.round(y.statSync(e).mtimeMs)}catch{return 0}}).join("."),Zn=Vn(),Qn=!1,un=null;for(let e of Xn)try{y.watch(e,()=>{clearTimeout(un),un=setTimeout(()=>{Vn()!==Zn&&(Qn=!0,qn())},1500)}).unref?.()}catch{}function qn(){if(ee?.state==="queued"&&!v.size)return Yn();!Qn||v.size||ut||(ut=!0,mn(process.execPath,["--check",h.join(le,"server.mjs")],e=>{if(e||v.size){ut=!1;return}console.log("Loop \u25B8 restarting into the new version"),ze(),je(process.execPath,[h.join(le,"server.mjs"),"--dir",_,"--port",String(X)],{detached:!0,stdio:"ignore",env:{...process.env,LOOP_SAME_PORT:"1",LOOP_UPDATE_TEST:""}}).unref(),setTimeout(()=>Be(!0),150)}))}var ut=!1;function Ze(e,t=20){Ve.once("error",n=>{if(n.code==="EADDRINUSE"&&process.env.LOOP_SAME_PORT&&t>0)return setTimeout(()=>Ze(e,t-1),500);if(n.code==="EADDRINUSE"&&process.env.LOOP_SAME_PORT)return delete process.env.LOOP_SAME_PORT,Ze(e+1,20);n.code==="EADDRINUSE"&&t>0?Ze(e+1,t-1):(console.error(n),process.exit(1))}),Ve.listen(e,"0.0.0.0",()=>{X=Ve.address().port,y.writeFileSync(Qe,JSON.stringify({port:X,pid:process.pid})),console.log(`Loop \u25B8 http://localhost:${X} (${_})`),Rt(),Ko().catch(()=>{})})}function Be(e=!1){try{e?y.writeFileSync(Qe,JSON.stringify({port:X,pid:process.pid,restarting:Date.now()})):y.rmSync(Qe,{force:!0})}catch{}ge?.kill(),xt();for(let t of q.values())try{t.child.kill("SIGTERM")}catch{}for(let t of v.values())t.child?.kill("SIGTERM");clearTimeout(mt),ze(),process.exit(0)}process.on("SIGINT",Be);process.on("SIGTERM",Be);(async()=>{if(!process.env.LOOP_SAME_PORT){let e=null;try{e=JSON.parse(y.readFileSync(Qe,"utf8"))}catch{}let t=n=>{try{return process.kill(n,0),!0}catch{return!1}};if(e?.pid&&e.pid!==process.pid&&t(e.pid))for(let n=0;n<(e.restarting?30:3);n++){try{(await fetch(`http://127.0.0.1:${e.port}/__loop/api/ping`,{signal:AbortSignal.timeout(800)})).ok&&(console.log(`Loop \u25B8 this canvas is already served at http://localhost:${e.port}/__loop/`),process.exit(0))}catch{}await new Promise(i=>setTimeout(i,500))}}Ze(+gn.port||4848)})();function di(e){let t={};for(let n=0;n<e.length;n++)if(e[n].startsWith("--")){let i=e[n].slice(2);t[i]=e[n+1]&&!e[n+1].startsWith("--")?e[++n]:!0}return t}function $e(e){let t=[...(process.env.PATH||"").split(":"),h.join(te.homedir(),".local/bin"),"/opt/homebrew/bin","/usr/local/bin"];for(let n of t){if(!n)continue;let i=h.join(n,e);try{return y.accessSync(i,y.constants.X_OK),i}catch{}}return null}export{be as PRESETS};
|