@popmelt.com/core 0.5.6 → 0.5.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/dist/server.mjs CHANGED
@@ -1,16 +1,43 @@
1
- var Dt=Object.defineProperty,At=Object.defineProperties;var Jt=Object.getOwnPropertyDescriptors;var Re=Object.getOwnPropertySymbols;var Ze=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Ke=(r,t)=>(t=Symbol[r])?t:Symbol.for("Symbol."+r);var Xe=(r,t,n)=>t in r?Dt(r,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[t]=n,Z=(r,t)=>{for(var n in t||(t={}))Ze.call(t,n)&&Xe(r,n,t[n]);if(Re)for(var n of Re(t))et.call(t,n)&&Xe(r,n,t[n]);return r},ae=(r,t)=>At(r,Jt(t));var tt=(r,t)=>{var n={};for(var e in r)Ze.call(r,e)&&t.indexOf(e)<0&&(n[e]=r[e]);if(r!=null&&Re)for(var e of Re(r))t.indexOf(e)<0&&et.call(r,e)&&(n[e]=r[e]);return n};var ce=(r,t,n)=>(t=r[Ke("asyncIterator")])?t.call(r):(r=r[Ke("iterator")](),t={},n=(e,s)=>(s=r[e])&&(t[e]=a=>new Promise((i,c,p)=>(a=s.call(r,a),p=a.done,Promise.resolve(a.value).then(u=>i({value:u,done:p}),c)))),n("next"),n("return"),t);import{execFileSync as an}from"child_process";import{randomUUID as he}from"crypto";import{mkdir as cn,readdir as ln,stat as dn,unlink as un,writeFile as ye}from"fs/promises";import{createServer as pn}from"http";import{tmpdir as hn}from"os";import{join as le}from"path";import{spawn as Nt}from"child_process";import{createInterface as _t}from"readline";function $e(r,t){let{prompt:n,projectRoot:e,maxTurns:s=40,maxBudgetUsd:a=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:p,model:u,onEvent:x}=t,L=[];p?L.push("--resume",p,"-p",n):L.push("-p",n),L.push("--output-format","stream-json","--verbose","--max-turns",String(s),"--max-budget-usd",String(a)),u&&L.push("--model",u);for(let I of i)L.push("--allowedTools",I);let w=Nt(c,L,{cwd:e,stdio:["ignore","pipe","pipe"],env:ae(Z({},process.env),{ANTHROPIC_API_KEY:void 0})}),M=new Promise(I=>{var J;let F,b=[],z=[],Q=!1,ee="",G=_t({input:w.stdout}),B=new Set;G.on("line",j=>{var R,q,H,K,Ie,ke,Pe,be,Te;if(j.trim())try{let Y=JSON.parse(j);Y.session_id&&!F&&(F=Y.session_id);let Ae=(q=Y.type)!=null?q:(R=Y.event)!=null&&R.type?`event.${Y.event.type}`:"unknown";if(B.add(Ae),Y.type==="result"&&Y.result&&b.length===0){let A=typeof Y.result=="string"?Y.result:"";A&&(b.push(A),x==null||x({type:"delta",jobId:r,text:A},r))}if(Y.type==="assistant"&&Array.isArray((H=Y.message)==null?void 0:H.content))for(let A of Y.message.content){if(A.type==="text"&&A.text&&(b.push(A.text),x==null||x({type:"delta",jobId:r,text:A.text},r)),A.type==="tool_use"&&A.name){let we=((K=A.input)==null?void 0:K.file_path)||((Ie=A.input)==null?void 0:Ie.path)||void 0;x==null||x(Z({type:"tool_use",jobId:r,tool:A.name},we?{file:we}:{}),r),A.name==="Edit"&&((ke=A.input)!=null&&ke.file_path)?z.push({tool:"Edit",file_path:A.input.file_path,old_string:A.input.old_string,new_string:A.input.new_string,replace_all:A.input.replace_all}):A.name==="Write"&&((Pe=A.input)!=null&&Pe.file_path)&&z.push({tool:"Write",file_path:A.input.file_path,content:A.input.content})}A.type==="thinking"&&A.thinking&&(x==null||x({type:"thinking",jobId:r,text:A.thinking},r))}Y.type==="user"&&((Te=(be=Y.tool_use_result)==null?void 0:be.file)!=null&&Te.filePath)&&(x==null||x({type:"tool_use",jobId:r,tool:"Read",file:Y.tool_use_result.file.filePath},r))}catch(Y){}});let te=[];(J=w.stderr)==null||J.on("data",j=>{te.push(j.toString())}),w.on("close",j=>{G.close(),j!==0&&j!==null&&(Q=!0,ee=te.join("")||`Claude process exited with code ${j}`),I({sessionId:F,text:b.join(""),success:!Q,error:Q?ee:void 0,fileEdits:z.length>0?z:void 0})}),w.on("error",j=>{Q=!0,ee=j.message,I({sessionId:F,text:b.join(""),success:!1,error:ee,fileEdits:z.length>0?z:void 0})})});return{process:w,result:M}}import{spawn as Bt}from"child_process";import{createInterface as Ut}from"readline";function nt(r,t){let{prompt:n,projectRoot:e,screenshotPath:s,resumeSessionId:a,model:i,onEvent:c}=t,p=[];a?(p.push("exec","resume",a),i&&p.push("-m",i),p.push("--json","--full-auto",n),s&&p.push("--image",s)):(p.push("exec","--json","--full-auto"),i&&p.push("-m",i),p.push(n),s&&p.push("--image",s));let u=Bt("codex",p,{cwd:e,stdio:["ignore","pipe","pipe"],env:Z({},process.env)}),x=new Promise(L=>{var ee;let w,M=[],I=!1,F="",b=Ut({input:u.stdout}),z=new Set;b.on("line",G=>{var B,te,J,j;if(G.trim())try{let R=JSON.parse(G),q=(B=R.type)!=null?B:"unknown";if(z.add(q),q==="thread.started"&&R.thread_id&&!w&&(w=R.thread_id),q==="item/agentMessage/delta"&&((te=R.delta)!=null&&te.text)&&(M.push(R.delta.text),c==null||c({type:"delta",jobId:r,text:R.delta.text},r)),q==="item/reasoning/delta"&&((J=R.delta)!=null&&J.text)&&(c==null||c({type:"thinking",jobId:r,text:R.delta.text},r)),q==="item/started"&&R.item){let H=R.item.type;if(H==="command_execution")c==null||c({type:"tool_use",jobId:r,tool:"Bash"},r);else if(H==="file_change"){let K=R.item.filename||R.item.path;c==null||c(Z({type:"tool_use",jobId:r,tool:"Edit"},K?{file:K}:{}),r)}else if(H==="file_read"){let K=R.item.filename||R.item.path;c==null||c(Z({type:"tool_use",jobId:r,tool:"Read"},K?{file:K}:{}),r)}else if(H==="web_search")c==null||c({type:"tool_use",jobId:r,tool:"WebSearch"},r);else if(H==="mcp_tool_call"){let K=R.item.tool_name||R.item.name||"MCP";c==null||c({type:"tool_use",jobId:r,tool:K},r)}}if(q==="item/completed"&&R.item){if(R.item.type==="agent_message"){let H=R.item.text;typeof H=="string"&&H&&M.push(H)}else if(R.item.type==="reasoning"){let H=R.item.text;typeof H=="string"&&H&&(c==null||c({type:"thinking",jobId:r,text:H},r))}}q==="turn.failed"&&(I=!0,F=((j=R.error)==null?void 0:j.message)||R.message||"Turn failed")}catch(R){}});let Q=[];(ee=u.stderr)==null||ee.on("data",G=>{Q.push(G.toString())}),u.on("close",G=>{b.close(),G!==0&&G!==null&&(I=!0,F=Q.join("")||`Codex process exited with code ${G}`),L({sessionId:w,text:M.join(""),success:!I,error:I?F:void 0})}),u.on("error",G=>{I=!0,F=G.message,L({sessionId:w,text:M.join(""),success:!1,error:F})})});return{process:u,result:x}}import{execFile as Ft}from"child_process";import{copyFile as st,mkdir as ot,readdir as zt,readFile as jt,writeFile as Ht}from"fs/promises";import{join as pe}from"path";var Me=class{constructor(t){this.projectRoot=t;let n=pe(t,".popmelt");this.decisionsDir=pe(n,"decisions"),this.screenshotsDir=pe(n,"screenshots")}async persist(t,n,e){try{await ot(this.decisionsDir,{recursive:!0}),await ot(this.screenshotsDir,{recursive:!0});try{await st(n,pe(this.screenshotsDir,`s-${t.id}.png`))}catch(s){}for(let s=0;s<e.length;s++)try{let a=t.pastedImagePaths[s];a&&await st(e[s],pe(this.screenshotsDir,a.replace("screenshots/","")))}catch(a){}await Ht(pe(this.decisionsDir,`d-${t.id}.json`),JSON.stringify(t,null,2))}catch(s){console.error("[DecisionStore] Failed to persist decision record:",s)}}async listDecisionIds(){try{return(await zt(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch(t){return[]}}async loadDecision(t){try{let n=await jt(pe(this.decisionsDir,`d-${t}.json`),"utf-8");return JSON.parse(n)}catch(n){return null}}async loadDecisions(t){return(await Promise.all(t.map(e=>this.loadDecision(e)))).filter(e=>e!==null)}captureGitDiff(t){return new Promise(n=>{Ft("git",["diff","HEAD"],{cwd:t,timeout:5e3,maxBuffer:1024*1024},(e,s)=>{if(e){n(null);return}n(s||null)})})}};import{readFile as rt,writeFile as fe}from"fs/promises";import{join as Ne}from"path";var oe="[Materializer]",Lt={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Oe=class{constructor(t,n,e={}){this.projectRoot=t;this.decisionStore=n;this.options=e;this.cachedIndex=null;this.running=!1;let s=Ne(t,".popmelt");this.indexPath=Ne(s,"materialized.json"),this.modelPath=Ne(s,"model.json")}get isRunning(){return this.running}async loadModel(){try{let t=await rt(this.modelPath,"utf-8");return JSON.parse(t)}catch(t){return null}}async addComponent(t){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let e=n.components;return e[t]?{added:!1,alreadyExists:!0}:(e[t]={description:""},await fe(this.modelPath,JSON.stringify(n,null,2)),console.log(`${oe} Added component "${t}" to model`),{added:!0,alreadyExists:!1})}async updateToken(t,n){let e=await this.loadModel();e||(e={tokens:{},components:{},rules:[]});let s=t.split("."),a=e;for(let p=0;p<s.length-1;p++){let u=s[p];(!a[u]||typeof a[u]!="object")&&(a[u]={}),a=a[u]}let i=s[s.length-1],c;try{c=JSON.parse(n)}catch(p){c=null}if(c&&typeof c=="object"&&c!==null&&"value"in c)a[i]=c;else{let p=a[i];p&&typeof p=="object"&&p!==null&&"value"in p?p.value=n:a[i]=n}return await fe(this.modelPath,JSON.stringify(e,null,2)),console.log(`${oe} Updated token "${t}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(t){let n=await this.loadModel();if(!n)return{removed:!1};let e=t.split("."),s=n;for(let i=0;i<e.length-1;i++){let c=e[i];if(!s[c]||typeof s[c]!="object")return{removed:!1};s=s[c]}let a=e[e.length-1];return a in s?(delete s[a],await fe(this.modelPath,JSON.stringify(n,null,2)),console.log(`${oe} Removed token "${t}" from model`),{removed:!0}):{removed:!1}}async removeComponent(t){let n=await this.loadModel();if(!n)return{removed:!1};let e=n.components;return!e||!e[t]?{removed:!1}:(delete e[t],await fe(this.modelPath,JSON.stringify(n,null,2)),console.log(`${oe} Removed component "${t}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let t=await this.loadIndex(),n=new Set(t.materializedIds),s=(await this.decisionStore.listDecisionIds()).filter(i=>!n.has(i));return s.length===0?[]:(await this.decisionStore.loadDecisions(s)).filter(i=>i.resolutions.some(c=>{var u;let p=(u=c.finalScope)!=null?u:c.inferredScope;return(p==null?void 0:p.breadth)==="pattern"}))}async run(){var t,n,e,s,a,i,c;if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;try{let p=await this.getUnmaterializedPatternDecisions();if(p.length===0)return{processedIds:[],success:!0};let u=p.map(b=>b.id);console.log(`${oe} Processing ${u.length} pattern-scoped decision(s): ${u.join(", ")}`),(n=(t=this.options).onEvent)==null||n.call(t,{type:"materialize_started",decisionIds:u});let x=await this.loadModel(),L=Gt(p,x),w=!0,M;try{let{result:b}=$e(`mat-${Date.now()}`,{prompt:L,projectRoot:this.projectRoot,maxTurns:(e=this.options.maxTurns)!=null?e:5,maxBudgetUsd:(s=this.options.maxBudgetUsd)!=null?s:.5,allowedTools:["Read"],claudePath:(a=this.options.claudePath)!=null?a:"claude"}),z=await b;if(!z.success)w=!1,M=z.error,console.error(`${oe} Claude spawn error:`,M);else{let Q=Wt(z.text);Q?(await fe(this.modelPath,JSON.stringify(Q,null,2)),console.log(`${oe} Successfully materialized ${u.length} decision(s) \u2192 ${this.modelPath}`)):(w=!1,M="No <model> block found in response",console.error(`${oe} ${M}`))}}catch(b){w=!1,M=b instanceof Error?b.message:String(b),console.error(`${oe} Error:`,M)}let I=await this.loadIndex(),F=new Set(I.materializedIds);for(let b of u)F.add(b);return I.materializedIds=[...F],I.lastRunAt=Date.now(),I.lastRunDecisionIds=u,I.lastRunError=M!=null?M:null,await this.persistIndex(I),(c=(i=this.options).onEvent)==null||c.call(i,{type:"materialize_done",decisionIds:u,success:w,error:M}),{processedIds:u,success:w,error:M}}finally{this.running=!1}}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let t=await rt(this.indexPath,"utf-8"),n=JSON.parse(t);return this.cachedIndex=n,n}catch(t){return this.cachedIndex=ae(Z({},Lt),{materializedIds:[],lastRunDecisionIds:[]}),this.cachedIndex}}async persistIndex(t){this.cachedIndex=t;try{await fe(this.indexPath,JSON.stringify(t,null,2))}catch(n){console.error(`${oe} Failed to write index:`,n)}}};function Wt(r){let t=r.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!(t!=null&&t[1]))return null;try{let n=JSON.parse(t[1]);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch(n){return null}}function Gt(r,t){let n=r.map(s=>{let i=s.resolutions.filter(u=>{var L;let x=(L=u.finalScope)!=null?L:u.inferredScope;return(x==null?void 0:x.breadth)==="pattern"}).map(u=>{var M,I,F,b;let x=(M=u.finalScope)!=null?M:u.inferredScope,L=(I=x==null?void 0:x.target)!=null?I:"unknown",w=(b=(F=u.filesModified)==null?void 0:F.join(", "))!=null?b:"none";return`- **${u.summary}** [scope: pattern/${L}]
2
- Files modified: ${w}`}).join(`
3
- `),c=s.annotations.map(u=>u.instruction).filter(Boolean).join(`
4
- `),p=s.gitDiff?`
1
+ import{a as ee,b as ce,c as tt,d as de}from"./chunk-3HWT3PC2.mjs";import{execFileSync as dn}from"child_process";import{randomUUID as fe}from"crypto";import{mkdir as un,readFile as pn,readdir as hn,stat as fn,unlink as mn,writeFile as ve}from"fs/promises";import{createServer as gn}from"http";import{tmpdir as yn}from"os";import{dirname as wn,join as oe}from"path";import{fileURLToPath as vn}from"url";function nt(i,n){return`<!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>Popmelt Canvas</title>
6
+ <link rel="preconnect" href="https://fonts.googleapis.com">
7
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
8
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
9
+ <style>*{margin:0;padding:0;box-sizing:border-box}html,body,#root{height:100%;overflow:hidden}</style>
10
+ </head>
11
+ <body>
12
+ <div id="root"></div>
13
+ <script type="importmap">
14
+ {"imports":{
15
+ "react":"https://esm.sh/react@19?dev",
16
+ "react-dom/client":"https://esm.sh/react-dom@19/client?dev",
17
+ "react/jsx-runtime":"https://esm.sh/react@19/jsx-runtime?dev"
18
+ }}
19
+ </script>
20
+ <script type="module">
21
+ import { mountCanvas } from 'http://localhost:${i}/canvas/app.mjs';
22
+ mountCanvas(document.getElementById('root'), {
23
+ devOrigin: '${n}',
24
+ bridgeOrigin: 'http://localhost:${i}',
25
+ });
26
+ </script>
27
+ </body>
28
+ </html>`}import{spawn as Ut}from"child_process";import{createInterface as Ft}from"readline";function Oe(i,n){let{prompt:t,projectRoot:e,maxTurns:o=40,maxBudgetUsd:a=1,allowedTools:r=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:l="claude",resumeSessionId:p,model:f,timeoutMs:I=3e5,onEvent:O}=n,L=[];p?L.push("--resume",p,"-p",t):L.push("-p",t),L.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(a)),f&&L.push("--model",f);for(let P of r)L.push("--allowedTools",P);let m=Ut(l,L,{cwd:e,stdio:["ignore","pipe","pipe"],env:ce(ee({},process.env),{ANTHROPIC_API_KEY:void 0})}),_=new Promise(P=>{var W;let U,N=[],H=[],te=!1,G="",V=!1,E=setTimeout(()=>{V=!0,m.kill("SIGTERM"),setTimeout(()=>{try{m.kill("SIGKILL")}catch(T){}},5e3)},I),ne=Ft({input:m.stdout}),C=new Set;ne.on("line",T=>{var K,me,Pe,ke,be,Te,Re,$e,Me;if(T.trim())try{let Q=JSON.parse(T);Q.session_id&&!U&&(U=Q.session_id);let Ne=(me=Q.type)!=null?me:(K=Q.event)!=null&&K.type?`event.${Q.event.type}`:"unknown";if(C.add(Ne),Q.type==="result"&&Q.result&&N.length===0){let B=typeof Q.result=="string"?Q.result:"";B&&(N.push(B),O==null||O({type:"delta",jobId:i,text:B},i))}if(Q.type==="assistant"&&Array.isArray((Pe=Q.message)==null?void 0:Pe.content))for(let B of Q.message.content){if(B.type==="text"&&B.text&&(N.push(B.text),O==null||O({type:"delta",jobId:i,text:B.text},i)),B.type==="tool_use"&&B.name){let Ce=((ke=B.input)==null?void 0:ke.file_path)||((be=B.input)==null?void 0:be.path)||void 0;O==null||O(ee({type:"tool_use",jobId:i,tool:B.name},Ce?{file:Ce}:{}),i),B.name==="Edit"&&((Te=B.input)!=null&&Te.file_path)?H.push({tool:"Edit",file_path:B.input.file_path,old_string:B.input.old_string,new_string:B.input.new_string,replace_all:B.input.replace_all}):B.name==="Write"&&((Re=B.input)!=null&&Re.file_path)&&H.push({tool:"Write",file_path:B.input.file_path,content:B.input.content})}B.type==="thinking"&&B.thinking&&(O==null||O({type:"thinking",jobId:i,text:B.thinking},i))}Q.type==="user"&&((Me=($e=Q.tool_use_result)==null?void 0:$e.file)!=null&&Me.filePath)&&(O==null||O({type:"tool_use",jobId:i,tool:"Read",file:Q.tool_use_result.file.filePath},i))}catch(Q){}});let x=[];(W=m.stderr)==null||W.on("data",T=>{x.push(T.toString())}),m.on("close",T=>{clearTimeout(E),ne.close(),N.length===0&&C.size>0&&console.warn(`[Claude:${i}] No text captured. Event types seen: ${[...C].join(", ")}`),V?(te=!0,G=`Timed out after ${Math.round(I/6e4)} minutes`):T!==0&&T!==null&&(te=!0,G=x.join("")||`Claude process exited with code ${T}`),P({sessionId:U,text:N.join(""),success:!te,error:te?G:void 0,fileEdits:H.length>0?H:void 0})}),m.on("error",T=>{clearTimeout(E),te=!0,G=T.message,P({sessionId:U,text:N.join(""),success:!1,error:G,fileEdits:H.length>0?H:void 0})})});return{process:m,result:_}}import{spawn as zt}from"child_process";import{createInterface as Lt}from"readline";function st(i,n){let{prompt:t,projectRoot:e,screenshotPath:o,resumeSessionId:a,model:r,onEvent:l}=n,p=[];a?(p.push("exec","resume",a),r&&p.push("-m",r),p.push("--json","--full-auto",t),o&&p.push("--image",o)):(p.push("exec","--json","--full-auto"),r&&p.push("-m",r),p.push(t),o&&p.push("--image",o));let f=zt("codex",p,{cwd:e,stdio:["ignore","pipe","pipe"],env:ee({},process.env)}),I=new Promise(O=>{var te;let L,m=[],_=!1,P="",U=Lt({input:f.stdout}),N=new Set;U.on("line",G=>{var V,E,ne,C;if(G.trim())try{let x=JSON.parse(G),W=(V=x.type)!=null?V:"unknown";if(N.add(W),W==="thread.started"&&x.thread_id&&!L&&(L=x.thread_id),(W==="item.agentMessage.delta"||W==="item/agentMessage/delta")&&((E=x.delta)!=null&&E.text)&&(m.push(x.delta.text),l==null||l({type:"delta",jobId:i,text:x.delta.text},i)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&((ne=x.delta)!=null&&ne.text)&&(l==null||l({type:"thinking",jobId:i,text:x.delta.text},i)),(W==="item.started"||W==="item/started")&&x.item){let T=x.item.type;if(T==="command_execution")l==null||l({type:"tool_use",jobId:i,tool:"Bash"},i);else if(T==="file_change"){let K=x.item.filename||x.item.path;l==null||l(ee({type:"tool_use",jobId:i,tool:"Edit"},K?{file:K}:{}),i)}else if(T==="file_read"){let K=x.item.filename||x.item.path;l==null||l(ee({type:"tool_use",jobId:i,tool:"Read"},K?{file:K}:{}),i)}else if(T==="web_search")l==null||l({type:"tool_use",jobId:i,tool:"WebSearch"},i);else if(T==="mcp_tool_call"){let K=x.item.tool_name||x.item.name||"MCP";l==null||l({type:"tool_use",jobId:i,tool:K},i)}}if((W==="item.completed"||W==="item/completed")&&x.item){if(x.item.type==="agent_message"){let T=x.item.text;typeof T=="string"&&T&&(m.push(T),l==null||l({type:"delta",jobId:i,text:T},i))}else if(x.item.type==="reasoning"){let T=x.item.text;typeof T=="string"&&T&&(l==null||l({type:"thinking",jobId:i,text:T},i))}}W==="turn.failed"&&(_=!0,P=((C=x.error)==null?void 0:C.message)||x.message||"Turn failed")}catch(x){}});let H=[];(te=f.stderr)==null||te.on("data",G=>{H.push(G.toString())}),f.on("close",G=>{U.close(),m.length===0&&N.size>0&&console.warn(`[Codex:${i}] No text captured. Event types seen: ${[...N].join(", ")}`),G!==0&&G!==null&&(_=!0,P=H.join("")||`Codex process exited with code ${G}`),O({sessionId:L,text:m.join(""),success:!_,error:_?P:void 0})}),f.on("error",G=>{_=!0,P=G.message,O({sessionId:L,text:m.join(""),success:!1,error:P})})});return{process:f,result:I}}import{execFile as Ht}from"child_process";import{copyFile as ot,mkdir as rt,readdir as Gt,readFile as jt,writeFile as Wt}from"fs/promises";import{join as he}from"path";var Ee=class{constructor(n){this.projectRoot=n;let t=he(n,".popmelt");this.decisionsDir=he(t,"decisions"),this.screenshotsDir=he(t,"screenshots")}async persist(n,t,e){try{await rt(this.decisionsDir,{recursive:!0}),await rt(this.screenshotsDir,{recursive:!0});try{await ot(t,he(this.screenshotsDir,`s-${n.id}.png`))}catch(o){}for(let o=0;o<e.length;o++)try{let a=n.pastedImagePaths[o];a&&await ot(e[o],he(this.screenshotsDir,a.replace("screenshots/","")))}catch(a){}await Wt(he(this.decisionsDir,`d-${n.id}.json`),JSON.stringify(n,null,2))}catch(o){console.error("[DecisionStore] Failed to persist decision record:",o)}}async listDecisionIds(){try{return(await Gt(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch(n){return[]}}async loadDecision(n){try{let t=await jt(he(this.decisionsDir,`d-${n}.json`),"utf-8");return JSON.parse(t)}catch(t){return null}}async loadDecisions(n){return(await Promise.all(n.map(e=>this.loadDecision(e)))).filter(e=>e!==null)}captureGitDiff(n){return new Promise(t=>{Ht("git",["diff","HEAD"],{cwd:n,timeout:5e3,maxBuffer:1024*1024},(e,o)=>{if(e){t(null);return}t(o||null)})})}};import{readFile as it,writeFile as ge}from"fs/promises";import{join as Ue}from"path";var ie="[Materializer]",Yt={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Ae=class{constructor(n,t,e={}){this.projectRoot=n;this.decisionStore=t;this.options=e;this.cachedIndex=null;this.running=!1;let o=Ue(n,".popmelt");this.indexPath=Ue(o,"materialized.json"),this.modelPath=Ue(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let n=await it(this.modelPath,"utf-8");return JSON.parse(n)}catch(n){return null}}async addComponent(n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]}),(!t.components||typeof t.components!="object")&&(t.components={});let e=t.components;return e[n]?{added:!1,alreadyExists:!0}:(e[n]={description:""},await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} Added component "${n}" to model`),{added:!0,alreadyExists:!1})}async updateToken(n,t){let e=await this.loadModel();e||(e={tokens:{},components:{},rules:[]});let o=n.split("."),a=e;for(let p=0;p<o.length-1;p++){let f=o[p];(!a[f]||typeof a[f]!="object")&&(a[f]={}),a=a[f]}let r=o[o.length-1],l;try{l=JSON.parse(t)}catch(p){l=null}if(l&&typeof l=="object"&&l!==null&&"value"in l)a[r]=l;else{let p=a[r];p&&typeof p=="object"&&p!==null&&"value"in p?p.value=t:a[r]=t}return await ge(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ie} Updated token "${n}" \u2192 "${t.slice(0,80)}"`),{updated:!0}}async removeToken(n){let t=await this.loadModel();if(!t)return{removed:!1};let e=n.split("."),o=t;for(let r=0;r<e.length-1;r++){let l=e[r];if(!o[l]||typeof o[l]!="object")return{removed:!1};o=o[l]}let a=e[e.length-1];return a in o?(delete o[a],await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} Removed token "${n}" from model`),{removed:!0}):{removed:!1}}async removeComponent(n){let t=await this.loadModel();if(!t)return{removed:!1};let e=t.components;return!e||!e[n]?{removed:!1}:(delete e[n],await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} Removed component "${n}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let n=await this.loadIndex(),t=new Set(n.materializedIds),o=(await this.decisionStore.listDecisionIds()).filter(r=>!t.has(r));return o.length===0?[]:(await this.decisionStore.loadDecisions(o)).filter(r=>r.resolutions.some(l=>{var f;let p=(f=l.finalScope)!=null?f:l.inferredScope;return(p==null?void 0:p.breadth)==="pattern"}))}async run(){var n,t,e,o,a,r,l;if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;try{let p=await this.getUnmaterializedPatternDecisions();if(p.length===0)return{processedIds:[],success:!0};let f=p.map(U=>U.id);console.log(`${ie} Processing ${f.length} pattern-scoped decision(s): ${f.join(", ")}`),(t=(n=this.options).onEvent)==null||t.call(n,{type:"materialize_started",decisionIds:f});let I=await this.loadModel(),O=Qt(p,I),L=!0,m;try{let{result:U}=Oe(`mat-${Date.now()}`,{prompt:O,projectRoot:this.projectRoot,maxTurns:(e=this.options.maxTurns)!=null?e:5,maxBudgetUsd:(o=this.options.maxBudgetUsd)!=null?o:.5,allowedTools:["Read"],claudePath:(a=this.options.claudePath)!=null?a:"claude"}),N=await U;if(!N.success)L=!1,m=N.error,console.error(`${ie} Claude spawn error:`,m);else{let H=qt(N.text);H?(await ge(this.modelPath,JSON.stringify(H,null,2)),console.log(`${ie} Successfully materialized ${f.length} decision(s) \u2192 ${this.modelPath}`)):(L=!1,m="No <model> block found in response",console.error(`${ie} ${m}`))}}catch(U){L=!1,m=U instanceof Error?U.message:String(U),console.error(`${ie} Error:`,m)}let _=await this.loadIndex(),P=new Set(_.materializedIds);for(let U of f)P.add(U);return _.materializedIds=[...P],_.lastRunAt=Date.now(),_.lastRunDecisionIds=f,_.lastRunError=m!=null?m:null,await this.persistIndex(_),(l=(r=this.options).onEvent)==null||l.call(r,{type:"materialize_done",decisionIds:f,success:L,error:m}),{processedIds:f,success:L,error:m}}finally{this.running=!1}}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let n=await it(this.indexPath,"utf-8"),t=JSON.parse(n);return this.cachedIndex=t,t}catch(n){return this.cachedIndex=ce(ee({},Yt),{materializedIds:[],lastRunDecisionIds:[]}),this.cachedIndex}}async persistIndex(n){this.cachedIndex=n;try{await ge(this.indexPath,JSON.stringify(n,null,2))}catch(t){console.error(`${ie} Failed to write index:`,t)}}};function qt(i){let n=i.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!(n!=null&&n[1]))return null;try{let t=JSON.parse(n[1]);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch(t){return null}}function Qt(i,n){let t=i.map(o=>{let r=o.resolutions.filter(f=>{var O;let I=(O=f.finalScope)!=null?O:f.inferredScope;return(I==null?void 0:I.breadth)==="pattern"}).map(f=>{var m,_,P,U;let I=(m=f.finalScope)!=null?m:f.inferredScope,O=(_=I==null?void 0:I.target)!=null?_:"unknown",L=(U=(P=f.filesModified)==null?void 0:P.join(", "))!=null?U:"none";return`- **${f.summary}** [scope: pattern/${O}]
29
+ Files modified: ${L}`}).join(`
30
+ `),l=o.annotations.map(f=>f.instruction).filter(Boolean).join(`
31
+ `),p=o.gitDiff?`
5
32
  \`\`\`diff
6
- ${s.gitDiff.slice(0,2e3)}
7
- \`\`\``:"";return`### Decision ${s.id} (${new Date(s.createdAt).toISOString()})
8
- Page: ${s.url}
9
- ${i}
33
+ ${o.gitDiff.slice(0,2e3)}
34
+ \`\`\``:"";return`### Decision ${o.id} (${new Date(o.createdAt).toISOString()})
35
+ Page: ${o.url}
36
+ ${r}
10
37
  ${p}
11
- ${c?`
38
+ ${l?`
12
39
  Original instructions:
13
- ${c}`:""}`}).join(`
40
+ ${l}`:""}`}).join(`
14
41
 
15
42
  `);return`You are extracting a local design model from accumulated design decisions.
16
43
 
@@ -19,15 +46,15 @@ ${c}`:""}`}).join(`
19
46
  2. Determine what design tokens, component patterns, and rules to add or update.
20
47
  3. Output the complete updated model as a JSON object inside <model> tags.
21
48
 
22
- ${t?`## Current Model
49
+ ${n?`## Current Model
23
50
  \`\`\`json
24
- ${JSON.stringify(t,null,2)}
51
+ ${JSON.stringify(n,null,2)}
25
52
  \`\`\`
26
53
 
27
54
  Merge the new decisions into the existing model. Preserve existing entries that are not contradicted by new decisions.`:"No model exists yet. Create one from scratch based on the decisions below."}
28
55
 
29
56
  ## Design Decisions to Materialize
30
- ${n}
57
+ ${t}
31
58
 
32
59
  ## Output Format
33
60
  Output the full model inside <model> tags. The model is a JSON object with these sections:
@@ -66,39 +93,39 @@ Example:
66
93
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
67
94
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
68
95
  - bindings: Tailwind class names (without responsive prefixes) that use this token
69
- Include property and bindings when the decision context has class-level evidence.`}import{readFile as ct}from"fs/promises";import{homedir as lt}from"os";import{join as me}from"path";var Be=/popmelt/i;function Ue(){return{found:!1,name:null,scope:null,disabled:!1}}function Se(r,t,n=!1){return{found:!0,name:r,scope:t,disabled:n}}function Ce(r){for(let t of Object.keys(r))if(Be.test(t))return t;return null}async function _e(r){try{let t=await ct(r,"utf-8");return JSON.parse(t)}catch(t){return null}}async function Fe(r){let t=lt(),n=await _e(me(t,".claude.json"));if(n&&typeof n=="object"){let s=n;if(s.mcpServers&&typeof s.mcpServers=="object"){let a=Ce(s.mcpServers);if(a)return Se(a,"user")}if(s.projects&&typeof s.projects=="object"){let i=s.projects[r];if(i&&typeof i=="object"){let c=i;if(c.mcpServers&&typeof c.mcpServers=="object"){let p=Ce(c.mcpServers);if(p){let u=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(x=>Be.test(x));return Se(p,"project",u)}}}}}let e=await _e(me(r,".mcp.json"));if(e&&typeof e=="object"){let s=e;if(s.mcpServers&&typeof s.mcpServers=="object"){let i=Ce(s.mcpServers);if(i){let c=await it(r,i);return Se(i,"mcp.json",c)}}let a=Ce(s);if(a&&a!=="mcpServers"){let i=await it(r,a);return Se(a,"mcp.json",i)}}return Ue()}async function it(r,t){let n=me(r,".claude","settings.local.json"),e=await _e(n);if(e&&typeof e=="object"){let s=e;if(Array.isArray(s.disabledMcpjsonServers))return s.disabledMcpjsonServers.some(a=>a===t)}return!1}var qt=/^\[mcp_servers\.([^\]]+)\]/;function Yt(r){let t=r.split(`
70
- `),n=[],e=null;for(let s of t){let a=s.match(qt);a?(e&&n.push({name:e.name,body:e.bodyLines.join(`
71
- `)}),e={name:a[1],bodyLines:[]}):s.startsWith("[")?e&&(n.push({name:e.name,body:e.bodyLines.join(`
72
- `)}),e=null):e&&e.bodyLines.push(s)}return e&&n.push({name:e.name,body:e.bodyLines.join(`
73
- `)}),n}function Qt(r){return/enabled\s*=\s*false/i.test(r)}async function ze(r){let t=process.env.CODEX_HOME||me(lt(),".codex"),n=await at(me(t,"config.toml"),"user");if(n.found)return n;let e=await at(me(r,".codex","config.toml"),"project");return e.found?e:Ue()}async function at(r,t){try{let n=await ct(r,"utf-8"),e=Yt(n);for(let s of e)if(Be.test(s.name)){let a=Qt(s.body);return Se(s.name,t,a)}}catch(n){}return Ue()}import{mkdir as Vt,readFile as dt,writeFile as ut}from"fs/promises";import{homedir as pt}from"os";import{dirname as Kt,join as je}from"path";var ht="https://mcp.popmelt.com/mcp";async function ft(r=ht){let t=je(pt(),".claude.json"),n;try{let s=await dt(t,"utf-8");n=JSON.parse(s)}catch(s){n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let e=n.mcpServers;for(let s of Object.keys(e))if(/popmelt/i.test(s))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return e.popmelt={type:"http",url:r},await ut(t,JSON.stringify(n,null,2)+`
74
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function mt(r=ht){let t=process.env.CODEX_HOME||je(pt(),".codex"),n=je(t,"config.toml"),e;try{e=await dt(n,"utf-8")}catch(a){e=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(e))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Vt(Kt(n),{recursive:!0});let s=`
96
+ Include property and bindings when the decision context has class-level evidence.`}import{readFile as lt}from"fs/promises";import{homedir as dt}from"os";import{join as ye}from"path";var ze=/popmelt/i;function Le(){return{found:!1,name:null,scope:null,disabled:!1}}function Ie(i,n,t=!1){return{found:!0,name:i,scope:n,disabled:t}}function De(i){for(let n of Object.keys(i))if(ze.test(n))return n;return null}async function Fe(i){try{let n=await lt(i,"utf-8");return JSON.parse(n)}catch(n){return null}}async function He(i){let n=dt(),t=await Fe(ye(n,".claude.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=De(o.mcpServers);if(a)return Ie(a,"user")}if(o.projects&&typeof o.projects=="object"){let r=o.projects[i];if(r&&typeof r=="object"){let l=r;if(l.mcpServers&&typeof l.mcpServers=="object"){let p=De(l.mcpServers);if(p){let f=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(I=>ze.test(I));return Ie(p,"project",f)}}}}}let e=await Fe(ye(i,".mcp.json"));if(e&&typeof e=="object"){let o=e;if(o.mcpServers&&typeof o.mcpServers=="object"){let r=De(o.mcpServers);if(r){let l=await at(i,r);return Ie(r,"mcp.json",l)}}let a=De(o);if(a&&a!=="mcpServers"){let r=await at(i,a);return Ie(a,"mcp.json",r)}}return Le()}async function at(i,n){let t=ye(i,".claude","settings.local.json"),e=await Fe(t);if(e&&typeof e=="object"){let o=e;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(a=>a===n)}return!1}var Kt=/^\[mcp_servers\.([^\]]+)\]/;function Vt(i){let n=i.split(`
97
+ `),t=[],e=null;for(let o of n){let a=o.match(Kt);a?(e&&t.push({name:e.name,body:e.bodyLines.join(`
98
+ `)}),e={name:a[1],bodyLines:[]}):o.startsWith("[")?e&&(t.push({name:e.name,body:e.bodyLines.join(`
99
+ `)}),e=null):e&&e.bodyLines.push(o)}return e&&t.push({name:e.name,body:e.bodyLines.join(`
100
+ `)}),t}function Xt(i){return/enabled\s*=\s*false/i.test(i)}async function Ge(i){let n=process.env.CODEX_HOME||ye(dt(),".codex"),t=await ct(ye(n,"config.toml"),"user");if(t.found)return t;let e=await ct(ye(i,".codex","config.toml"),"project");return e.found?e:Le()}async function ct(i,n){try{let t=await lt(i,"utf-8"),e=Vt(t);for(let o of e)if(ze.test(o.name)){let a=Xt(o.body);return Ie(o.name,n,a)}}catch(t){}return Le()}import{mkdir as Zt,readFile as ut,writeFile as pt}from"fs/promises";import{homedir as ht}from"os";import{dirname as en,join as je}from"path";var ft="https://mcp.popmelt.com/mcp";async function mt(i=ft){let n=je(ht(),".claude.json"),t;try{let o=await ut(n,"utf-8");t=JSON.parse(o)}catch(o){t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let e=t.mcpServers;for(let o of Object.keys(e))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return e.popmelt={type:"http",url:i},await pt(n,JSON.stringify(t,null,2)+`
101
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function gt(i=ft){let n=process.env.CODEX_HOME||je(ht(),".codex"),t=je(n,"config.toml"),e;try{e=await ut(t,"utf-8")}catch(a){e=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(e))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Zt(en(t),{recursive:!0});let o=`
75
102
  [mcp_servers.popmelt]
76
- url = "${r}"
77
- `;return await ut(n,e+s,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function ge(r){let n=(r.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let e=n[1]||n[2],s=await Xt(r),a=Buffer.from(`--${e}`),i=Buffer.from(`--${e}--`),c,p,u,x,L,w,M,I,F,b,z,Q=[],ee=0,G=[];for(;ee<s.length;){let B=s.indexOf(a,ee);if(B===-1)break;let te=B+a.length;if(s.slice(B,B+i.length).equals(i))break;let J=te;s[J]===13&&s[J+1]===10&&(J+=2);let j=s.indexOf(`\r
103
+ url = "${i}"
104
+ `;return await pt(t,e+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function we(i){let t=(i.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let e=t[1]||t[2],o=await tn(i),a=Buffer.from(`--${e}`),r=Buffer.from(`--${e}--`),l,p,f,I,O,L,m,_,P,U,N,H,te=[],G=0,V=[];for(;G<o.length;){let E=o.indexOf(a,G);if(E===-1)break;let ne=E+a.length;if(o.slice(E,E+r.length).equals(r))break;let C=ne;o[C]===13&&o[C+1]===10&&(C+=2);let x=o.indexOf(`\r
78
105
  \r
79
- `,J);if(j===-1)break;let R=s.slice(J,j).toString("utf-8"),q=j+4,H=s.indexOf(a,q),K=H!==-1?H-2:s.length;G.push({headers:R,body:s.slice(q,K)}),ee=H!==-1?H:s.length}for(let B of G){let te=B.headers.match(/name="([^"]+)"/);if(!te)continue;let J=te[1];if(J==="screenshot")c=B.body;else if(J==="feedback")p=B.body.toString("utf-8");else if(J==="color")u=B.body.toString("utf-8");else if(J==="provider")x=B.body.toString("utf-8");else if(J==="model")L=B.body.toString("utf-8");else if(J==="goal")w=B.body.toString("utf-8");else if(J==="pageUrl")M=B.body.toString("utf-8");else if(J==="viewport")I=B.body.toString("utf-8");else if(J==="planId")F=B.body.toString("utf-8");else if(J==="manifest")b=B.body.toString("utf-8");else if(J==="tasks")z=B.body.toString("utf-8");else if(J.startsWith("image-")){let j=J.split("-"),R=parseInt(j[j.length-1],10),q=j.slice(1,-1).join("-");q&&!isNaN(R)&&Q.push({annotationId:q,index:R,data:B.body})}}if(!c)throw new Error("Missing screenshot field");return p||(p=""),{screenshot:c,feedback:p,color:u,provider:x,model:L,goal:w,pageUrl:M,viewport:I,planId:F,manifest:b,tasks:z,pastedImages:Q}}function Xt(r){return new Promise((t,n)=>{let e=[];r.on("data",s=>e.push(s)),r.on("end",()=>t(Buffer.concat(e))),r.on("error",n)})}function xe(r,t){var e,s;let n=[];if(r.annotations.length>0){n.push("## Annotations");for(let a of r.annotations){let i=a.elements.map(u=>{let x=[u.selector];return u.reactComponent&&x.push(`(${u.reactComponent})`),x.join(" ")}).join(", "),c=a.instruction||"No text";n.push(`- id=${a.id} [${a.type}] ${c} \u2192 Elements: ${i||"none"}`);let p=t==null?void 0:t[a.id];if(p&&p.length>0)for(let u of p)n.push(` Attached image: use the Read tool to view ${u}`)}}if(r.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let a of r.styleModifications){let i=(e=a.element)!=null&&e.reactComponent?`(${a.element.reactComponent})`:"";for(let c of a.changes)n.push(`- ${a.selector} ${i}: ${c.property} ${c.original} \u2192 ${c.modified}`)}}if((s=r.spacingTokenChanges)!=null&&s.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let a of r.spacingTokenChanges){n.push(`
80
- ### ${a.tokenName}: ${a.originalPx}px \u2192 ${a.newPx}px`);for(let i of a.affectedElements){let c=i.reactComponent?` (${i.reactComponent})`:"";i.matchedClass&&i.suggestedClass?n.push(`- ${i.selector}${c}: \`${i.matchedClass}\` \u2192 \`${i.suggestedClass}\``):n.push(`- ${i.selector}${c}: ${i.property} ${a.originalPx}px \u2192 ${a.newPx}px`),n.push(` class="${i.className}"`)}}}if(r.inspectedElement){let a=r.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let i=[a.selector];a.reactComponent&&i.push(`(${a.reactComponent})`),a.context&&i.push(`in ${a.context}`),a.textContent&&i.push(`"${a.textContent.slice(0,80)}"`),n.push(`- ${i.join(" ")}`)}return n.join(`
81
- `)}function gt(r,t,n){var a;let e=[];if(e.push("You are reviewing a UI screenshot with developer annotations."),e.push(""),(n==null?void 0:n.provider)!=="codex"&&(e.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),e.push("")),e.push(`The developer annotated their running app at ${t.url} (${t.viewport.width}x${t.viewport.height}).`),n!=null&&n.threadHistory&&n.threadHistory.length>0){e.push(""),e.push("## Previous Conversation");let i=0;for(let c of n.threadHistory)if(c.role==="human")i++,c.replyToQuestion?(e.push(`### Round ${i} (human) \u2014 reply`),e.push(`"${c.replyToQuestion}"`)):(e.push(`### Round ${i} (human)`),c.feedbackSummary&&e.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&e.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)e.push(`### Round ${i} (assistant) \u2014 question`),e.push(`"${c.question}"`);else{if(e.push(`### Round ${i} (assistant)`),c.responseText&&e.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let p of c.resolutions){let u=(a=p.finalScope)!=null?a:p.inferredScope,x=u?` [${u.breadth} ${u.target}]`:"";e.push(`- ${p.annotationId}: ${p.status}${x} \u2014 ${p.summary}`),p.filesModified&&p.filesModified.length>0&&e.push(` Files: ${p.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&e.push(`Tools used: ${c.toolsUsed.join(", ")}`)}e.push(""),e.push("The current round is shown in full below.")}if(n!=null&&n.designModel){e.push(""),e.push("## Established Design Policies"),e.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let i=n.designModel.rules;if(Array.isArray(i)&&i.length>0){e.push(""),e.push("Rules:");for(let u of i)typeof u=="string"&&e.push(`- ${u}`)}let c=n.designModel.tokens;c&&typeof c=="object"&&(e.push(""),e.push("Design tokens:"),e.push("```json"),e.push(JSON.stringify(c,null,2)),e.push("```"));let p=n.designModel.components;p&&typeof p=="object"&&(e.push(""),e.push("Component patterns:"),e.push("```json"),e.push(JSON.stringify(p,null,2)),e.push("```")),e.push(""),e.push("### Novel Pattern Detection"),e.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),e.push("<novel>"),e.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),e.push("</novel>"),e.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),e.push("- `element`: What you are styling or creating"),e.push("- `decision`: What you decided to do (specific values)"),e.push("- `reason`: Why this is novel (what is missing from the model)"),e.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}n!=null&&n.designModel||(e.push(""),e.push("## Design Context"),e.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code."));let s=xe(t,n==null?void 0:n.imagePaths);return s&&(e.push(""),e.push(s)),e.push(""),e.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),e.push(""),e.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e.push(""),e.push("## Resolution"),e.push("After completing all work, output a resolution block listing what you did for each annotation:"),e.push("<resolution>"),e.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),e.push("</resolution>"),e.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),e.push(""),e.push("### Scope classification"),e.push("Each resolution MUST include scope fields:"),e.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),e.push("- `inferredScope`: What scope the change actually has, based on what you modified."),e.push("Scope has two dimensions:"),e.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),e.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),e.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),e.push("If you cannot confidently determine scope, set it to null."),e.push(""),e.push("## Questions"),e.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),e.push('<question>What do you mean by "..."?</question>'),e.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),e.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),e.join(`
82
- `)}function yt(r){var n;let t=r.match(/<question>\s*([\s\S]*?)\s*<\/question>/);return(n=t==null?void 0:t[1])!=null?n:null}function wt(r,t,n,e){let s=[];s.push("You are continuing work on a UI based on the developer's reply to your question."),s.push(""),n!=="codex"&&s.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`);let a=t.find(i=>i.role==="human"&&i.feedbackContext);if(a!=null&&a.feedbackContext&&(s.push(""),s.push(a.feedbackContext)),t.length>0){s.push(""),s.push("## Conversation History");let i=0;for(let c of t)c.role==="human"?(i++,c.replyToQuestion?(s.push(`### Round ${i} (human) \u2014 reply`),s.push(`"${c.replyToQuestion}"`)):(s.push(`### Round ${i} (human)`),c.feedbackSummary&&s.push(`Annotations: ${c.feedbackSummary}`))):c.question?(s.push(`### Round ${i} (assistant) \u2014 question`),s.push(`"${c.question}"`)):(s.push(`### Round ${i} (assistant)`),c.responseText&&s.push(`Response: ${c.responseText}`))}if(s.push(""),s.push("The developer answered your question. Continue working based on their reply."),s.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),s.push(""),s.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e&&e.length>0){s.push(""),s.push("## Attached Images"),s.push("The developer attached reference images with their reply:");for(let i of e)s.push(`Attached image: use the Read tool to view the image at: ${i}`)}return s.push(""),s.push("## Resolution"),s.push("After completing all work, output a resolution block listing what you did for each annotation:"),s.push("<resolution>"),s.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),s.push("</resolution>"),s.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),s.push(""),s.push("### Scope classification"),s.push("Each resolution MUST include scope fields:"),s.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),s.push("- `inferredScope`: What scope the change actually has, based on what you modified."),s.push("Scope has two dimensions:"),s.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),s.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),s.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),s.push("If you cannot confidently determine scope, set it to null."),s.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),s.push(""),s.push("## Questions"),s.push("If you still need clarification, output:"),s.push("<question>Your question here</question>"),s.push("You may output BOTH a <resolution> and a <question> in the same response."),s.join(`
83
- `)}function Zt(r){if(typeof r!="object"||r===null)return!1;let t=r;return(t.breadth==="instance"||t.breadth==="pattern")&&(t.target==="element"||t.target==="component"||t.target==="token")}function vt(r){if(typeof r!="object"||r===null||typeof r.annotationId!="string"||r.status!=="resolved"&&r.status!=="needs_review"||typeof r.summary!="string")return!1;let t=r;for(let n of["declaredScope","inferredScope","finalScope"])if(t[n]!==void 0&&t[n]!==null&&!Zt(t[n]))return!1;return!0}function St(r){let t=r.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!t||!t[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(vt):[]}catch(n){return[]}}function xt(r){let t=[],n=/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g,e;for(;(e=n.exec(r))!==null;)if(e[1])try{let s=JSON.parse(e[1]);Array.isArray(s)&&t.push(...s.filter(vt))}catch(s){}return t}function It(r){let t=r.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!(t!=null&&t[1]))return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(e=>{if(typeof e!="object"||e===null)return!1;let s=e;return(s.category==="token"||s.category==="component"||s.category==="element")&&typeof s.element=="string"&&typeof s.decision=="string"&&typeof s.reason=="string"}):[]}catch(n){return[]}}function kt(r,t,n,e,s,a){let i=[];return i.push("You are a UI design planner. You are looking at a full-page screenshot of a web application."),i.push(""),i.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),i.push(""),i.push(`Page: ${n}`),i.push(`Viewport: ${e.width}x${e.height}`),s&&(i.push(""),i.push("## Page Elements (ground truth)"),i.push("Below is a structured inventory of actual DOM elements on this page. Cross-reference"),i.push("against this list \u2014 do NOT reference elements that aren't listed here."),i.push(""),i.push("<manifest>"),i.push(s),i.push("</manifest>")),a&&(i.push(""),i.push("## Developer Context"),i.push("The developer has the following annotations and style changes on their canvas. Factor these into your plan:"),i.push(a)),i.push(""),i.push("## Goal"),i.push(t),i.push(""),i.push("## Your Task"),i.push("Analyze the screenshot and decompose the goal into specific, element-level tasks."),i.push("Each task targets a specific region of the page and gives a clear instruction for a worker agent."),i.push(""),i.push("Output your plan as a JSON array inside a <plan> tag. Each task has:"),i.push('- `id`: A short unique identifier (e.g., "t1", "t2")'),i.push("- `instruction`: Clear, specific instruction for a worker agent (what to change and how)"),i.push("- `region`: Bounding box in page coordinates `{x, y, width, height}` \u2014 where (x,y) is top-left corner"),i.push("- `priority`: Optional 1-5 (1=highest). Tasks with no dependency can share a priority level."),i.push(""),i.push("Example:"),i.push("<plan>"),i.push("["),i.push(' {"id":"t1","instruction":"Increase heading font-size to 48px and change font-weight to 700","region":{"x":100,"y":50,"width":600,"height":80},"priority":1},'),i.push(' {"id":"t2","instruction":"Add a subtle box-shadow to the card container","region":{"x":80,"y":200,"width":640,"height":300},"priority":2}'),i.push("]"),i.push("</plan>"),i.push(""),i.push("Guidelines:"),i.push("- CRITICAL: Cross-check all element references against the <manifest>. Only reference elements that actually exist. Use the manifest's text content, component names, and bounding rects for precise instructions."),i.push('- Be specific about values (colors, sizes, spacing) rather than vague ("make it look better")'),i.push("- Each task should be independently actionable by a worker that can only see its region"),i.push("- Regions should tightly bound the relevant UI element(s)"),i.push("- Keep tasks atomic \u2014 one change per task, not multiple unrelated changes"),i.push("- Order by priority: structural changes first, then visual polish"),i.push("- If the goal can be accomplished as a single change, return a plan with just one task. Only decompose when the goal genuinely requires multiple independent changes."),i.push("- If the goal is unclear or you need more context, output a question instead:"),i.push("<question>Your question here</question>"),i.push(""),i.push("Do NOT modify any files. You are a planner only \u2014 output a <plan> or <question>, nothing else."),i.join(`
84
- `)}function Pt(r){let t=r.match(/<plan>\s*([\s\S]*?)\s*<\/plan>/);if(!(t!=null&&t[1]))return null;try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(e=>{if(typeof e!="object"||e===null)return!1;let s=e;if(typeof s.id!="string"||typeof s.instruction!="string"||typeof s.region!="object"||s.region===null)return!1;let a=s.region;return typeof a.x=="number"&&typeof a.y=="number"&&typeof a.width=="number"&&typeof a.height=="number"}):null}catch(n){return null}}function bt(r,t,n){let e=[];e.push("You are reviewing whether a series of UI changes achieved the original design goal."),e.push(""),e.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),e.push(""),e.push("## Original Goal"),e.push(t),e.push(""),e.push("## Completed Tasks");for(let s of n)e.push(`- [${s.id}] ${s.instruction} \u2192 ${s.summary}`);return e.push(""),e.push("## Your Task"),e.push("Look at the current screenshot and determine if the goal has been achieved."),e.push("Output your verdict inside a <review> tag:"),e.push("<review>"),e.push('{"verdict":"pass","summary":"The changes look good..."}'),e.push("</review>"),e.push(""),e.push("Or if issues remain:"),e.push("<review>"),e.push('{"verdict":"fail","summary":"Some issues remain...","issues":["Issue 1","Issue 2"]}'),e.push("</review>"),e.push(""),e.push("Do NOT modify any files. Output only a <review> block."),e.join(`
85
- `)}function Tt(r,t,n,e,s){let a=[];a.push("You are implementing a series of UI changes on a web application."),a.push(""),s!=="codex"&&(a.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),a.push("")),a.push(`Page: ${n} (${e.width}x${e.height})`),a.push(""),a.push("## Tasks"),a.push("Each task targets a specific region of the page. Complete them in order."),a.push("");for(let i of t){if(a.push(`### Task ${i.planTaskId} (annotationId: ${i.annotationId})`),a.push(`Instruction: ${i.instruction}`),a.push(`Region: (${i.region.x}, ${i.region.y}) ${i.region.width}x${i.region.height}`),i.linkedSelector&&a.push(`Target element: ${i.linkedSelector}`),i.elements&&i.elements.length>0){let c=i.elements.map(p=>{let u=[p.selector];return p.reactComponent&&u.push(`(${p.reactComponent})`),u.join(" ")}).join(", ");a.push(`Elements: ${c}`)}a.push("")}return a.push("## Instructions"),a.push("- Apply each change to the source files \u2014 the dev server has HMR so changes appear immediately."),a.push("- IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source."),a.push("- You may use parallel subagents (Task tool) for independent changes, or work serially \u2014 use your judgment."),a.push(""),a.push("## Resolution"),a.push("CRITICAL: After completing EACH task, immediately output a <resolution> block for that task."),a.push("Do NOT wait until all tasks are done \u2014 output each resolution as soon as that task is finished."),a.push("<resolution>"),a.push('[{"annotationId":"<annotationId>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),a.push("</resolution>"),a.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),a.push(""),a.push("### Scope classification"),a.push("Each resolution MUST include scope fields:"),a.push("- `declaredScope`: What scope the task instruction implies. null if no signal."),a.push("- `inferredScope`: What scope the change actually has, based on what you modified."),a.push("Scope has two dimensions:"),a.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),a.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),a.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),a.push("If you cannot confidently determine scope, set it to null."),a.join(`
86
- `)}function Rt(r){let t=r.match(/<review>\s*([\s\S]*?)\s*<\/review>/);if(!(t!=null&&t[1]))return null;try{let n=JSON.parse(t[1]);return typeof n!="object"||n===null||n.verdict!=="pass"&&n.verdict!=="fail"||typeof n.summary!="string"?null:{verdict:n.verdict,summary:n.summary,issues:Array.isArray(n.issues)?n.issues.filter(e=>typeof e=="string"):void 0}}catch(n){return null}}var Ee=class{constructor(t=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.maxConcurrency=t}setProcessor(t){this.processor=t}get active(){let t=this.activeJobs.values().next();return t.done?null:t.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(t,n){n?this.activeProcesses.set(t,n):this.activeProcesses.delete(t)}enqueue(t){return this.queue.push(t),this.processNext(),this.queue.length+this.activeJobs.size}addListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}broadcast(t,n){for(let e of this.listeners)e(t,n)}cancelJob(t){let n=this.activeProcesses.get(t),e=this.activeJobs.get(t);return!n||!e?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(t),this.activeJobs.delete(t),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,message:"Cancelled by user"},e.id),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let t=Array.from(this.activeJobs.keys());for(let n of t)this.cancelJob(n);return!0}destroy(){for(let t of this.activeProcesses.values())t.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let t=this.queue.shift();this.activeJobs.set(t.id,t),t.status="running",this.broadcast({type:"job_started",jobId:t.id,position:0},t.id),this.processor(t).catch(n=>{t.status="error",t.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:t.id,message:t.error},t.id)}).finally(()=>{this.activeJobs.delete(t.id),this.activeProcesses.delete(t.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id)})}}};import{mkdir as en,readFile as tn,writeFile as nn}from"fs/promises";import{dirname as sn,join as on}from"path";var rn={version:1,threads:{}},De=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=on(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await tn(this.filePath,"utf-8"),n=JSON.parse(t);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch(t){}return this.cache=ae(Z({},rn),{threads:{}}),this.cache}async getThread(t){var e;return(e=(await this.load()).threads[t])!=null?e:null}async findContinuationThread(t){if(t.length===0)return null;let n=await this.load(),e=new Set(t);for(let s of Object.values(n.threads))if(s.elementIdentifiers.some(i=>e.has(i)))return s;return null}async createThread(t,n){let e=await this.load(),s={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=s,await this.persist(),s}async appendMessage(t,n){let s=(await this.load()).threads[t];s&&(s.messages.push(n),s.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let s=(await this.load()).threads[t];if(!s)return;let a=new Set(s.elementIdentifiers);for(let i of n)a.has(i)||s.elementIdentifiers.push(i);s.updatedAt=Date.now(),await this.persist()}async getThreadHistory(t,n=6){let e=await this.getThread(t);return!e||e.messages.length===0?[]:e.messages.length<=n?e.messages:[e.messages[0],...e.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await en(sn(this.filePath),{recursive:!0}),await nn(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var fn=1111,mn=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],gn=1800*1e3,yn=3600*1e3;function wn(r){if(!r)return!1;try{let t=new URL(r);return t.hostname==="localhost"||t.hostname==="127.0.0.1"}catch(t){return!1}}function vn(r,t){let n=r.headers.origin;wn(n)&&(t.setHeader("Access-Control-Allow-Origin",n),t.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type"))}function g(r,t,n){r.writeHead(t,{"Content-Type":"application/json"}),r.end(JSON.stringify(n))}function Sn(r,t){if(!r)return t;let n=r.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return t;let[,e,s,a]=n;return`\x1B[38;2;${parseInt(e,16)};${parseInt(s,16)};${parseInt(a,16)}m${t}\x1B[0m`}function $t(r,t){try{r.res.write(`event: ${t.type}
87
- data: ${JSON.stringify(t)}
106
+ `,C);if(x===-1)break;let W=o.slice(C,x).toString("utf-8"),T=x+4,K=o.indexOf(a,T),me=K!==-1?K-2:o.length;V.push({headers:W,body:o.slice(T,me)}),G=K!==-1?K:o.length}for(let E of V){let ne=E.headers.match(/name="([^"]+)"/);if(!ne)continue;let C=ne[1];if(C==="screenshot")l=E.body;else if(C==="feedback")p=E.body.toString("utf-8");else if(C==="color")f=E.body.toString("utf-8");else if(C==="provider")I=E.body.toString("utf-8");else if(C==="model")O=E.body.toString("utf-8");else if(C==="goal")L=E.body.toString("utf-8");else if(C==="pageUrl")m=E.body.toString("utf-8");else if(C==="viewport")_=E.body.toString("utf-8");else if(C==="planId")P=E.body.toString("utf-8");else if(C==="manifest")U=E.body.toString("utf-8");else if(C==="tasks")N=E.body.toString("utf-8");else if(C==="sourceId")H=E.body.toString("utf-8");else if(C.startsWith("image-")){let x=C.split("-"),W=parseInt(x[x.length-1],10),T=x.slice(1,-1).join("-");T&&!isNaN(W)&&te.push({annotationId:T,index:W,data:E.body})}}if(!l)throw new Error("Missing screenshot field");return p||(p=""),{screenshot:l,feedback:p,color:f,provider:I,model:O,goal:L,pageUrl:m,viewport:_,planId:P,manifest:U,tasks:N,sourceId:H,pastedImages:te}}function tn(i){return new Promise((n,t)=>{let e=[];i.on("data",o=>e.push(o)),i.on("end",()=>n(Buffer.concat(e))),i.on("error",t)})}function xe(i,n){var e,o;let t=[];if(i.annotations.length>0){t.push("## Annotations");for(let a of i.annotations){let r=a.elements.map(f=>{let I=[f.selector];return f.reactComponent&&I.push(`(${f.reactComponent})`),I.join(" ")}).join(", "),l=a.instruction||"No text";t.push(`- id=${a.id} [${a.type}] ${l} \u2192 Elements: ${r||"none"}`);let p=n==null?void 0:n[a.id];if(p&&p.length>0)for(let f of p)t.push(` Attached image: use the Read tool to view ${f}`)}}if(i.styleModifications.length>0){t.push(""),t.push("## Style Changes (make permanent in source)"),t.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let a of i.styleModifications){let r=(e=a.element)!=null&&e.reactComponent?`(${a.element.reactComponent})`:"";for(let l of a.changes)t.push(`- ${a.selector} ${r}: ${l.property} ${l.original} \u2192 ${l.modified}`)}}if((o=i.spacingTokenChanges)!=null&&o.length){t.push(""),t.push("## Spacing Token Changes"),t.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let a of i.spacingTokenChanges){t.push(`
107
+ ### ${a.tokenName}: ${a.originalPx}px \u2192 ${a.newPx}px`);for(let r of a.affectedElements){let l=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?t.push(`- ${r.selector}${l}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):t.push(`- ${r.selector}${l}: ${r.property} ${a.originalPx}px \u2192 ${a.newPx}px`),t.push(` class="${r.className}"`)}}}if(i.inspectedElement){let a=i.inspectedElement;t.push(""),t.push("## Inspected Element"),t.push("The developer has this element selected in the inspector:");let r=[a.selector];a.reactComponent&&r.push(`(${a.reactComponent})`),a.context&&r.push(`in ${a.context}`),a.textContent&&r.push(`"${a.textContent.slice(0,80)}"`),t.push(`- ${r.join(" ")}`)}return t.join(`
108
+ `)}function yt(i,n,t){var a;let e=[];if(e.push("You are reviewing a UI screenshot with developer annotations."),e.push(""),(t==null?void 0:t.provider)!=="codex"&&(e.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`),e.push("")),e.push(`The developer annotated their running app at ${n.url} (${n.viewport.width}x${n.viewport.height}).`),t!=null&&t.threadHistory&&t.threadHistory.length>0){e.push(""),e.push("## Previous Conversation");let r=0;for(let l of t.threadHistory)if(l.role==="human")r++,l.replyToQuestion?(e.push(`### Round ${r} (human) \u2014 reply`),e.push(`"${l.replyToQuestion}"`)):(e.push(`### Round ${r} (human)`),l.feedbackSummary&&e.push(`Annotations: ${l.feedbackSummary}`),l.annotationIds&&l.annotationIds.length>0&&e.push(`Annotation IDs: ${l.annotationIds.join(", ")}`));else if(l.question)e.push(`### Round ${r} (assistant) \u2014 question`),e.push(`"${l.question}"`);else{if(e.push(`### Round ${r} (assistant)`),l.responseText&&e.push(`Response: ${l.responseText}`),l.resolutions&&l.resolutions.length>0)for(let p of l.resolutions){let f=(a=p.finalScope)!=null?a:p.inferredScope,I=f?` [${f.breadth} ${f.target}]`:"";e.push(`- ${p.annotationId}: ${p.status}${I} \u2014 ${p.summary}`),p.filesModified&&p.filesModified.length>0&&e.push(` Files: ${p.filesModified.join(", ")}`)}l.toolsUsed&&l.toolsUsed.length>0&&e.push(`Tools used: ${l.toolsUsed.join(", ")}`)}e.push(""),e.push("The current round is shown in full below.")}if(t!=null&&t.designModel){e.push(""),e.push("## Established Design Policies"),e.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let r=t.designModel.rules;if(Array.isArray(r)&&r.length>0){e.push(""),e.push("Rules:");for(let f of r)typeof f=="string"&&e.push(`- ${f}`)}let l=t.designModel.tokens;l&&typeof l=="object"&&(e.push(""),e.push("Design tokens:"),e.push("```json"),e.push(JSON.stringify(l,null,2)),e.push("```"));let p=t.designModel.components;p&&typeof p=="object"&&(e.push(""),e.push("Component patterns:"),e.push("```json"),e.push(JSON.stringify(p,null,2)),e.push("```")),e.push(""),e.push("### Novel Pattern Detection"),e.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),e.push("<novel>"),e.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),e.push("</novel>"),e.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),e.push("- `element`: What you are styling or creating"),e.push("- `decision`: What you decided to do (specific values)"),e.push("- `reason`: Why this is novel (what is missing from the model)"),e.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}t!=null&&t.designModel||(e.push(""),e.push("## Design Context"),e.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code."));let o=xe(n,t==null?void 0:t.imagePaths);return o&&(e.push(""),e.push(o)),e.push(""),e.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),e.push(""),e.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e.push(""),e.push("## Resolution"),e.push("After completing all work, output a resolution block listing what you did for each annotation:"),e.push("<resolution>"),e.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),e.push("</resolution>"),e.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),e.push(""),e.push("### Scope classification"),e.push("Each resolution MUST include scope fields:"),e.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),e.push("- `inferredScope`: What scope the change actually has, based on what you modified."),e.push("Scope has two dimensions:"),e.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),e.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),e.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),e.push("If you cannot confidently determine scope, set it to null."),e.push(""),e.push("## Questions"),e.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),e.push('<question>What do you mean by "..."?</question>'),e.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),e.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),e.join(`
109
+ `)}function wt(i){var t;let n=i.match(/<question>\s*([\s\S]*?)\s*<\/question>/);return(t=n==null?void 0:n[1])!=null?t:null}function vt(i,n,t,e){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),t!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`);let a=n.find(r=>r.role==="human"&&r.feedbackContext);if(a!=null&&a.feedbackContext&&(o.push(""),o.push(a.feedbackContext)),n.length>0){o.push(""),o.push("## Conversation History");let r=0;for(let l of n)l.role==="human"?(r++,l.replyToQuestion?(o.push(`### Round ${r} (human) \u2014 reply`),o.push(`"${l.replyToQuestion}"`)):(o.push(`### Round ${r} (human)`),l.feedbackSummary&&o.push(`Annotations: ${l.feedbackSummary}`))):l.question?(o.push(`### Round ${r} (assistant) \u2014 question`),o.push(`"${l.question}"`)):(o.push(`### Round ${r} (assistant)`),l.responseText&&o.push(`Response: ${l.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e&&e.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let r of e)o.push(`Attached image: use the Read tool to view the image at: ${r}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output a resolution block listing what you did for each annotation:"),o.push("<resolution>"),o.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),o.push("</resolution>"),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
110
+ `)}function nn(i){if(typeof i!="object"||i===null)return!1;let n=i;return(n.breadth==="instance"||n.breadth==="pattern")&&(n.target==="element"||n.target==="component"||n.target==="token")}function St(i){if(typeof i!="object"||i===null||typeof i.annotationId!="string"||i.status!=="resolved"&&i.status!=="needs_review"||typeof i.summary!="string")return!1;let n=i;for(let t of["declaredScope","inferredScope","finalScope"])if(n[t]!==void 0&&n[t]!==null&&!nn(n[t]))return!1;return!0}function It(i){let n=i.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!n||!n[1])return[];try{let t=JSON.parse(n[1]);return Array.isArray(t)?t.filter(St):[]}catch(t){return[]}}function xt(i){let n=[],t=/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g,e;for(;(e=t.exec(i))!==null;)if(e[1])try{let o=JSON.parse(e[1]);Array.isArray(o)&&n.push(...o.filter(St))}catch(o){}return n}function Pt(i){let n=i.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!(n!=null&&n[1]))return[];try{let t=JSON.parse(n[1]);return Array.isArray(t)?t.filter(e=>{if(typeof e!="object"||e===null)return!1;let o=e;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch(t){return[]}}function kt(i,n,t,e,o,a){let r=[];return r.push("You are a UI design planner. You are looking at a full-page screenshot of a web application."),r.push(""),r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`),r.push(""),r.push(`Page: ${t}`),r.push(`Viewport: ${e.width}x${e.height}`),o&&(r.push(""),r.push("## Page Elements (ground truth)"),r.push("Below is a structured inventory of actual DOM elements on this page. Cross-reference"),r.push("against this list \u2014 do NOT reference elements that aren't listed here."),r.push(""),r.push("<manifest>"),r.push(o),r.push("</manifest>")),a&&(r.push(""),r.push("## Developer Context"),r.push("The developer has the following annotations and style changes on their canvas. Factor these into your plan:"),r.push(a)),r.push(""),r.push("## Goal"),r.push(n),r.push(""),r.push("## Your Task"),r.push("Analyze the screenshot and decompose the goal into specific, element-level tasks."),r.push("Each task targets a specific region of the page and gives a clear instruction for a worker agent."),r.push(""),r.push("Output your plan as a JSON array inside a <plan> tag. Each task has:"),r.push('- `id`: A short unique identifier (e.g., "t1", "t2")'),r.push("- `instruction`: Clear, specific instruction for a worker agent (what to change and how)"),r.push("- `region`: Bounding box in page coordinates `{x, y, width, height}` \u2014 where (x,y) is top-left corner"),r.push("- `priority`: Optional 1-5 (1=highest). Tasks with no dependency can share a priority level."),r.push(""),r.push("Example:"),r.push("<plan>"),r.push("["),r.push(' {"id":"t1","instruction":"Increase heading font-size to 48px and change font-weight to 700","region":{"x":100,"y":50,"width":600,"height":80},"priority":1},'),r.push(' {"id":"t2","instruction":"Add a subtle box-shadow to the card container","region":{"x":80,"y":200,"width":640,"height":300},"priority":2}'),r.push("]"),r.push("</plan>"),r.push(""),r.push("Guidelines:"),r.push("- CRITICAL: Cross-check all element references against the <manifest>. Only reference elements that actually exist. Use the manifest's text content, component names, and bounding rects for precise instructions."),r.push('- Be specific about values (colors, sizes, spacing) rather than vague ("make it look better")'),r.push("- Each task should be independently actionable by a worker that can only see its region"),r.push("- Regions should tightly bound the relevant UI element(s)"),r.push("- Keep tasks atomic \u2014 one change per task, not multiple unrelated changes"),r.push("- Order by priority: structural changes first, then visual polish"),r.push("- If the goal can be accomplished as a single change, return a plan with just one task. Only decompose when the goal genuinely requires multiple independent changes."),r.push("- If the goal is unclear or you need more context, output a question instead:"),r.push("<question>Your question here</question>"),r.push(""),r.push("Do NOT modify any files. You are a planner only \u2014 output a <plan> or <question>, nothing else."),r.join(`
111
+ `)}function bt(i){let n=i.match(/<plan>\s*([\s\S]*?)\s*<\/plan>/);if(!(n!=null&&n[1]))return null;try{let t=JSON.parse(n[1]);return Array.isArray(t)?t.filter(e=>{if(typeof e!="object"||e===null)return!1;let o=e;if(typeof o.id!="string"||typeof o.instruction!="string"||typeof o.region!="object"||o.region===null)return!1;let a=o.region;return typeof a.x=="number"&&typeof a.y=="number"&&typeof a.width=="number"&&typeof a.height=="number"}):null}catch(t){return null}}function Tt(i,n,t){let e=[];e.push("You are reviewing whether a series of UI changes achieved the original design goal."),e.push(""),e.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`),e.push(""),e.push("## Original Goal"),e.push(n),e.push(""),e.push("## Completed Tasks");for(let o of t)e.push(`- [${o.id}] ${o.instruction} \u2192 ${o.summary}`);return e.push(""),e.push("## Your Task"),e.push("Look at the current screenshot and determine if the goal has been achieved."),e.push("Output your verdict inside a <review> tag:"),e.push("<review>"),e.push('{"verdict":"pass","summary":"The changes look good..."}'),e.push("</review>"),e.push(""),e.push("Or if issues remain:"),e.push("<review>"),e.push('{"verdict":"fail","summary":"Some issues remain...","issues":["Issue 1","Issue 2"]}'),e.push("</review>"),e.push(""),e.push("Do NOT modify any files. Output only a <review> block."),e.join(`
112
+ `)}function Rt(i,n,t,e,o){let a=[];a.push("You are implementing a series of UI changes on a web application."),a.push(""),o!=="codex"&&(a.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`),a.push("")),a.push(`Page: ${t} (${e.width}x${e.height})`),a.push(""),a.push("## Tasks"),a.push("Each task targets a specific region of the page. Complete them in order."),a.push("");for(let r of n){if(a.push(`### Task ${r.planTaskId} (annotationId: ${r.annotationId})`),a.push(`Instruction: ${r.instruction}`),a.push(`Region: (${r.region.x}, ${r.region.y}) ${r.region.width}x${r.region.height}`),r.linkedSelector&&a.push(`Target element: ${r.linkedSelector}`),r.elements&&r.elements.length>0){let l=r.elements.map(p=>{let f=[p.selector];return p.reactComponent&&f.push(`(${p.reactComponent})`),f.join(" ")}).join(", ");a.push(`Elements: ${l}`)}a.push("")}return a.push("## Instructions"),a.push("- Apply each change to the source files \u2014 the dev server has HMR so changes appear immediately."),a.push("- IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source."),a.push("- You may use parallel subagents (Task tool) for independent changes, or work serially \u2014 use your judgment."),a.push(""),a.push("## Resolution"),a.push("CRITICAL: After completing EACH task, immediately output a <resolution> block for that task."),a.push("Do NOT wait until all tasks are done \u2014 output each resolution as soon as that task is finished."),a.push("<resolution>"),a.push('[{"annotationId":"<annotationId>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),a.push("</resolution>"),a.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),a.push(""),a.push("### Scope classification"),a.push("Each resolution MUST include scope fields:"),a.push("- `declaredScope`: What scope the task instruction implies. null if no signal."),a.push("- `inferredScope`: What scope the change actually has, based on what you modified."),a.push("Scope has two dimensions:"),a.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),a.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),a.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),a.push("If you cannot confidently determine scope, set it to null."),a.join(`
113
+ `)}function $t(i){let n=i.match(/<review>\s*([\s\S]*?)\s*<\/review>/);if(!(n!=null&&n[1]))return null;try{let t=JSON.parse(n[1]);return typeof t!="object"||t===null||t.verdict!=="pass"&&t.verdict!=="fail"||typeof t.summary!="string"?null:{verdict:t.verdict,summary:t.summary,issues:Array.isArray(t.issues)?t.issues.filter(e=>typeof e=="string"):void 0}}catch(t){return null}}var Je=class{constructor(n=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.maxConcurrency=n}setProcessor(n){this.processor=n}get active(){let n=this.activeJobs.values().next();return n.done?null:n.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(n,t){t?this.activeProcesses.set(n,t):this.activeProcesses.delete(n)}enqueue(n){return this.queue.push(n),this.processNext(),this.queue.length+this.activeJobs.size}addListener(n){return this.listeners.add(n),()=>this.listeners.delete(n)}broadcast(n,t,e){for(let o of this.listeners)o(n,t,e)}cancelJob(n){let t=this.activeProcesses.get(n),e=this.activeJobs.get(n);return!t||!e?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(n),this.activeJobs.delete(n),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,message:"Cancelled by user",cancelled:!0},e.id,e.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let n=Array.from(this.activeJobs.keys());for(let t of n)this.cancelJob(t);return!0}destroy(){for(let n of this.activeProcesses.values())n.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear()}async destroyAsync(n=1e4){let t=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),t.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let e of t)try{e.kill("SIGTERM")}catch(o){}await Promise.all(t.map(e=>new Promise(o=>{let a=!1,r=()=>{a||(a=!0,o())};e.on("exit",r),e.on("error",r),setTimeout(()=>{if(!a){try{e.kill("SIGKILL")}catch(l){}setTimeout(r,500)}},n)}))),this.activeProcesses.clear(),this.activeJobs.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let n=this.queue.shift();this.activeJobs.set(n.id,n),n.status="running",this.broadcast({type:"job_started",jobId:n.id,position:0},n.id,n.sourceId),this.processor(n).catch(t=>{n.status="error",n.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:n.id,message:n.error},n.id,n.sourceId)}).finally(()=>{this.activeJobs.delete(n.id),this.activeProcesses.delete(n.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},n.id)})}}};import{mkdir as sn,readFile as on,writeFile as rn}from"fs/promises";import{dirname as an,join as cn}from"path";var ln={version:1,threads:{}},_e=class{constructor(n){this.cache=null;this.writeChain=Promise.resolve();this.filePath=cn(n,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let n=await on(this.filePath,"utf-8"),t=JSON.parse(n);if(t&&t.version===1&&t.threads)return this.cache=t,this.cache}catch(n){}return this.cache=ce(ee({},ln),{threads:{}}),this.cache}async getThread(n){var e;return(e=(await this.load()).threads[n])!=null?e:null}async findContinuationThread(n){if(n.length===0)return null;let t=await this.load(),e=new Set(n);for(let o of Object.values(t.threads))if(o.elementIdentifiers.some(r=>e.has(r)))return o;return null}async createThread(n,t){let e=await this.load(),o={id:n,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return e.threads[n]=o,await this.persist(),o}async appendMessage(n,t){let o=(await this.load()).threads[n];o&&(o.messages.push(t),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(n,t){let o=(await this.load()).threads[n];if(!o)return;let a=new Set(o.elementIdentifiers);for(let r of t)a.has(r)||o.elementIdentifiers.push(r);o.updatedAt=Date.now(),await this.persist()}async getThreadHistory(n,t=6){let e=await this.getThread(n);return!e||e.messages.length===0?[]:e.messages.length<=t?e.messages:[e.messages[0],...e.messages.slice(-(t-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await sn(an(this.filePath),{recursive:!0}),await rn(this.filePath,JSON.stringify(this.cache,null,2))}catch(n){console.error("[ThreadStore] Failed to persist:",n)}}),await this.writeChain}};var Rn={};var Sn=1111,In=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],xn=1800*1e3,Pn=3600*1e3;function kn(i){if(!i)return!1;try{let n=new URL(i);return n.hostname==="localhost"||n.hostname==="127.0.0.1"}catch(n){return!1}}function bn(i,n){let t=i.headers.origin;kn(t)&&(n.setHeader("Access-Control-Allow-Origin",t),n.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),n.setHeader("Access-Control-Allow-Headers","Content-Type"))}function g(i,n,t){i.writeHead(n,{"Content-Type":"application/json"}),i.end(JSON.stringify(t))}function Tn(i,n){if(!i)return n;let t=i.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return n;let[,e,o,a]=t;return`\x1B[38;2;${parseInt(e,16)};${parseInt(o,16)};${parseInt(a,16)}m${n}\x1B[0m`}function Mt(i,n){try{i.res.write(`event: ${n.type}
114
+ data: ${JSON.stringify(n)}
88
115
 
89
- `)}catch(n){}}async function Ot(r={}){var we,He,Le,We,Ge,qe,Ye,Qe;let t=(we=r.port)!=null?we:fn,n=(He=r.projectRoot)!=null?He:process.cwd(),e=(Le=r.tempDir)!=null?Le:le(hn(),"popmelt-bridge"),s=(We=r.maxTurns)!=null?We:40,a=(Ge=r.maxBudgetUsd)!=null?Ge:1,i=(qe=r.allowedTools)!=null?qe:mn,c=(Ye=r.claudePath)!=null?Ye:"claude",p=(Qe=r.provider)!=null?Qe:"claude",u={};for(let o of["claude","codex"])try{let l=an("which",[o],{encoding:"utf-8"}).trim();u[o]={available:!0,path:l}}catch(l){u[o]={available:!1,path:null}}let[x,L]=await Promise.all([Fe(n),ze(n)]);u.claude&&(u.claude.mcp=x),u.codex&&(u.codex.mcp=L),await cn(e,{recursive:!0}),Mt(e).catch(()=>{});let w=new Ee(1),M=new Set,I=new De(n),F=new Me(n),b=new Oe(n,F,{claudePath:c,onEvent:o=>{for(let l of M)$t(l,o)}}),z=new Map;w.addListener((o,l)=>{for(let h of M)$t(h,o)}),w.setProcessor(async o=>{var V,se,E,ne,ie,ve,de;let l=o._replyPrompt,h=o._replyImagePaths,d=(V=o.provider)!=null?V:p,f;if(o.threadId){let $=await I.getThread(o.threadId);if($){for(let m=$.messages.length-1;m>=0;m--)if($.messages[m].sessionId){f=$.messages[m].sessionId;break}}}let P;if(f&&l){let $=(se=await I.getThread(o.threadId))==null?void 0:se.messages.filter(O=>O.role==="human").pop();if(P=($==null?void 0:$.replyToQuestion)||($==null?void 0:$.feedbackSummary)||"",h&&h.length>0){P+=`
116
+ `)}catch(t){}}async function Ot(i={}){var We,Ye,qe,Qe,Ke,Ve,Xe,Ze;let n=(We=i.port)!=null?We:Sn,t=(Ye=i.projectRoot)!=null?Ye:process.cwd(),e=(qe=i.tempDir)!=null?qe:oe(yn(),"popmelt-bridge"),o=(Qe=i.maxTurns)!=null?Qe:40,a=(Ke=i.maxBudgetUsd)!=null?Ke:1,r=(Ve=i.allowedTools)!=null?Ve:In,l=(Xe=i.claudePath)!=null?Xe:"claude",p=(Ze=i.provider)!=null?Ze:"claude",f=i.timeoutMs,I={};for(let s of["claude","codex"])try{let c=dn("which",[s],{encoding:"utf-8"}).trim();I[s]={available:!0,path:c}}catch(c){I[s]={available:!1,path:null}}let[O,L]=await Promise.all([He(t),Ge(t)]);I.claude&&(I.claude.mcp=O),I.codex&&(I.codex.mcp=L),await un(e,{recursive:!0}),Ct(e).catch(()=>{});let m=new Je(1),_=new Set,P=new _e(t),U=new Ee(t),N=new Ae(t,U,{claudePath:l,onEvent:s=>{for(let c of _)Mt(c,s)}}),H=new Map,te=20,G=300*1e3,V=[],E=null,ne;m.addListener((s,c,u)=>{for(let d of _)(!u||!d.sourceId||d.sourceId===u)&&Mt(d,s)}),m.setProcessor(async s=>{var X,re,D,se,le,Se,ue;let c=s._replyPrompt,u=s._replyImagePaths,d=(X=s.provider)!=null?X:p,h;if(s.threadId){let $=await P.getThread(s.threadId);if($){for(let y=$.messages.length-1;y>=0;y--)if($.messages[y].sessionId){h=$.messages[y].sessionId;break}}}let v;if(h&&c){let $=(re=await P.getThread(s.threadId))==null?void 0:re.messages.filter(M=>M.role==="human").pop();if(v=($==null?void 0:$.replyToQuestion)||($==null?void 0:$.feedbackSummary)||"",u&&u.length>0){v+=`
90
117
 
91
- The developer attached reference images with their reply:`;for(let O of h)P+=`
92
- Attached image: use the Read tool to view the image at: ${O}`}P+=`
118
+ The developer attached reference images with their reply:`;for(let M of u)v+=`
119
+ Attached image: use the Read tool to view the image at: ${M}`}v+=`
93
120
 
94
- After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(f)P=xe(o.feedback,o.imagePaths)+`
121
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(h)v=xe(s.feedback,s.imagePaths)+`
95
122
 
96
123
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
97
124
 
98
125
  After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
99
126
 
100
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${o.screenshotPath}`:"");else{let $=!l&&o.threadId?await I.getThreadHistory(o.threadId):void 0,m=l?null:await b.loadModel();P=l!=null?l:gt(o.screenshotPath,o.feedback,{threadHistory:$&&$.length>0?$:void 0,provider:d,imagePaths:o.imagePaths,designModel:m!=null?m:void 0})}let S=Sn(o.color,`[\u22B9 ${t}:${o.id}]`);console.log(`${S} Reviewing feedback ${o.screenshotPath} (provider: ${d})${o.threadId?` (thread: ${o.threadId})`:""}${f?` (resuming: ${f.slice(0,8)})`:""}`);let k=!!o._isPlanExecutor,C="",v=0,U=($,m)=>{if(w.broadcast($,m),k&&$.type==="delta"&&"text"in $){C+=$.text;let O=xt(C);if(O.length>v){let X=O.slice(v);v=O.length,w.broadcast({type:"task_resolved",jobId:m,planId:o.planId,resolutions:X,threadId:o.threadId},m)}}},D=(E=o._allowedTools)!=null?E:i,{process:_,result:T}=d==="codex"?nt(o.id,{prompt:P,projectRoot:n,screenshotPath:o.screenshotPath,resumeSessionId:f,model:o.model,onEvent:U}):$e(o.id,{prompt:P,projectRoot:n,maxTurns:s,maxBudgetUsd:a,allowedTools:D,claudePath:c,resumeSessionId:f,model:o.model,onEvent:U});w.setActiveProcess(o.id,_);let y=await T;if(o.result=y.text,y.success){console.log(`${S} Iteration complete`),y.fileEdits&&y.fileEdits.length>0&&console.log(`${S} Captured ${y.fileEdits.length} file edit(s): ${y.fileEdits.map(N=>`${N.tool} ${N.file_path}`).join(", ")}`),o.status="done";let $=yt(y.text),m=St(y.text);if(m.length>0&&o.annotationIds&&o.annotationIds.length>0){let N=new Set(o.annotationIds);m.every(re=>N.has(re.annotationId))||(m=m.map((re,ue)=>ae(Z({},re),{annotationId:o.annotationIds[ue%o.annotationIds.length]})))}let O=y.fileEdits&&y.fileEdits.length>0?y.fileEdits.map(N=>`${N.tool} ${N.file_path.split("/").pop()}`):void 0;if(o.threadId&&await I.appendMessage(o.threadId,{role:"assistant",timestamp:Date.now(),jobId:o.id,responseText:y.text,resolutions:m.length>0?m:void 0,question:$!=null?$:void 0,sessionId:y.sessionId,toolsUsed:O}),F.captureGitDiff(n).then(async N=>{var Ve;let W=Date.now(),re=o.imagePaths?Object.values(o.imagePaths).flat():[],ue=[];if(o.imagePaths)for(let[Ct,Et]of Object.entries(o.imagePaths))for(let Je=0;Je<Et.length;Je++)ue.push(`screenshots/p-${o.id}-${Ct}-${Je}.png`);await F.persist({version:1,id:o.id,createdAt:o.createdAt,completedAt:W,durationMs:W-o.createdAt,url:o.feedback.url,viewport:o.feedback.viewport,screenshotPath:`screenshots/s-${o.id}.png`,pastedImagePaths:ue,annotations:o.feedback.annotations,styleModifications:o.feedback.styleModifications,inspectedElement:o.feedback.inspectedElement,provider:o.provider,model:o.model,sessionId:y.sessionId,threadId:o.threadId,planId:o.planId,planTaskId:o.planTaskId,responseText:y.text,resolutions:m.length>0?m:[],question:$!=null?$:void 0,fileEdits:(Ve=y.fileEdits)!=null?Ve:[],toolsUsed:O,gitDiff:N},o.screenshotPath,re)}).catch(()=>{}),m.length>0&&m.some(W=>{var ue;let re=(ue=W.finalScope)!=null?ue:W.inferredScope;return(re==null?void 0:re.breadth)==="pattern"})&&b.run().catch(()=>{}),o.planId&&!o.planTaskId){let N=z.get(o.planId);if(N){let W=Pt(y.text);W&&W.length>0?(N.plan=W,N.status="awaiting_approval",N.plannerThreadId=o.threadId,console.log(`${S} Plan ready: ${W.length} tasks for group ${o.planId}`),w.broadcast({type:"plan_ready",jobId:o.id,planId:o.planId,tasks:W,threadId:o.threadId},o.id)):$||(N.status="error",console.error(`${S} Failed to parse plan from planner response`))}}if(o.planId&&o._isReview){let N=z.get(o.planId);if(N){let W=Rt(y.text);W&&(N.status=W.verdict==="pass"?"done":"executing",console.log(`${S} Review verdict: ${W.verdict} \u2014 ${W.summary}`),w.broadcast({type:"plan_review",planId:o.planId,verdict:W.verdict,summary:W.summary,issues:W.issues},o.id))}}$&&(console.log(`${S} \u{1F4AC} Question detected: "${$.slice(0,120)}" \u2192 broadcasting to ${M.size} SSE clients (threadId=${(ne=o.threadId)!=null?ne:o.id}, annotationIds=${(ve=(ie=o.annotationIds)==null?void 0:ie.join(","))!=null?ve:"none"})`),w.broadcast({type:"question",jobId:o.id,threadId:(de=o.threadId)!=null?de:o.id,question:$,annotationIds:o.annotationIds},o.id));let X=It(y.text);X.length>0&&(console.log(`${S} Novel pattern(s): ${X.map(N=>`${N.category}/${N.element}`).join(", ")}`),w.broadcast({type:"novel_patterns",jobId:o.id,patterns:X,threadId:o.threadId},o.id)),w.broadcast({type:"done",jobId:o.id,success:!0,resolutions:m.length>0?m:void 0,responseText:y.text,threadId:o.threadId},o.id)}else console.error(`${S} Error: ${y.error}`),o.status="error",o.error=y.error,w.broadcast({type:"error",jobId:o.id,message:y.error||"Unknown error"},o.id)});let Q=pn(async(o,l)=>{if(vn(o,l),o.method==="OPTIONS"){l.writeHead(204),l.end();return}let d=new URL(o.url||"/",`http://127.0.0.1:${t}`).pathname;try{if(o.method==="POST"&&d==="/send")await ee(o,l);else if(o.method==="GET"&&d==="/events")B(o,l);else if(o.method==="GET"&&d==="/status")te(l);else if(o.method==="GET"&&d==="/capabilities")g(l,200,{providers:u});else if(o.method==="POST"&&d==="/mcp/install")await ke(o,l);else if(o.method==="POST"&&d==="/reply")await G(o,l);else if(o.method==="POST"&&d==="/cancel")J(o,l);else if(o.method==="POST"&&d==="/materialize")await j(l);else if(o.method==="POST"&&d==="/plan")await R(o,l);else if(o.method==="POST"&&d==="/plan/approve")await q(o,l);else if(o.method==="POST"&&d==="/plan/execute")await H(o,l);else if(o.method==="POST"&&d==="/plan/review")await K(o,l);else if(o.method==="GET"&&d.startsWith("/plan/"))Ie(d.slice(6),l);else if(o.method==="POST"&&d==="/model/component")await Pe(o,l);else if(o.method==="DELETE"&&d==="/model/component")await be(o,l);else if(o.method==="PATCH"&&d==="/model/token")await Te(o,l);else if(o.method==="DELETE"&&d==="/model/token")await Y(o,l);else if(o.method==="GET"&&d==="/model"){let f=await b.loadModel();g(l,200,{model:f})}else if(o.method==="GET"&&d.startsWith("/thread/")){let f=d.slice(8);await Ae(f,l)}else g(l,404,{error:"Not found"})}catch(f){console.error("[Bridge] Request error:",f),g(l,500,{error:f instanceof Error?f.message:"Internal error"})}});async function ee(o,l){let{screenshot:h,feedback:d,color:f,provider:P,model:S,pastedImages:k}=await ge(o),C;try{C=JSON.parse(d)}catch(E){g(l,400,{error:"Invalid feedback JSON"});return}let v=he().slice(0,8),U=le(e,`screenshot-${v}.png`);await ye(U,h);let D={};if(k.length>0)for(let E of k){let ne=le(e,`pasted-${v}-${E.annotationId}-${E.index}.png`);await ye(ne,E.data),D[E.annotationId]||(D[E.annotationId]=[]),D[E.annotationId].push(ne)}let _=C.annotations.map(E=>E.linkedSelector).filter(E=>!!E),T;if(_.length>0){let E=await I.findContinuationThread(_);E?(T=E.id,await I.addElementIdentifiers(T,_)):T=(await I.createThread(v,_)).id}let y=C.annotations.map(E=>E.id),V=Z({id:v,status:"queued",screenshotPath:U,feedback:C,createdAt:Date.now(),color:f,threadId:T,annotationIds:y,provider:P==="claude"||P==="codex"?P:void 0,model:S||void 0},Object.keys(D).length>0?{imagePaths:D}:{});if(T){let E=C.annotations.map(ie=>ie.instruction||`[${ie.type}]`).join("; "),ne=xe(C,Object.keys(D).length>0?D:void 0);await I.appendMessage(T,{role:"human",timestamp:Date.now(),jobId:v,screenshotPath:U,annotationIds:y,feedbackSummary:E,feedbackContext:ne||void 0})}let se=w.enqueue(V);g(l,200,{jobId:v,position:se,threadId:T})}async function G(o,l){let h=o.headers["content-type"]||"",d,f,P,S,k,C=[];if(h.includes("multipart/form-data")){let m=await ge(o),O=m.feedback?JSON.parse(m.feedback):{};d=O.threadId,f=O.reply,P=O.color,S=O.provider,k=O.model;for(let X of m.pastedImages)C.push(X.data)}else{let m=[];try{for(var ie=ce(o),ve,de,$;ve=!(de=await ie.next()).done;ve=!1){let N=de.value;m.push(typeof N=="string"?Buffer.from(N):N)}}catch(de){$=[de]}finally{try{ve&&(de=ie.return)&&await de.call(ie)}finally{if($)throw $[0]}}let O=Buffer.concat(m).toString("utf-8"),X;try{X=JSON.parse(O)}catch(N){g(l,400,{error:"Invalid JSON"});return}d=X.threadId,f=X.reply,P=X.color,S=X.provider,k=X.model}if(!d||!f){g(l,400,{error:"Missing threadId or reply"});return}if(!await I.getThread(d)){g(l,404,{error:"Thread not found"});return}let U=he().slice(0,8),D=[];for(let m=0;m<C.length;m++){let O=le(e,`reply-${U}-${m}.png`);await ye(O,C[m]),D.push(O)}let _="";{let m=await I.getThreadHistory(d);for(let O=m.length-1;O>=0;O--)if(m[O].screenshotPath){_=m[O].screenshotPath;break}}if(!_){g(l,400,{error:"No screenshot available"});return}await I.appendMessage(d,{role:"human",timestamp:Date.now(),jobId:U,replyToQuestion:f,screenshotPath:_});let T=await I.getThreadHistory(d),y=[];for(let m of T)if(m.annotationIds)for(let O of m.annotationIds)y.includes(O)||y.push(O);let V=S==="claude"||S==="codex"?S:void 0,se=wt(_,T,V,D.length>0?D:void 0),E={id:U,status:"queued",screenshotPath:_,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:P,threadId:d,annotationIds:y.length>0?y:void 0,provider:V,model:k||void 0};E._replyPrompt=se,D.length>0&&(E._replyImagePaths=D);let ne=w.enqueue(E);g(l,200,{jobId:U,position:ne,threadId:d})}function B(o,l){l.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),l.write(`event: connected
127
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${s.screenshotPath}`:"");else{let $=!c&&s.threadId?await P.getThreadHistory(s.threadId):void 0,y=c?null:await N.loadModel();v=c!=null?c:yt(s.screenshotPath,s.feedback,{threadHistory:$&&$.length>0?$:void 0,provider:d,imagePaths:s.imagePaths,designModel:y!=null?y:void 0})}let R=Tn(s.color,`[\u22B9 ${n}:${s.id}]`);console.log(`${R} Reviewing feedback ${s.screenshotPath} (provider: ${d})${s.threadId?` (thread: ${s.threadId})`:""}${h?` (resuming: ${h.slice(0,8)})`:""}`);let k=!!s._isPlanExecutor,A="",w=0,Y=($,y)=>{if(m.broadcast($,y,s.sourceId),k&&$.type==="delta"&&"text"in $){A+=$.text;let M=xt(A);if(M.length>w){let Z=M.slice(w);w=M.length,m.broadcast({type:"task_resolved",jobId:y,planId:s.planId,resolutions:Z,threadId:s.threadId},y,s.sourceId)}}},z=(D=s._allowedTools)!=null?D:r,{process:J,result:b}=d==="codex"?st(s.id,{prompt:v,projectRoot:t,screenshotPath:s.screenshotPath,resumeSessionId:h,model:s.model,onEvent:Y}):Oe(s.id,{prompt:v,projectRoot:t,maxTurns:o,maxBudgetUsd:a,allowedTools:z,claudePath:l,resumeSessionId:h,model:s.model,timeoutMs:f,onEvent:Y});m.setActiveProcess(s.id,J);let S=await b;if(s.result=S.text,S.success){console.log(`${R} Iteration complete`),S.fileEdits&&S.fileEdits.length>0&&console.log(`${R} Captured ${S.fileEdits.length} file edit(s): ${S.fileEdits.map(F=>`${F.tool} ${F.file_path}`).join(", ")}`),s.status="done";let $=wt(S.text),y=It(S.text);if(y.length>0&&s.annotationIds&&s.annotationIds.length>0){let F=new Set(s.annotationIds);y.every(ae=>F.has(ae.annotationId))||(y=y.map((ae,pe)=>ce(ee({},ae),{annotationId:s.annotationIds[pe%s.annotationIds.length]})))}let M=S.fileEdits&&S.fileEdits.length>0?S.fileEdits.map(F=>`${F.tool} ${F.file_path.split("/").pop()}`):void 0;if(s.threadId&&await P.appendMessage(s.threadId,{role:"assistant",timestamp:Date.now(),jobId:s.id,responseText:S.text,resolutions:y.length>0?y:void 0,question:$!=null?$:void 0,sessionId:S.sessionId,toolsUsed:M}),U.captureGitDiff(t).then(async F=>{var et;let q=Date.now(),ae=s.imagePaths?Object.values(s.imagePaths).flat():[],pe=[];if(s.imagePaths)for(let[Nt,Bt]of Object.entries(s.imagePaths))for(let Be=0;Be<Bt.length;Be++)pe.push(`screenshots/p-${s.id}-${Nt}-${Be}.png`);await U.persist({version:1,id:s.id,createdAt:s.createdAt,completedAt:q,durationMs:q-s.createdAt,url:s.feedback.url,viewport:s.feedback.viewport,screenshotPath:`screenshots/s-${s.id}.png`,pastedImagePaths:pe,annotations:s.feedback.annotations,styleModifications:s.feedback.styleModifications,inspectedElement:s.feedback.inspectedElement,provider:s.provider,model:s.model,sessionId:S.sessionId,threadId:s.threadId,planId:s.planId,planTaskId:s.planTaskId,responseText:S.text,resolutions:y.length>0?y:[],question:$!=null?$:void 0,fileEdits:(et=S.fileEdits)!=null?et:[],toolsUsed:M,gitDiff:F},s.screenshotPath,ae)}).catch(()=>{}),y.length>0&&y.some(q=>{var pe;let ae=(pe=q.finalScope)!=null?pe:q.inferredScope;return(ae==null?void 0:ae.breadth)==="pattern"})&&N.run().catch(()=>{}),s.planId&&!s.planTaskId){let F=H.get(s.planId);if(F){let q=bt(S.text);q&&q.length>0?(F.plan=q,F.status="awaiting_approval",F.plannerThreadId=s.threadId,console.log(`${R} Plan ready: ${q.length} tasks for group ${s.planId}`),m.broadcast({type:"plan_ready",jobId:s.id,planId:s.planId,tasks:q,threadId:s.threadId},s.id,s.sourceId)):$||(F.status="error",console.error(`${R} Failed to parse plan from planner response`))}}if(s.planId&&s._isReview){let F=H.get(s.planId);if(F){let q=$t(S.text);q&&(F.status=q.verdict==="pass"?"done":"executing",console.log(`${R} Review verdict: ${q.verdict} \u2014 ${q.summary}`),m.broadcast({type:"plan_review",planId:s.planId,verdict:q.verdict,summary:q.summary,issues:q.issues},s.id,s.sourceId))}}$&&(console.log(`${R} \u{1F4AC} Question detected: "${$.slice(0,120)}" \u2192 broadcasting to ${_.size} SSE clients (threadId=${(se=s.threadId)!=null?se:s.id}, annotationIds=${(Se=(le=s.annotationIds)==null?void 0:le.join(","))!=null?Se:"none"})`),m.broadcast({type:"question",jobId:s.id,threadId:(ue=s.threadId)!=null?ue:s.id,question:$,annotationIds:s.annotationIds},s.id,s.sourceId));let Z=Pt(S.text);Z.length>0&&(console.log(`${R} Novel pattern(s): ${Z.map(F=>`${F.category}/${F.element}`).join(", ")}`),m.broadcast({type:"novel_patterns",jobId:s.id,patterns:Z,threadId:s.threadId},s.id,s.sourceId)),m.broadcast({type:"done",jobId:s.id,success:!0,resolutions:y.length>0?y:void 0,responseText:S.text,threadId:s.threadId},s.id,s.sourceId),V.push({id:s.id,status:"done",completedAt:Date.now(),threadId:s.threadId})}else console.error(`${R} Error: ${S.error}`),s.status="error",s.error=S.error,m.broadcast({type:"error",jobId:s.id,message:S.error||"Unknown error"},s.id,s.sourceId),V.push({id:s.id,status:"error",completedAt:Date.now(),error:S.error,threadId:s.threadId});let j=Date.now()-G;for(;V.length>0&&(V[0].completedAt<j||V.length>te);)V.shift()});let C=gn(async(s,c)=>{if(bn(s,c),s.method==="OPTIONS"){c.writeHead(204),c.end();return}let d=new URL(s.url||"/",`http://127.0.0.1:${n}`).pathname;try{if(s.method==="POST"&&d==="/send")await x(s,c);else if(s.method==="GET"&&d==="/events")T(s,c);else if(s.method==="GET"&&d==="/status")K(c);else if(s.method==="GET"&&d==="/capabilities")g(c,200,{providers:I});else if(s.method==="POST"&&d==="/mcp/install")await Me(s,c);else if(s.method==="POST"&&d==="/reply")await W(s,c);else if(s.method==="POST"&&d==="/cancel")me(s,c);else if(s.method==="POST"&&d==="/materialize")await Pe(c);else if(s.method==="POST"&&d==="/plan")await ke(s,c);else if(s.method==="POST"&&d==="/plan/approve")await be(s,c);else if(s.method==="POST"&&d==="/plan/execute")await Te(s,c);else if(s.method==="POST"&&d==="/plan/review")await Re(s,c);else if(s.method==="GET"&&d.startsWith("/plan/"))$e(d.slice(6),c);else if(s.method==="POST"&&d==="/model/component")await Q(s,c);else if(s.method==="DELETE"&&d==="/model/component")await Ne(s,c);else if(s.method==="PATCH"&&d==="/model/token")await B(s,c);else if(s.method==="DELETE"&&d==="/model/token")await Ce(s,c);else if(s.method==="GET"&&d==="/model"){let h=await N.loadModel();g(c,200,{model:h})}else if(s.method==="GET"&&d.startsWith("/thread/")){let h=d.slice(8);await Jt(h,c)}else s.method==="GET"&&(d==="/canvas"||d==="/canvas/")?Et(s,c):s.method==="GET"&&d==="/canvas/manifest"?await At(c):s.method==="GET"&&d==="/canvas/app.mjs"?await Dt(c):g(c,404,{error:"Not found"})}catch(h){console.error("[Bridge] Request error:",h),g(c,500,{error:h instanceof Error?h.message:"Internal error"})}});async function x(s,c){let{screenshot:u,feedback:d,color:h,provider:v,model:R,sourceId:k,pastedImages:A}=await we(s),w;try{w=JSON.parse(d)}catch(D){g(c,400,{error:"Invalid feedback JSON"});return}let Y=fe().slice(0,8),z=oe(e,`screenshot-${Y}.png`);await ve(z,u);let J={};if(A.length>0)for(let D of A){let se=oe(e,`pasted-${Y}-${D.annotationId}-${D.index}.png`);await ve(se,D.data),J[D.annotationId]||(J[D.annotationId]=[]),J[D.annotationId].push(se)}let b=w.annotations.map(D=>D.linkedSelector).filter(D=>!!D),S;if(b.length>0){let D=await P.findContinuationThread(b);D?(S=D.id,await P.addElementIdentifiers(S,b)):S=(await P.createThread(Y,b)).id}let j=w.annotations.map(D=>D.id),X=ce(ee({id:Y,status:"queued",screenshotPath:z,feedback:w,createdAt:Date.now(),color:h,threadId:S,annotationIds:j,provider:v==="claude"||v==="codex"?v:void 0,model:R||void 0},Object.keys(J).length>0?{imagePaths:J}:{}),{sourceId:k||void 0});if(S){let D=w.annotations.map(le=>le.instruction||`[${le.type}]`).join("; "),se=xe(w,Object.keys(J).length>0?J:void 0);await P.appendMessage(S,{role:"human",timestamp:Date.now(),jobId:Y,screenshotPath:z,annotationIds:j,feedbackSummary:D,feedbackContext:se||void 0})}let re=m.enqueue(X);g(c,200,{jobId:Y,position:re,threadId:S})}async function W(s,c){let u=s.headers["content-type"]||"",d,h,v,R,k,A,w=[];if(u.includes("multipart/form-data")){let y=await we(s),M=y.feedback?JSON.parse(y.feedback):{};d=M.threadId,h=M.reply,v=M.color,R=M.provider,k=M.model,A=M.sourceId||y.sourceId;for(let Z of y.pastedImages)w.push(Z.data)}else{let y=[];try{for(var le=de(s),Se,ue,$;Se=!(ue=await le.next()).done;Se=!1){let F=ue.value;y.push(typeof F=="string"?Buffer.from(F):F)}}catch(ue){$=[ue]}finally{try{Se&&(ue=le.return)&&await ue.call(le)}finally{if($)throw $[0]}}let M=Buffer.concat(y).toString("utf-8"),Z;try{Z=JSON.parse(M)}catch(F){g(c,400,{error:"Invalid JSON"});return}d=Z.threadId,h=Z.reply,v=Z.color,R=Z.provider,k=Z.model,A=Z.sourceId}if(!d||!h){g(c,400,{error:"Missing threadId or reply"});return}if(!await P.getThread(d)){g(c,404,{error:"Thread not found"});return}let z=fe().slice(0,8),J=[];for(let y=0;y<w.length;y++){let M=oe(e,`reply-${z}-${y}.png`);await ve(M,w[y]),J.push(M)}let b="";{let y=await P.getThreadHistory(d);for(let M=y.length-1;M>=0;M--)if(y[M].screenshotPath){b=y[M].screenshotPath;break}}if(!b){g(c,400,{error:"No screenshot available"});return}await P.appendMessage(d,{role:"human",timestamp:Date.now(),jobId:z,replyToQuestion:h,screenshotPath:b});let S=await P.getThreadHistory(d),j=[];for(let y of S)if(y.annotationIds)for(let M of y.annotationIds)j.includes(M)||j.push(M);let X=R==="claude"||R==="codex"?R:void 0,re=vt(b,S,X,J.length>0?J:void 0),D={id:z,status:"queued",screenshotPath:b,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:v,threadId:d,annotationIds:j.length>0?j:void 0,provider:X,model:k||void 0,sourceId:A||void 0};D._replyPrompt=re,J.length>0&&(D._replyImagePaths=J);let se=m.enqueue(D);g(c,200,{jobId:z,position:se,threadId:d})}function T(s,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
101
128
  data: {"status":"connected"}
102
129
 
103
- `);let h={id:he().slice(0,8),res:l};M.add(h),o.on("close",()=>{M.delete(h)})}function te(o){let l=w.allActive;g(o,200,{ok:!0,activeJob:l[0]?{id:l[0].id,status:l[0].status}:null,activeJobs:l.map(h=>({id:h.id,status:h.status})),queueDepth:w.depth})}function J(o,l){let d=new URL(o.url||"/",`http://127.0.0.1:${t}`).searchParams.get("jobId"),f=d?w.cancelJob(d):w.cancelActive();g(l,200,{cancelled:f})}async function j(o){if(b.isRunning){g(o,200,{skipped:!0,reason:"Already running"});return}let l=await b.getUnmaterializedPatternDecisions();if(l.length===0){g(o,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}b.run().catch(()=>{}),g(o,200,{started:!0,decisionCount:l.length,decisionIds:l.map(h=>h.id)})}async function R(o,l){let{screenshot:h,feedback:d,goal:f,pageUrl:P,viewport:S,provider:k,model:C,manifest:v}=await ge(o);if(!h||!f){g(l,400,{error:"Missing screenshot or goal"});return}let U=P||"",D={width:1440,height:900};try{S&&(D=JSON.parse(S))}catch(m){}let _;if(d)try{let m=JSON.parse(d),O=xe(m);O&&(_=O)}catch(m){}let T=he().slice(0,8),y=he().slice(0,8),V=le(e,`screenshot-plan-${T}.png`);await ye(V,h);let E=(await I.createThread(y,[])).id,ne={id:T,goal:f,status:"planning",plannerJobId:y,plannerThreadId:E,workerJobIds:[],screenshotPath:V,pageUrl:U,viewport:D,createdAt:Date.now()};z.set(T,ne);let ie=kt(V,f,U,D,v,_);await I.appendMessage(E,{role:"human",timestamp:Date.now(),jobId:y,screenshotPath:V,feedbackSummary:`Plan: ${f}`,feedbackContext:`Goal: ${f}
104
- Page: ${U}`});let ve=k==="claude"||k==="codex"?k:p,de={id:y,status:"queued",screenshotPath:V,feedback:{timestamp:new Date().toISOString(),url:U,viewport:D,scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:E,provider:ve,model:C||void 0,planId:T};de._replyPrompt=ie,de._allowedTools=["Read"];let $=w.enqueue(de);g(l,200,{planId:T,jobId:y,position:$,threadId:E})}async function q(o,l){let h=[];try{for(var v=ce(o),U,D,_;U=!(D=await v.next()).done;U=!1){let T=D.value;h.push(typeof T=="string"?Buffer.from(T):T)}}catch(D){_=[D]}finally{try{U&&(D=v.return)&&await D.call(v)}finally{if(_)throw _[0]}}let d=Buffer.concat(h).toString("utf-8"),f;try{f=JSON.parse(d)}catch(T){g(l,400,{error:"Invalid JSON"});return}let{planId:P,approvedTaskIds:S}=f;if(!P){g(l,400,{error:"Missing planId"});return}let k=z.get(P);if(!k){g(l,404,{error:"Plan not found"});return}if(!k.plan){g(l,400,{error:"Plan has no tasks"});return}let C=S?k.plan.filter(T=>S.includes(T.id)):k.plan;k.status="executing",g(l,200,{planId:P,tasks:C,status:"executing"})}async function H(o,l){let{screenshot:h,planId:d,tasks:f,provider:P,model:S}=await ge(o);if(!d||!f||!h){g(l,400,{error:"Missing planId, tasks, or screenshot"});return}let k=z.get(d);if(!k){g(l,404,{error:"Plan not found"});return}if(k.status!=="executing"){g(l,400,{error:`Plan status is ${k.status}, expected executing`});return}let C;try{C=JSON.parse(f)}catch(se){g(l,400,{error:"Invalid tasks JSON"});return}let v=he().slice(0,8),U=le(e,`screenshot-exec-${d}.png`);await ye(U,h);let D=P==="claude"||P==="codex"?P:p,_=Tt(U,C,k.pageUrl,k.viewport,D),T=C.map(se=>se.annotationId),y={id:v,status:"queued",screenshotPath:U,feedback:{timestamp:new Date().toISOString(),url:k.pageUrl,viewport:k.viewport,scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),provider:D,model:S||void 0,planId:d,annotationIds:T};y._replyPrompt=_,y._isPlanExecutor=!0,k.executorJobId=v;let V=w.enqueue(y);g(l,200,{jobId:v,planId:d,position:V})}async function K(o,l){let{screenshot:h,planId:d,provider:f,model:P}=await ge(o);if(!d){g(l,400,{error:"Missing planId"});return}let S=z.get(d);if(!S){g(l,404,{error:"Plan not found"});return}S.status="reviewing";let k=he().slice(0,8),C=S.screenshotPath;h&&(C=le(e,`screenshot-review-${d}.png`),await ye(C,h));let v=(S.plan||[]).map(y=>({id:y.id,instruction:y.instruction,summary:"completed"})),U=bt(C,S.goal,v),D=f==="claude"||f==="codex"?f:p,_={id:k,status:"queued",screenshotPath:C,feedback:{timestamp:new Date().toISOString(),url:S.pageUrl,viewport:S.viewport,scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),provider:D,model:P||void 0,planId:d};_._replyPrompt=U,_._isReview=!0,_._allowedTools=["Read"];let T=w.enqueue(_);g(l,200,{jobId:k,planId:d,position:T})}function Ie(o,l){let h=z.get(o);if(!h){g(l,404,{error:"Plan not found"});return}g(l,200,h)}async function ke(o,l){var D,_;let h=[];try{for(var k=ce(o),C,v,U;C=!(v=await k.next()).done;C=!1){let T=v.value;h.push(typeof T=="string"?Buffer.from(T):T)}}catch(v){U=[v]}finally{try{C&&(v=k.return)&&await v.call(k)}finally{if(U)throw U[0]}}let d;if(h.length>0)try{d=JSON.parse(Buffer.concat(h).toString("utf-8")).serverUrl}catch(T){}let f=[];(D=u.claude)!=null&&D.available&&u.claude.mcp&&!u.claude.mcp.found&&f.push(await ft(d)),(_=u.codex)!=null&&_.available&&u.codex.mcp&&!u.codex.mcp.found&&f.push(await mt(d));let[P,S]=await Promise.all([Fe(n),ze(n)]);u.claude&&(u.claude.mcp=P),u.codex&&(u.codex.mcp=S),g(l,200,{results:f,capabilities:{providers:u}})}async function Pe(o,l){let h=[];try{for(var P=ce(o),S,k,C;S=!(k=await P.next()).done;S=!1){let v=k.value;h.push(typeof v=="string"?Buffer.from(v):v)}}catch(k){C=[k]}finally{try{S&&(k=P.return)&&await k.call(P)}finally{if(C)throw C[0]}}let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch(v){g(l,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){g(l,400,{error:"Missing or invalid name"});return}let f=await b.addComponent(d.name);g(l,200,f)}async function be(o,l){let h=[];try{for(var P=ce(o),S,k,C;S=!(k=await P.next()).done;S=!1){let v=k.value;h.push(typeof v=="string"?Buffer.from(v):v)}}catch(k){C=[k]}finally{try{S&&(k=P.return)&&await k.call(P)}finally{if(C)throw C[0]}}let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch(v){g(l,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){g(l,400,{error:"Missing or invalid name"});return}let f=await b.removeComponent(d.name);g(l,200,f)}async function Te(o,l){let h=[];try{for(var P=ce(o),S,k,C;S=!(k=await P.next()).done;S=!1){let v=k.value;h.push(typeof v=="string"?Buffer.from(v):v)}}catch(k){C=[k]}finally{try{S&&(k=P.return)&&await k.call(P)}finally{if(C)throw C[0]}}let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch(v){g(l,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"||typeof d.value!="string"){g(l,400,{error:"Missing or invalid path/value"});return}let f=await b.updateToken(d.path,d.value);g(l,200,f)}async function Y(o,l){let h=[];try{for(var P=ce(o),S,k,C;S=!(k=await P.next()).done;S=!1){let v=k.value;h.push(typeof v=="string"?Buffer.from(v):v)}}catch(k){C=[k]}finally{try{S&&(k=P.return)&&await k.call(P)}finally{if(C)throw C[0]}}let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch(v){g(l,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"){g(l,400,{error:"Missing or invalid path"});return}let f=await b.removeToken(d.path);g(l,200,f)}async function Ae(o,l){let h=await I.getThread(o);if(!h){g(l,404,{error:"Thread not found"});return}let d=h.messages.map(S=>{var k=S,{screenshotPath:f}=k,P=tt(k,["screenshotPath"]);return P});g(l,200,{id:h.id,createdAt:h.createdAt,messages:d})}let A=setInterval(()=>{Mt(e).catch(()=>{})},gn);return new Promise((o,l)=>{Q.on("error",h=>{if(h.code==="EADDRINUSE"){console.log(`[\u22B9 already watching :${t}]`),o({port:t,close:async()=>{}});return}l(h)}),Q.listen(t,"127.0.0.1",()=>{console.log(`[\u22B9 is watching :${t}]`),o({port:t,close:async()=>{clearInterval(A),w.destroy();for(let h of M)try{h.res.end()}catch(d){}return M.clear(),new Promise(h=>{Q.close(()=>h())})}})})})}async function Mt(r){try{let t=await ln(r),n=Date.now();for(let e of t){let s=le(r,e);try{let a=await dn(s);n-a.mtimeMs>yn&&await un(s)}catch(a){}}}catch(t){}}async function vs(r){if(process.env.NODE_ENV==="production"&&!(r!=null&&r.force))throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");return Ot(r)}export{vs as startPopmelt};
130
+ `);let d=new URL(s.url||"/",`http://127.0.0.1:${n}`).searchParams.get("sourceId")||void 0,h={id:fe().slice(0,8),res:c,sourceId:d};_.add(h),s.on("close",()=>{_.delete(h)})}function K(s){let c=m.allActive;g(s,200,{ok:!0,activeJob:c[0]?{id:c[0].id,status:c[0].status}:null,activeJobs:c.map(u=>({id:u.id,status:u.status})),queueDepth:m.depth,recentJobs:V})}function me(s,c){let d=new URL(s.url||"/",`http://127.0.0.1:${n}`).searchParams.get("jobId"),h=d?m.cancelJob(d):m.cancelActive();g(c,200,{cancelled:h})}async function Pe(s){if(N.isRunning){g(s,200,{skipped:!0,reason:"Already running"});return}let c=await N.getUnmaterializedPatternDecisions();if(c.length===0){g(s,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}N.run().catch(()=>{}),g(s,200,{started:!0,decisionCount:c.length,decisionIds:c.map(u=>u.id)})}async function ke(s,c){let{screenshot:u,feedback:d,goal:h,pageUrl:v,viewport:R,provider:k,model:A,manifest:w,sourceId:Y}=await we(s);if(!u||!h){g(c,400,{error:"Missing screenshot or goal"});return}let z=v||"",J={width:1440,height:900};try{R&&(J=JSON.parse(R))}catch(y){}let b;if(d)try{let y=JSON.parse(d),M=xe(y);M&&(b=M)}catch(y){}let S=fe().slice(0,8),j=fe().slice(0,8),X=oe(e,`screenshot-plan-${S}.png`);await ve(X,u);let D=(await P.createThread(j,[])).id,se={id:S,goal:h,status:"planning",plannerJobId:j,plannerThreadId:D,workerJobIds:[],screenshotPath:X,pageUrl:z,viewport:J,createdAt:Date.now()};H.set(S,se);let le=kt(X,h,z,J,w,b);await P.appendMessage(D,{role:"human",timestamp:Date.now(),jobId:j,screenshotPath:X,feedbackSummary:`Plan: ${h}`,feedbackContext:`Goal: ${h}
131
+ Page: ${z}`});let Se=k==="claude"||k==="codex"?k:p,ue={id:j,status:"queued",screenshotPath:X,feedback:{timestamp:new Date().toISOString(),url:z,viewport:J,scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:D,provider:Se,model:A||void 0,planId:S,sourceId:Y||void 0};ue._replyPrompt=le,ue._allowedTools=["Read"];let $=m.enqueue(ue);g(c,200,{planId:S,jobId:j,position:$,threadId:D})}async function be(s,c){let u=[];try{for(var w=de(s),Y,z,J;Y=!(z=await w.next()).done;Y=!1){let b=z.value;u.push(typeof b=="string"?Buffer.from(b):b)}}catch(z){J=[z]}finally{try{Y&&(z=w.return)&&await z.call(w)}finally{if(J)throw J[0]}}let d=Buffer.concat(u).toString("utf-8"),h;try{h=JSON.parse(d)}catch(b){g(c,400,{error:"Invalid JSON"});return}let{planId:v,approvedTaskIds:R}=h;if(!v){g(c,400,{error:"Missing planId"});return}let k=H.get(v);if(!k){g(c,404,{error:"Plan not found"});return}if(!k.plan){g(c,400,{error:"Plan has no tasks"});return}let A=R?k.plan.filter(b=>R.includes(b.id)):k.plan;k.status="executing",g(c,200,{planId:v,tasks:A,status:"executing"})}async function Te(s,c){let{screenshot:u,planId:d,tasks:h,provider:v,model:R,sourceId:k}=await we(s);if(!d||!h||!u){g(c,400,{error:"Missing planId, tasks, or screenshot"});return}let A=H.get(d);if(!A){g(c,404,{error:"Plan not found"});return}if(A.status!=="executing"){g(c,400,{error:`Plan status is ${A.status}, expected executing`});return}let w;try{w=JSON.parse(h)}catch(re){g(c,400,{error:"Invalid tasks JSON"});return}let Y=fe().slice(0,8),z=oe(e,`screenshot-exec-${d}.png`);await ve(z,u);let J=v==="claude"||v==="codex"?v:p,b=Rt(z,w,A.pageUrl,A.viewport,J),S=w.map(re=>re.annotationId),j={id:Y,status:"queued",screenshotPath:z,feedback:{timestamp:new Date().toISOString(),url:A.pageUrl,viewport:A.viewport,scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),provider:J,model:R||void 0,planId:d,annotationIds:S,sourceId:k||void 0};j._replyPrompt=b,j._isPlanExecutor=!0,A.executorJobId=Y;let X=m.enqueue(j);g(c,200,{jobId:Y,planId:d,position:X})}async function Re(s,c){let{screenshot:u,planId:d,provider:h,model:v,sourceId:R}=await we(s);if(!d){g(c,400,{error:"Missing planId"});return}let k=H.get(d);if(!k){g(c,404,{error:"Plan not found"});return}k.status="reviewing";let A=fe().slice(0,8),w=k.screenshotPath;u&&(w=oe(e,`screenshot-review-${d}.png`),await ve(w,u));let Y=(k.plan||[]).map(j=>({id:j.id,instruction:j.instruction,summary:"completed"})),z=Tt(w,k.goal,Y),J=h==="claude"||h==="codex"?h:p,b={id:A,status:"queued",screenshotPath:w,feedback:{timestamp:new Date().toISOString(),url:k.pageUrl,viewport:k.viewport,scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),provider:J,model:v||void 0,planId:d,sourceId:R||void 0};b._replyPrompt=z,b._isReview=!0,b._allowedTools=["Read"];let S=m.enqueue(b);g(c,200,{jobId:A,planId:d,position:S})}function $e(s,c){let u=H.get(s);if(!u){g(c,404,{error:"Plan not found"});return}g(c,200,u)}async function Me(s,c){var z,J;let u=[];try{for(var k=de(s),A,w,Y;A=!(w=await k.next()).done;A=!1){let b=w.value;u.push(typeof b=="string"?Buffer.from(b):b)}}catch(w){Y=[w]}finally{try{A&&(w=k.return)&&await w.call(k)}finally{if(Y)throw Y[0]}}let d;if(u.length>0)try{d=JSON.parse(Buffer.concat(u).toString("utf-8")).serverUrl}catch(b){}let h=[];(z=I.claude)!=null&&z.available&&I.claude.mcp&&!I.claude.mcp.found&&h.push(await mt(d)),(J=I.codex)!=null&&J.available&&I.codex.mcp&&!I.codex.mcp.found&&h.push(await gt(d));let[v,R]=await Promise.all([He(t),Ge(t)]);I.claude&&(I.claude.mcp=v),I.codex&&(I.codex.mcp=R),g(c,200,{results:h,capabilities:{providers:I}})}async function Q(s,c){let u=[];try{for(var v=de(s),R,k,A;R=!(k=await v.next()).done;R=!1){let w=k.value;u.push(typeof w=="string"?Buffer.from(w):w)}}catch(k){A=[k]}finally{try{R&&(k=v.return)&&await k.call(v)}finally{if(A)throw A[0]}}let d;try{d=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch(w){g(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){g(c,400,{error:"Missing or invalid name"});return}let h=await N.addComponent(d.name);g(c,200,h)}async function Ne(s,c){let u=[];try{for(var v=de(s),R,k,A;R=!(k=await v.next()).done;R=!1){let w=k.value;u.push(typeof w=="string"?Buffer.from(w):w)}}catch(k){A=[k]}finally{try{R&&(k=v.return)&&await k.call(v)}finally{if(A)throw A[0]}}let d;try{d=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch(w){g(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){g(c,400,{error:"Missing or invalid name"});return}let h=await N.removeComponent(d.name);g(c,200,h)}async function B(s,c){let u=[];try{for(var v=de(s),R,k,A;R=!(k=await v.next()).done;R=!1){let w=k.value;u.push(typeof w=="string"?Buffer.from(w):w)}}catch(k){A=[k]}finally{try{R&&(k=v.return)&&await k.call(v)}finally{if(A)throw A[0]}}let d;try{d=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch(w){g(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"||typeof d.value!="string"){g(c,400,{error:"Missing or invalid path/value"});return}let h=await N.updateToken(d.path,d.value);g(c,200,h)}async function Ce(s,c){let u=[];try{for(var v=de(s),R,k,A;R=!(k=await v.next()).done;R=!1){let w=k.value;u.push(typeof w=="string"?Buffer.from(w):w)}}catch(k){A=[k]}finally{try{R&&(k=v.return)&&await k.call(v)}finally{if(A)throw A[0]}}let d;try{d=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch(w){g(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"){g(c,400,{error:"Missing or invalid path"});return}let h=await N.removeToken(d.path);g(c,200,h)}function Et(s,c){let u="http://localhost:3000",d=s.headers.referer||s.headers.origin;if(d)try{let v=new URL(typeof d=="string"?d:d[0]||"");(v.hostname==="localhost"||v.hostname==="127.0.0.1")&&(u=v.origin)}catch(v){}let h=nt(n,u);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(h)}async function At(s){let c=Date.now();if(E&&c<E.expires){g(s,200,E.data);return}try{let{scanForComponents:u}=await import("./react-scanner-5NIJ6ZPL.mjs"),{generateRenderFiles:d}=await import("./render-generator-ZNV3RDU7.mjs"),h=await u(t);E={data:h,expires:c+5e3},d(h,t,ne).then(v=>{ne=v}).catch(v=>console.warn("[Bridge] Render generation failed:",v)),g(s,200,h)}catch(u){console.error("[Bridge] Scanner error:",u),g(s,500,{error:"Failed to scan components"})}}async function Dt(s){let c=[oe(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),oe(t,"packages","popmelt","dist","canvas.mjs")];try{let u=vn(Rn.url);c.unshift(oe(wn(u),"canvas.mjs"))}catch(u){}for(let u of c)try{let d=await pn(u,"utf-8");s.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),s.end(d);return}catch(d){}console.error("[Bridge] Canvas bundle not found in:",c),g(s,404,{error:"Canvas bundle not found"})}async function Jt(s,c){let u=await P.getThread(s);if(!u){g(c,404,{error:"Thread not found"});return}let d=u.messages.map(R=>{var k=R,{screenshotPath:h}=k,v=tt(k,["screenshotPath"]);return v});g(c,200,{id:u.id,createdAt:u.createdAt,messages:d})}let _t=setInterval(()=>{Ct(e).catch(()=>{})},xn);return new Promise((s,c)=>{C.on("error",u=>{if(u.code==="EADDRINUSE"){console.log(`[\u22B9 already watching :${n}]`),s({port:n,close:async()=>{}});return}c(u)}),C.listen(n,"127.0.0.1",()=>{console.log(`[\u22B9 is watching :${n}]`),s({port:n,close:async()=>{clearInterval(_t),await m.destroyAsync();for(let u of _)try{u.res.end()}catch(d){}return _.clear(),new Promise(u=>{C.close(()=>u())})}})})})}async function Ct(i){try{let n=await hn(i),t=Date.now();for(let e of n){let o=oe(i,e);try{let a=await fn(o);t-a.mtimeMs>Pn&&await mn(o)}catch(a){}}}catch(n){}}async function $s(i){if(process.env.NODE_ENV==="production"&&!(i!=null&&i.force))throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");return Ot(i)}export{$s as startPopmelt};