@popmelt.com/core 0.6.3 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as C,b as V,c as rt,d as ue}from"./chunk-4LDJX6BW.mjs";import{spawn as En}from"child_process";import{execFileSync as ln,spawn as dn}from"child_process";import{createHash as un,randomUUID as Ge}from"crypto";import{mkdir as pn,readFile as $t,readdir as hn,stat as fn,unlink as mn,writeFile as Ae}from"fs/promises";import{createServer as gn}from"http";import{tmpdir as yn}from"os";import{basename as wn,dirname as vn,join as ie}from"path";import{fileURLToPath as Sn}from"url";function it(r,e){return`<!DOCTYPE html>
2
+ import{a as C,b as K,c as at,d as pe}from"./chunk-4LDJX6BW.mjs";import{spawn as _n}from"child_process";import{readFile as Dn,unlink as Nn}from"fs/promises";import{join as Bn}from"path";import{execFileSync as pn,spawn as hn}from"child_process";import{createHash as fn,randomUUID as He}from"crypto";import{mkdir as mn,readFile as Et,readdir as gn,stat as yn,unlink as wn,writeFile as De}from"fs/promises";import{createServer as vn}from"http";import{tmpdir as Sn}from"os";import{basename as xn,dirname as Pn,join as ce}from"path";import{fileURLToPath as In}from"url";function ct(r,e){return`<!DOCTYPE html>
3
3
  <html>
4
4
  <head>
5
5
  <meta charset="utf-8">
@@ -26,20 +26,21 @@ import{a as C,b as V,c as rt,d as ue}from"./chunk-4LDJX6BW.mjs";import{spawn as
26
26
  });
27
27
  </script>
28
28
  </body>
29
- </html>`}import{spawn as Dt}from"child_process";import{createInterface as Nt}from"readline";var Bt=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),at=1e5;function Jt(r){var o,i,l,c;let e=((o=r.input)==null?void 0:o.file_path)||((i=r.input)==null?void 0:i.path);if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Bt.has(t))return;let n;if(r.name==="Write"&&typeof((l=r.input)==null?void 0:l.content)=="string"?n=r.input.content:r.name==="Edit"&&typeof((c=r.input)==null?void 0:c.new_string)=="string"&&(n=r.input.new_string),!!n)return n.length>at?n.slice(0,at)+`
30
- \u2026[truncated]`:n}function Re(r,e){let{prompt:t,projectRoot:n,maxTurns:o=40,maxBudgetUsd:i=1,allowedTools:l=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:p,model:d,timeoutMs:S=3e5,onEvent:x}=e,b=[];p?b.push("--resume",p,"-p",t):b.push("-p",t),b.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(i)),d&&b.push("--model",d);for(let F of l)b.push("--allowedTools",F);let y=Dt(c,b,{cwd:n,stdio:["ignore","pipe","pipe"],env:V(C({},process.env),{ANTHROPIC_API_KEY:void 0})}),J=new Promise(F=>{var N;let U,P=[],L=[],A=!1,j="",W=!1,oe=setTimeout(()=>{W=!0,y.kill("SIGTERM"),setTimeout(()=>{try{y.kill("SIGKILL")}catch(k){}},5e3)},S),D=Nt({input:y.stdout}),z=new Set;D.on("line",k=>{var H,ne,he,ve,Se,xe,Ie,Pe,Te;if(k.trim())try{let Q=JSON.parse(k);Q.session_id&&!U&&(U=Q.session_id);let De=(ne=Q.type)!=null?ne:(H=Q.event)!=null&&H.type?`event.${Q.event.type}`:"unknown";if(z.add(De),Q.type==="result"&&Q.result&&P.length===0){let O=typeof Q.result=="string"?Q.result:"";O&&(P.push(O),x==null||x({type:"delta",jobId:r,text:O},r))}if(Q.type==="assistant"&&Array.isArray((he=Q.message)==null?void 0:he.content))for(let O of Q.message.content){if(O.type==="text"&&O.text&&(P.push(O.text),x==null||x({type:"delta",jobId:r,text:O.text},r)),O.type==="tool_use"&&O.name){let be=((ve=O.input)==null?void 0:ve.file_path)||((Se=O.input)==null?void 0:Se.path)||void 0,ke=Jt(O);x==null||x(C(C({type:"tool_use",jobId:r,tool:O.name},be?{file:be}:{}),ke?{content:ke}:{}),r),O.name==="Edit"&&((xe=O.input)!=null&&xe.file_path)?L.push({tool:"Edit",file_path:O.input.file_path,old_string:O.input.old_string,new_string:O.input.new_string,replace_all:O.input.replace_all}):O.name==="Write"&&((Ie=O.input)!=null&&Ie.file_path)&&L.push({tool:"Write",file_path:O.input.file_path,content:O.input.content})}O.type==="thinking"&&O.thinking&&(x==null||x({type:"thinking",jobId:r,text:O.thinking},r))}Q.type==="user"&&((Te=(Pe=Q.tool_use_result)==null?void 0:Pe.file)!=null&&Te.filePath)&&(x==null||x({type:"tool_use",jobId:r,tool:"Read",file:Q.tool_use_result.file.filePath},r))}catch(Q){}});let g=[];(N=y.stderr)==null||N.on("data",k=>{g.push(k.toString())}),y.on("close",k=>{if(clearTimeout(oe),D.close(),P.length===0&&z.size>0&&console.warn(`[Claude:${r}] No text captured. Event types seen: ${[...z].join(", ")}`),W)A=!0,j=`Timed out after ${Math.round(S/6e4)} minutes`;else if(k!==0&&k!==null){A=!0;let H=g.join("").trim(),ne=P.length===0&&z.size>0?` (no text captured, event types: ${[...z].join(", ")})`:"";j=H||`Claude process exited with code ${k}${ne}`}F({sessionId:U,text:P.join(""),success:!A,error:A?j:void 0,fileEdits:L.length>0?L:void 0})}),y.on("error",k=>{clearTimeout(oe),A=!0,j=k.message,F({sessionId:U,text:P.join(""),success:!1,error:j,fileEdits:L.length>0?L:void 0})})});return{process:y,result:J}}import{spawn as Ut}from"child_process";import{createInterface as Ft}from"readline";function ct(r,e){let{prompt:t,projectRoot:n,screenshotPath:o,resumeSessionId:i,model:l,onEvent:c}=e,p=[];i?(p.push("exec","resume",i),l&&p.push("-m",l),p.push("--json","--full-auto",t),o&&p.push("--image",o)):(p.push("exec","--json","--full-auto"),l&&p.push("-m",l),p.push(t),o&&p.push("--image",o));let d=Ut("codex",p,{cwd:n,stdio:["ignore","pipe","pipe"],env:C({},process.env)}),S=new Promise(x=>{var A;let b,y=[],J=!1,F="",U=Ft({input:d.stdout}),P=new Set;U.on("line",j=>{var W,oe,D,z;if(j.trim())try{let g=JSON.parse(j),N=(W=g.type)!=null?W:"unknown";if(P.add(N),N==="thread.started"&&g.thread_id&&!b&&(b=g.thread_id),(N==="item.agentMessage.delta"||N==="item/agentMessage/delta")&&((oe=g.delta)!=null&&oe.text)&&(y.push(g.delta.text),c==null||c({type:"delta",jobId:r,text:g.delta.text},r)),(N==="item.reasoning.delta"||N==="item/reasoning/delta")&&((D=g.delta)!=null&&D.text)&&(c==null||c({type:"thinking",jobId:r,text:g.delta.text},r)),(N==="item.started"||N==="item/started")&&g.item){let k=g.item.type;if(k==="command_execution")c==null||c({type:"tool_use",jobId:r,tool:"Bash"},r);else if(k==="file_change"){let H=g.item.filename||g.item.path;c==null||c(C({type:"tool_use",jobId:r,tool:"Edit"},H?{file:H}:{}),r)}else if(k==="file_read"){let H=g.item.filename||g.item.path;c==null||c(C({type:"tool_use",jobId:r,tool:"Read"},H?{file:H}:{}),r)}else if(k==="web_search")c==null||c({type:"tool_use",jobId:r,tool:"WebSearch"},r);else if(k==="mcp_tool_call"){let H=g.item.tool_name||g.item.name||"MCP";c==null||c({type:"tool_use",jobId:r,tool:H},r)}}if((N==="item.completed"||N==="item/completed")&&g.item){if(g.item.type==="agent_message"){let k=g.item.text;typeof k=="string"&&k&&(y.push(k),c==null||c({type:"delta",jobId:r,text:k},r))}else if(g.item.type==="reasoning"){let k=g.item.text;typeof k=="string"&&k&&(c==null||c({type:"thinking",jobId:r,text:k},r))}}N==="turn.failed"&&(J=!0,F=((z=g.error)==null?void 0:z.message)||g.message||"Turn failed")}catch(g){}});let L=[];(A=d.stderr)==null||A.on("data",j=>{L.push(j.toString())}),d.on("close",j=>{U.close(),y.length===0&&P.size>0&&console.warn(`[Codex:${r}] No text captured. Event types seen: ${[...P].join(", ")}`),j!==0&&j!==null&&(J=!0,F=L.join("")||`Codex process exited with code ${j}`),x({sessionId:b,text:y.join(""),success:!J,error:J?F:void 0})}),d.on("error",j=>{J=!0,F=j.message,x({sessionId:b,text:y.join(""),success:!1,error:F})})});return{process:d,result:S}}import{execFile as Lt}from"child_process";import{copyFile as lt,mkdir as dt,readdir as jt,readFile as zt,writeFile as Ht}from"fs/promises";import{join as pe}from"path";var Me=class{constructor(e){this.projectRoot=e;let t=pe(e,".popmelt");this.decisionsDir=pe(t,"decisions"),this.screenshotsDir=pe(t,"screenshots")}async persist(e,t,n){try{await dt(this.decisionsDir,{recursive:!0}),await dt(this.screenshotsDir,{recursive:!0});try{await lt(t,pe(this.screenshotsDir,`s-${e.id}.png`))}catch(o){}for(let o=0;o<n.length;o++)try{let i=e.pastedImagePaths[o];i&&await lt(n[o],pe(this.screenshotsDir,i.replace("screenshots/","")))}catch(i){}await Ht(pe(this.decisionsDir,`d-${e.id}.json`),JSON.stringify(e,null,2))}catch(o){console.error("[DecisionStore] Failed to persist decision record:",o)}}async listDecisionIds(){try{return(await jt(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch(e){return[]}}async loadDecision(e){try{let t=await zt(pe(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch(t){return null}}async loadDecisions(e){return(await Promise.all(e.map(n=>this.loadDecision(n)))).filter(n=>n!==null)}captureGitDiff(e){return new Promise(t=>{Lt("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(n,o)=>{if(n){t(null);return}t(o||null)})})}};import{readFile as ut,writeFile as me}from"fs/promises";import{join as Be}from"path";var re="[Materializer]",Gt={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Ee=class{constructor(e,t,n={}){this.projectRoot=e;this.decisionStore=t;this.options=n;this.cachedIndex=null;this.running=!1;let o=Be(e,".popmelt");this.indexPath=Be(o,"materialized.json"),this.modelPath=Be(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await ut(this.modelPath,"utf-8");return JSON.parse(e)}catch(e){return null}}async addComponent(e){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]}),(!t.components||typeof t.components!="object")&&(t.components={});let n=t.components;return n[e]?{added:!1,alreadyExists:!0}:(n[e]={description:""},await me(this.modelPath,JSON.stringify(t,null,2)),console.log(`${re} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,t){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]});let o=e.split("."),i=n;for(let p=0;p<o.length-1;p++){let d=o[p];(!i[d]||typeof i[d]!="object")&&(i[d]={}),i=i[d]}let l=o[o.length-1],c;try{c=JSON.parse(t)}catch(p){c=null}if(c&&typeof c=="object"&&c!==null&&"value"in c)i[l]=c;else{let p=i[l];p&&typeof p=="object"&&p!==null&&"value"in p?p.value=t:i[l]=t}return await me(this.modelPath,JSON.stringify(n,null,2)),console.log(`${re} Updated token "${e}" \u2192 "${t.slice(0,80)}"`),{updated:!0}}async removeToken(e){let t=await this.loadModel();if(!t)return{removed:!1};let n=e.split("."),o=t;for(let l=0;l<n.length-1;l++){let c=n[l];if(!o[c]||typeof o[c]!="object")return{removed:!1};o=o[c]}let i=n[n.length-1];return i in o?(delete o[i],await me(this.modelPath,JSON.stringify(t,null,2)),console.log(`${re} Removed token "${e}" from model`),{removed:!0}):{removed:!1}}async removeComponent(e){let t=await this.loadModel();if(!t)return{removed:!1};let n=t.components;return!n||!n[e]?{removed:!1}:(delete n[e],await me(this.modelPath,JSON.stringify(t,null,2)),console.log(`${re} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=new Set(e.materializedIds),o=(await this.decisionStore.listDecisionIds()).filter(l=>!t.has(l));return o.length===0?[]:(await this.decisionStore.loadDecisions(o)).filter(l=>l.resolutions.some(c=>{var d;let p=(d=c.finalScope)!=null?d:c.inferredScope;return(p==null?void 0:p.breadth)==="pattern"}))}async run(){var e,t,n,o,i,l,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 d=p.map(U=>U.id);console.log(`${re} Processing ${d.length} pattern-scoped decision(s): ${d.join(", ")}`),(t=(e=this.options).onEvent)==null||t.call(e,{type:"materialize_started",decisionIds:d});let S=await this.loadModel(),x=qt(p,S),b=!0,y;try{let{result:U}=Re(`mat-${Date.now()}`,{prompt:x,projectRoot:this.projectRoot,maxTurns:(n=this.options.maxTurns)!=null?n:5,maxBudgetUsd:(o=this.options.maxBudgetUsd)!=null?o:.5,allowedTools:["Read"],claudePath:(i=this.options.claudePath)!=null?i:"claude"}),P=await U;if(!P.success)b=!1,y=P.error,console.error(`${re} Claude spawn error:`,y);else{let L=Wt(P.text);L?(await me(this.modelPath,JSON.stringify(L,null,2)),console.log(`${re} Successfully materialized ${d.length} decision(s) \u2192 ${this.modelPath}`)):(b=!1,y="No <model> block found in response",console.error(`${re} ${y}`))}}catch(U){b=!1,y=U instanceof Error?U.message:String(U),console.error(`${re} Error:`,y)}let J=await this.loadIndex(),F=new Set(J.materializedIds);for(let U of d)F.add(U);return J.materializedIds=[...F],J.lastRunAt=Date.now(),J.lastRunDecisionIds=d,J.lastRunError=y!=null?y:null,await this.persistIndex(J),(c=(l=this.options).onEvent)==null||c.call(l,{type:"materialize_done",decisionIds:d,success:b,error:y}),{processedIds:d,success:b,error:y}}finally{this.running=!1}}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await ut(this.indexPath,"utf-8"),t=JSON.parse(e);return this.cachedIndex=t,t}catch(e){return this.cachedIndex=V(C({},Gt),{materializedIds:[],lastRunDecisionIds:[]}),this.cachedIndex}}async persistIndex(e){this.cachedIndex=e;try{await me(this.indexPath,JSON.stringify(e,null,2))}catch(t){console.error(`${re} Failed to write index:`,t)}}};function Wt(r){let e=r.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!(e!=null&&e[1]))return null;try{let t=JSON.parse(e[1]);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch(t){return null}}function qt(r,e){let t=r.map(o=>{let l=o.resolutions.filter(d=>{var x;let S=(x=d.finalScope)!=null?x:d.inferredScope;return(S==null?void 0:S.breadth)==="pattern"}).map(d=>{var y,J,F,U;let S=(y=d.finalScope)!=null?y:d.inferredScope,x=(J=S==null?void 0:S.target)!=null?J:"unknown",b=(U=(F=d.filesModified)==null?void 0:F.join(", "))!=null?U:"none";return`- **${d.summary}** [scope: pattern/${x}]
31
- Files modified: ${b}`}).join(`
32
- `),c=o.annotations.map(d=>d.instruction).filter(Boolean).join(`
33
- `),p=o.gitDiff?`
29
+ </html>`}import{spawn as Bt}from"child_process";import{createInterface as Jt}from"readline";var Ut=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),lt=1e5;function Ft(r){var s,i,l,a;let e=((s=r.input)==null?void 0:s.file_path)||((i=r.input)==null?void 0:i.path);if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Ut.has(t))return;let n;if(r.name==="Write"&&typeof((l=r.input)==null?void 0:l.content)=="string"?n=r.input.content:r.name==="Edit"&&typeof((a=r.input)==null?void 0:a.new_string)=="string"&&(n=r.input.new_string),!!n)return n.length>lt?n.slice(0,lt)+`
30
+ \u2026[truncated]`:n}function Ee(r,e){let{prompt:t,projectRoot:n,maxTurns:s=40,maxBudgetUsd:i=1,allowedTools:l=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:a="claude",resumeSessionId:u,model:d,timeoutMs:v=3e5,onEvent:y}=e,I=[];u?I.push("--resume",u,"-p",t):I.push("-p",t),I.push("--output-format","stream-json","--verbose","--max-turns",String(s),"--max-budget-usd",String(i)),d&&I.push("--model",d);for(let W of l)I.push("--allowedTools",W);let g=Bt(a,I,{cwd:n,stdio:["ignore","pipe","pipe"],env:K(C({},process.env),{ANTHROPIC_API_KEY:void 0})}),_=new Promise(W=>{var P;let J,k=[],j=[],D=!1,Z="",U=!1,ie=setTimeout(()=>{U=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch(R){}},5e3)},v),F=Jt({input:g.stdout}),H=new Set;F.on("line",R=>{var M,O,te,fe,xe,Pe,Ie,be,ke;if(R.trim())try{let Q=JSON.parse(R);Q.session_id&&!J&&(J=Q.session_id);let Ne=(O=Q.type)!=null?O:(M=Q.event)!=null&&M.type?`event.${Q.event.type}`:"unknown";if(H.add(Ne),Q.type==="result"&&Q.result&&k.length===0){let N=typeof Q.result=="string"?Q.result:"";N&&(k.push(N),y==null||y({type:"delta",jobId:r,text:N},r))}if(Q.type==="assistant"&&Array.isArray((te=Q.message)==null?void 0:te.content))for(let N of Q.message.content){if(N.type==="text"&&N.text&&(k.push(N.text),y==null||y({type:"delta",jobId:r,text:N.text},r)),N.type==="tool_use"&&N.name){let Te=((fe=N.input)==null?void 0:fe.file_path)||((xe=N.input)==null?void 0:xe.path)||void 0,$e=Ft(N);y==null||y(C(C({type:"tool_use",jobId:r,tool:N.name},Te?{file:Te}:{}),$e?{content:$e}:{}),r),N.name==="Edit"&&((Pe=N.input)!=null&&Pe.file_path)?j.push({tool:"Edit",file_path:N.input.file_path,old_string:N.input.old_string,new_string:N.input.new_string,replace_all:N.input.replace_all}):N.name==="Write"&&((Ie=N.input)!=null&&Ie.file_path)&&j.push({tool:"Write",file_path:N.input.file_path,content:N.input.content})}N.type==="thinking"&&N.thinking&&(y==null||y({type:"thinking",jobId:r,text:N.thinking},r))}Q.type==="user"&&((ke=(be=Q.tool_use_result)==null?void 0:be.file)!=null&&ke.filePath)&&(y==null||y({type:"tool_use",jobId:r,tool:"Read",file:Q.tool_use_result.file.filePath},r))}catch(Q){}});let E=[];(P=g.stderr)==null||P.on("data",R=>{E.push(R.toString())}),g.on("close",R=>{if(clearTimeout(ie),F.close(),k.length===0&&H.size>0&&console.warn(`[Claude:${r}] No text captured. Event types seen: ${[...H].join(", ")}`),U)D=!0,Z=`Timed out after ${Math.round(v/6e4)} minutes`;else if(R!==0&&R!==null){D=!0;let M=E.join("").trim(),O=k.length===0&&H.size>0?` (no text captured, event types: ${[...H].join(", ")})`:"";Z=M||`Claude process exited with code ${R}${O}`}W({sessionId:J,text:k.join(""),success:!D,error:D?Z:void 0,fileEdits:j.length>0?j:void 0})}),g.on("error",R=>{clearTimeout(ie),D=!0,Z=R.message,W({sessionId:J,text:k.join(""),success:!1,error:Z,fileEdits:j.length>0?j:void 0})})});return{process:g,result:_}}import{spawn as Lt}from"child_process";import{createInterface as zt}from"readline";function jt(r){let e=r.match(new RegExp('^\\/bin\\/(?:ba)?sh\\s+-\\w+\\s+"(.*)"$',"s"));return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):r}function dt(r,e){let{prompt:t,projectRoot:n,screenshotPath:s,resumeSessionId:i,model:l,onEvent:a}=e,u=[];i?(u.push("exec","resume",i),l&&u.push("-m",l),u.push("--json","--full-auto",t),s&&u.push("--image",s)):(u.push("exec","--json","--full-auto"),l&&u.push("-m",l),u.push(t),s&&u.push("--image",s));let d=Lt("codex",u,{cwd:n,stdio:["ignore","pipe","pipe"],env:C({},process.env)}),v=new Promise(y=>{var Z;let I,g=[],_=[],W=!1,J="",k=zt({input:d.stdout}),j=new Set;k.on("line",U=>{var ie,F,H,E;if(U.trim())try{let P=JSON.parse(U),R=(ie=P.type)!=null?ie:"unknown";if(j.add(R),R==="thread.started"&&P.thread_id&&!I&&(I=P.thread_id),(R==="item.agentMessage.delta"||R==="item/agentMessage/delta")&&((F=P.delta)!=null&&F.text)&&(g.push(P.delta.text),a==null||a({type:"delta",jobId:r,text:P.delta.text},r)),(R==="item.reasoning.delta"||R==="item/reasoning/delta")&&((H=P.delta)!=null&&H.text)&&(a==null||a({type:"thinking",jobId:r,text:P.delta.text},r)),(R==="item.started"||R==="item/started")&&P.item){let M=P.item.type;if(M==="command_execution"){let O=P.item.command,te=O?jt(O):void 0,fe=te?`Bash: ${te.split(`
31
+ `)[0].slice(0,80)}`:"Bash";_.push(fe),a==null||a(C({type:"tool_use",jobId:r,tool:"Bash"},te?{content:te}:{}),r)}else if(M==="file_change"){let O=P.item.filename||P.item.path;_.push(O?`Edit ${O.split("/").pop()}`:"Edit"),a==null||a(C({type:"tool_use",jobId:r,tool:"Edit"},O?{file:O}:{}),r)}else if(M==="file_read"){let O=P.item.filename||P.item.path;_.push(O?`Read ${O.split("/").pop()}`:"Read"),a==null||a(C({type:"tool_use",jobId:r,tool:"Read"},O?{file:O}:{}),r)}else if(M==="web_search")_.push("WebSearch"),a==null||a({type:"tool_use",jobId:r,tool:"WebSearch"},r);else if(M==="mcp_tool_call"){let O=P.item.tool_name||P.item.name||"MCP";_.push(O),a==null||a({type:"tool_use",jobId:r,tool:O},r)}}if((R==="item.completed"||R==="item/completed")&&P.item){if(P.item.type==="agent_message"){let M=P.item.text;typeof M=="string"&&M&&(g.push(M),a==null||a({type:"delta",jobId:r,text:M},r))}else if(P.item.type==="reasoning"){let M=P.item.text;typeof M=="string"&&M&&(a==null||a({type:"thinking",jobId:r,text:M},r))}else if(P.item.type==="file_change"&&Array.isArray(P.item.changes))for(let M of P.item.changes){let O=M.path||M.filename,te=M.kind==="add"?"Write":"Edit";O&&(_.push(`${te} ${O.split("/").pop()}`),a==null||a({type:"tool_use",jobId:r,tool:te,file:O},r))}}R==="turn.failed"&&(W=!0,J=((E=P.error)==null?void 0:E.message)||P.message||"Turn failed")}catch(P){}});let D=[];(Z=d.stderr)==null||Z.on("data",U=>{D.push(U.toString())}),d.on("close",U=>{k.close(),g.length===0&&j.size>0&&console.warn(`[Codex:${r}] No text captured. Event types seen: ${[...j].join(", ")}`),U!==0&&U!==null&&(W=!0,J=D.join("")||`Codex process exited with code ${U}`),y({sessionId:I,text:g.join(""),success:!W,error:W?J:void 0,toolsUsed:_.length>0?_:void 0})}),d.on("error",U=>{W=!0,J=U.message,y({sessionId:I,text:g.join(""),success:!1,error:J,toolsUsed:_.length>0?_:void 0})})});return{process:d,result:v}}import{execFile as Gt}from"child_process";import{copyFile as ut,mkdir as pt,readdir as Wt,readFile as Ht,writeFile as qt}from"fs/promises";import{join as he}from"path";var Me=class{constructor(e){this.projectRoot=e;let t=he(e,".popmelt");this.decisionsDir=he(t,"decisions"),this.screenshotsDir=he(t,"screenshots")}async persist(e,t,n){try{await pt(this.decisionsDir,{recursive:!0}),await pt(this.screenshotsDir,{recursive:!0});try{await ut(t,he(this.screenshotsDir,`s-${e.id}.png`))}catch(s){}for(let s=0;s<n.length;s++)try{let i=e.pastedImagePaths[s];i&&await ut(n[s],he(this.screenshotsDir,i.replace("screenshots/","")))}catch(i){}await qt(he(this.decisionsDir,`d-${e.id}.json`),JSON.stringify(e,null,2))}catch(s){console.error("[DecisionStore] Failed to persist decision record:",s)}}async listDecisionIds(){try{return(await Wt(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch(e){return[]}}async loadDecision(e){try{let t=await Ht(he(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch(t){return null}}async loadDecisions(e){return(await Promise.all(e.map(n=>this.loadDecision(n)))).filter(n=>n!==null)}captureGitDiff(e){return new Promise(t=>{Gt("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(n,s)=>{if(n){t(null);return}t(s||null)})})}};import{readFile as ht,writeFile as ge}from"fs/promises";import{join as Je}from"path";var ae="[Materializer]",Qt={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Ce=class{constructor(e,t,n={}){this.projectRoot=e;this.decisionStore=t;this.options=n;this.cachedIndex=null;this.running=!1;let s=Je(e,".popmelt");this.indexPath=Je(s,"materialized.json"),this.modelPath=Je(s,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await ht(this.modelPath,"utf-8");return JSON.parse(e)}catch(e){return null}}async addComponent(e){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]}),(!t.components||typeof t.components!="object")&&(t.components={});let n=t.components;return n[e]?{added:!1,alreadyExists:!0}:(n[e]={description:""},await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ae} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,t){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]});let s=e.split("."),i=n;for(let u=0;u<s.length-1;u++){let d=s[u];(!i[d]||typeof i[d]!="object")&&(i[d]={}),i=i[d]}let l=s[s.length-1],a;try{a=JSON.parse(t)}catch(u){a=null}if(a&&typeof a=="object"&&a!==null&&"value"in a)i[l]=a;else{let u=i[l];u&&typeof u=="object"&&u!==null&&"value"in u?u.value=t:i[l]=t}return await ge(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Updated token "${e}" \u2192 "${t.slice(0,80)}"`),{updated:!0}}async removeToken(e){let t=await this.loadModel();if(!t)return{removed:!1};let n=e.split("."),s=t;for(let l=0;l<n.length-1;l++){let a=n[l];if(!s[a]||typeof s[a]!="object")return{removed:!1};s=s[a]}let i=n[n.length-1];return i in s?(delete s[i],await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ae} Removed token "${e}" from model`),{removed:!0}):{removed:!1}}async removeComponent(e){let t=await this.loadModel();if(!t)return{removed:!1};let n=t.components;return!n||!n[e]?{removed:!1}:(delete n[e],await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ae} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=new Set(e.materializedIds),s=(await this.decisionStore.listDecisionIds()).filter(l=>!t.has(l));return s.length===0?[]:(await this.decisionStore.loadDecisions(s)).filter(l=>l.resolutions.some(a=>{var d;let u=(d=a.finalScope)!=null?d:a.inferredScope;return(u==null?void 0:u.breadth)==="pattern"}))}async run(){var e,t,n,s,i,l,a;if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;try{let u=await this.getUnmaterializedPatternDecisions();if(u.length===0)return{processedIds:[],success:!0};let d=u.map(J=>J.id);console.log(`${ae} Processing ${d.length} pattern-scoped decision(s): ${d.join(", ")}`),(t=(e=this.options).onEvent)==null||t.call(e,{type:"materialize_started",decisionIds:d});let v=await this.loadModel(),y=Yt(u,v),I=!0,g;try{let{result:J}=Ee(`mat-${Date.now()}`,{prompt:y,projectRoot:this.projectRoot,maxTurns:(n=this.options.maxTurns)!=null?n:5,maxBudgetUsd:(s=this.options.maxBudgetUsd)!=null?s:.5,allowedTools:["Read"],claudePath:(i=this.options.claudePath)!=null?i:"claude"}),k=await J;if(!k.success)I=!1,g=k.error,console.error(`${ae} Claude spawn error:`,g);else{let j=Xt(k.text);j?(await ge(this.modelPath,JSON.stringify(j,null,2)),console.log(`${ae} Successfully materialized ${d.length} decision(s) \u2192 ${this.modelPath}`)):(I=!1,g="No <model> block found in response",console.error(`${ae} ${g}`))}}catch(J){I=!1,g=J instanceof Error?J.message:String(J),console.error(`${ae} Error:`,g)}let _=await this.loadIndex(),W=new Set(_.materializedIds);for(let J of d)W.add(J);return _.materializedIds=[...W],_.lastRunAt=Date.now(),_.lastRunDecisionIds=d,_.lastRunError=g!=null?g:null,await this.persistIndex(_),(a=(l=this.options).onEvent)==null||a.call(l,{type:"materialize_done",decisionIds:d,success:I,error:g}),{processedIds:d,success:I,error:g}}finally{this.running=!1}}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await ht(this.indexPath,"utf-8"),t=JSON.parse(e);return this.cachedIndex=t,t}catch(e){return this.cachedIndex=K(C({},Qt),{materializedIds:[],lastRunDecisionIds:[]}),this.cachedIndex}}async persistIndex(e){this.cachedIndex=e;try{await ge(this.indexPath,JSON.stringify(e,null,2))}catch(t){console.error(`${ae} Failed to write index:`,t)}}};function Xt(r){let e=r.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!(e!=null&&e[1]))return null;try{let t=JSON.parse(e[1]);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch(t){return null}}function Yt(r,e){let t=r.map(s=>{let l=s.resolutions.filter(d=>{var y;let v=(y=d.finalScope)!=null?y:d.inferredScope;return(v==null?void 0:v.breadth)==="pattern"}).map(d=>{var g,_,W,J;let v=(g=d.finalScope)!=null?g:d.inferredScope,y=(_=v==null?void 0:v.target)!=null?_:"unknown",I=(J=(W=d.filesModified)==null?void 0:W.join(", "))!=null?J:"none";return`- **${d.summary}** [scope: pattern/${y}]
32
+ Files modified: ${I}`}).join(`
33
+ `),a=s.annotations.map(d=>d.instruction).filter(Boolean).join(`
34
+ `),u=s.gitDiff?`
34
35
  \`\`\`diff
35
- ${o.gitDiff.slice(0,2e3)}
36
- \`\`\``:"";return`### Decision ${o.id} (${new Date(o.createdAt).toISOString()})
37
- Page: ${o.url}
36
+ ${s.gitDiff.slice(0,2e3)}
37
+ \`\`\``:"";return`### Decision ${s.id} (${new Date(s.createdAt).toISOString()})
38
+ Page: ${s.url}
38
39
  ${l}
39
- ${p}
40
- ${c?`
40
+ ${u}
41
+ ${a?`
41
42
  Original instructions:
42
- ${c}`:""}`}).join(`
43
+ ${a}`:""}`}).join(`
43
44
 
44
45
  `);return`You are extracting a local design model from accumulated design decisions.
45
46
 
@@ -95,39 +96,40 @@ Example:
95
96
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
96
97
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
97
98
  - bindings: Tailwind class names (without responsive prefixes) that use this token
98
- Include property and bindings when the decision context has class-level evidence.`}import{readFile as ft}from"fs/promises";import{homedir as mt}from"os";import{join as ge}from"path";var Ue=/popmelt/i;function Fe(){return{found:!1,name:null,scope:null,disabled:!1}}function ye(r,e,t=!1){return{found:!0,name:r,scope:e,disabled:t}}function Ce(r){for(let e of Object.keys(r))if(Ue.test(e))return e;return null}async function Je(r){try{let e=await ft(r,"utf-8");return JSON.parse(e)}catch(e){return null}}async function Le(r){let e=mt(),t=await Je(ge(e,".claude.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=Ce(o.mcpServers);if(i)return ye(i,"user")}if(o.projects&&typeof o.projects=="object"){let l=o.projects[r];if(l&&typeof l=="object"){let c=l;if(c.mcpServers&&typeof c.mcpServers=="object"){let p=Ce(c.mcpServers);if(p){let d=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(S=>Ue.test(S));return ye(p,"project",d)}}}}}let n=await Je(ge(r,".mcp.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let l=Ce(o.mcpServers);if(l){let c=await pt(r,l);return ye(l,"mcp.json",c)}}let i=Ce(o);if(i&&i!=="mcpServers"){let l=await pt(r,i);return ye(i,"mcp.json",l)}}return Fe()}async function pt(r,e){let t=ge(r,".claude","settings.local.json"),n=await Je(t);if(n&&typeof n=="object"){let o=n;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var Qt=/^\[mcp_servers\.([^\]]+)\]/;function Xt(r){let e=r.split(`
99
- `),t=[],n=null;for(let o of e){let i=o.match(Qt);i?(n&&t.push({name:n.name,body:n.bodyLines.join(`
100
- `)}),n={name:i[1],bodyLines:[]}):o.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
101
- `)}),n=null):n&&n.bodyLines.push(o)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
102
- `)}),t}function Yt(r){return/enabled\s*=\s*false/i.test(r)}async function je(r){let e=process.env.CODEX_HOME||ge(mt(),".codex"),t=await ht(ge(e,"config.toml"),"user");if(t.found)return t;let n=await ht(ge(r,".codex","config.toml"),"project");return n.found?n:Fe()}async function ht(r,e){try{let t=await ft(r,"utf-8"),n=Xt(t);for(let o of n)if(Ue.test(o.name)){let i=Yt(o.body);return ye(o.name,e,i)}}catch(t){}return Fe()}import{mkdir as Vt,readFile as gt,writeFile as yt}from"fs/promises";import{homedir as wt}from"os";import{dirname as Kt,join as ze}from"path";var vt="https://mcp.popmelt.com/mcp";async function St(r=vt){let e=ze(wt(),".claude.json"),t;try{let o=await gt(e,"utf-8");t=JSON.parse(o)}catch(o){t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let n=t.mcpServers;for(let o of Object.keys(n))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:r},await yt(e,JSON.stringify(t,null,2)+`
103
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function xt(r=vt){let e=process.env.CODEX_HOME||ze(wt(),".codex"),t=ze(e,"config.toml"),n;try{n=await gt(t,"utf-8")}catch(i){n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Vt(Kt(t),{recursive:!0});let o=`
99
+ Include property and bindings when the decision context has class-level evidence.`}import{readFile as gt}from"fs/promises";import{homedir as yt}from"os";import{join as ye}from"path";var Fe=/popmelt/i;function Le(){return{found:!1,name:null,scope:null,disabled:!1}}function ve(r,e,t=!1){return{found:!0,name:r,scope:e,disabled:t}}function Oe(r){for(let e of Object.keys(r))if(Fe.test(e))return e;return null}async function Ue(r){try{let e=await gt(r,"utf-8");return JSON.parse(e)}catch(e){return null}}async function ze(r){let e=yt(),t=await Ue(ye(e,".claude.json"));if(t&&typeof t=="object"){let s=t;if(s.mcpServers&&typeof s.mcpServers=="object"){let i=Oe(s.mcpServers);if(i)return ve(i,"user")}if(s.projects&&typeof s.projects=="object"){let l=s.projects[r];if(l&&typeof l=="object"){let a=l;if(a.mcpServers&&typeof a.mcpServers=="object"){let u=Oe(a.mcpServers);if(u){let d=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(v=>Fe.test(v));return ve(u,"project",d)}}}}}let n=await Ue(ye(r,".mcp.json"));if(n&&typeof n=="object"){let s=n;if(s.mcpServers&&typeof s.mcpServers=="object"){let l=Oe(s.mcpServers);if(l){let a=await ft(r,l);return ve(l,"mcp.json",a)}}let i=Oe(s);if(i&&i!=="mcpServers"){let l=await ft(r,i);return ve(i,"mcp.json",l)}}return Le()}async function ft(r,e){let t=ye(r,".claude","settings.local.json"),n=await Ue(t);if(n&&typeof n=="object"){let s=n;if(Array.isArray(s.disabledMcpjsonServers))return s.disabledMcpjsonServers.some(i=>i===e)}return!1}var Vt=/^\[mcp_servers\.([^\]]+)\]/;function Kt(r){let e=r.split(`
100
+ `),t=[],n=null;for(let s of e){let i=s.match(Vt);i?(n&&t.push({name:n.name,body:n.bodyLines.join(`
101
+ `)}),n={name:i[1],bodyLines:[]}):s.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
102
+ `)}),n=null):n&&n.bodyLines.push(s)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
103
+ `)}),t}function Zt(r){return/enabled\s*=\s*false/i.test(r)}async function je(r){let e=process.env.CODEX_HOME||ye(yt(),".codex"),t=await mt(ye(e,"config.toml"),"user");if(t.found)return t;let n=await mt(ye(r,".codex","config.toml"),"project");return n.found?n:Le()}async function mt(r,e){try{let t=await gt(r,"utf-8"),n=Kt(t);for(let s of n)if(Fe.test(s.name)){let i=Zt(s.body);return ve(s.name,e,i)}}catch(t){}return Le()}import{mkdir as en,readFile as wt,writeFile as vt}from"fs/promises";import{homedir as St}from"os";import{dirname as tn,join as Ge}from"path";var xt="https://mcp.popmelt.com/mcp";async function Pt(r=xt){let e=Ge(St(),".claude.json"),t;try{let s=await wt(e,"utf-8");t=JSON.parse(s)}catch(s){t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let n=t.mcpServers;for(let s of Object.keys(n))if(/popmelt/i.test(s))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:r},await vt(e,JSON.stringify(t,null,2)+`
104
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function It(r=xt){let e=process.env.CODEX_HOME||Ge(St(),".codex"),t=Ge(e,"config.toml"),n;try{n=await wt(t,"utf-8")}catch(i){n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await en(tn(t),{recursive:!0});let s=`
104
105
  [mcp_servers.popmelt]
105
106
  url = "${r}"
106
- `;return await yt(t,n+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function He(r){let t=(r.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],o=await Zt(r),i=Buffer.from(`--${n}`),l=Buffer.from(`--${n}--`),c,p,d,S,x,b,y,J,F,U,P,L,A=[],j=[],W=0,oe=[];for(;W<o.length;){let D=o.indexOf(i,W);if(D===-1)break;let z=D+i.length;if(o.slice(D,D+l.length).equals(l))break;let g=z;o[g]===13&&o[g+1]===10&&(g+=2);let N=o.indexOf(`\r
107
+ `;return await vt(t,n+s,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function We(r){let t=(r.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],s=await nn(r),i=Buffer.from(`--${n}`),l=Buffer.from(`--${n}--`),a,u,d,v,y,I,g,_,W,J,k,j,D=[],Z=[],U=0,ie=[];for(;U<s.length;){let F=s.indexOf(i,U);if(F===-1)break;let H=F+i.length;if(s.slice(F,F+l.length).equals(l))break;let E=H;s[E]===13&&s[E+1]===10&&(E+=2);let P=s.indexOf(`\r
107
108
  \r
108
- `,g);if(N===-1)break;let k=o.slice(g,N).toString("utf-8"),H=N+4,ne=o.indexOf(i,H),he=ne!==-1?ne-2:o.length;oe.push({headers:k,body:o.slice(H,he)}),W=ne!==-1?ne:o.length}for(let D of oe){let z=D.headers.match(/name="([^"]+)"/);if(!z)continue;let g=z[1];if(g==="screenshot")c=D.body;else if(g==="feedback")p=D.body.toString("utf-8");else if(g==="color")d=D.body.toString("utf-8");else if(g==="provider")S=D.body.toString("utf-8");else if(g==="model")x=D.body.toString("utf-8");else if(g==="goal")b=D.body.toString("utf-8");else if(g==="pageUrl")y=D.body.toString("utf-8");else if(g==="viewport")J=D.body.toString("utf-8");else if(g==="planId")F=D.body.toString("utf-8");else if(g==="manifest")U=D.body.toString("utf-8");else if(g==="tasks")P=D.body.toString("utf-8");else if(g==="sourceId")L=D.body.toString("utf-8");else if(g.startsWith("screenshot-")){let N=g.slice(11);try{let k=decodeURIComponent(N);j.push({pathname:k,data:D.body})}catch(k){}}else if(g.startsWith("image-")){let N=g.split("-"),k=parseInt(N[N.length-1],10),H=N.slice(1,-1).join("-");H&&!isNaN(k)&&A.push({annotationId:H,index:k,data:D.body})}}if(!c)throw new Error("Missing screenshot field");return p||(p=""),{screenshot:c,feedback:p,color:d,provider:S,model:x,goal:b,pageUrl:y,viewport:J,planId:F,manifest:U,tasks:P,sourceId:L,pastedImages:A,pageScreenshots:j}}function Zt(r){return new Promise((e,t)=>{let n=[];r.on("data",o=>n.push(o)),r.on("end",()=>e(Buffer.concat(n))),r.on("error",t)})}function we(r,e){var n,o;let t=[];if(r.annotations.length>0){t.push("## Annotations");for(let i of r.annotations){let l=i.elements.map(d=>{let S=[d.selector];return d.reactComponent&&S.push(`(${d.reactComponent})`),S.join(" ")}).join(", "),c=i.instruction||"No text";t.push(`- id=${i.id} [${i.type}] ${c} \u2192 Elements: ${l||"none"}`);let p=e==null?void 0:e[i.id];if(p&&p.length>0)for(let d of p)t.push(` Attached image: use the Read tool to view ${d}`)}}if(r.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 i of r.styleModifications){let l=(n=i.element)!=null&&n.reactComponent?`(${i.element.reactComponent})`:"";for(let c of i.changes)t.push(`- ${i.selector} ${l}: ${c.property} ${c.original} \u2192 ${c.modified}`)}}if((o=r.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 i of r.spacingTokenChanges){t.push(`
109
- ### ${i.tokenName}: ${i.originalPx}px \u2192 ${i.newPx}px`);for(let l of i.affectedElements){let c=l.reactComponent?` (${l.reactComponent})`:"";l.matchedClass&&l.suggestedClass?t.push(`- ${l.selector}${c}: \`${l.matchedClass}\` \u2192 \`${l.suggestedClass}\``):t.push(`- ${l.selector}${c}: ${l.property} ${i.originalPx}px \u2192 ${i.newPx}px`),t.push(` class="${l.className}"`)}}}if(r.inspectedElement){let i=r.inspectedElement;t.push(""),t.push("## Inspected Element"),t.push("The developer has this element selected in the inspector:");let l=[i.selector];i.reactComponent&&l.push(`(${i.reactComponent})`),i.context&&l.push(`in ${i.context}`),i.textContent&&l.push(`"${i.textContent.slice(0,80)}"`),t.push(`- ${l.join(" ")}`)}return t.join(`
110
- `)}function It(r,e,t){var l,c;let n=[],i=new Set(e.annotations.map(p=>p.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!i&&(t==null?void 0:t.provider)!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t!=null&&t.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let p=0;for(let d of t.threadHistory)if(d.role==="human")p++,d.replyToQuestion?(n.push(`### Round ${p} (human) \u2014 reply`),n.push(`"${d.replyToQuestion}"`)):(n.push(`### Round ${p} (human)`),d.feedbackSummary&&n.push(`Annotations: ${d.feedbackSummary}`),d.annotationIds&&d.annotationIds.length>0&&n.push(`Annotation IDs: ${d.annotationIds.join(", ")}`));else if(d.question)n.push(`### Round ${p} (assistant) \u2014 question`),n.push(`"${d.question}"`);else{if(n.push(`### Round ${p} (assistant)`),d.responseText&&n.push(`Response: ${d.responseText}`),d.resolutions&&d.resolutions.length>0)for(let S of d.resolutions){let x=(l=S.finalScope)!=null?l:S.inferredScope,b=x?` [${x.breadth} ${x.target}]`:"";n.push(`- ${S.annotationId}: ${S.status}${b} \u2014 ${S.summary}`),S.filesModified&&S.filesModified.length>0&&n.push(` Files: ${S.filesModified.join(", ")}`)}d.toolsUsed&&d.toolsUsed.length>0&&n.push(`Tools used: ${d.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(t!=null&&t.designModel){n.push(""),n.push("## Established Design Policies"),n.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 p=t.designModel.rules;if(Array.isArray(p)&&p.length>0){n.push(""),n.push("Rules:");for(let x of p)typeof x=="string"&&n.push(`- ${x}`)}let d=t.designModel.tokens;d&&typeof d=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(d,null,2)),n.push("```"));let S=t.designModel.components;S&&typeof S=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(S,null,2)),n.push("```")),n.push(""),n.push("### Novel Pattern Detection"),n.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:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you decided to do (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(t!=null&&t.designModel||(n.push(""),n.push("## Design Context"),n.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.")),i){let p=(c=t==null?void 0:t.screenshotPaths)!=null?c:{},d=new Map;for(let S of e.annotations){let x=S.pathname||new URL(e.url).pathname;d.has(x)||d.set(x,[]),d.get(x).push(S)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[S,x]of d){n.push(""),n.push(`## Page: ${S}`);let b=p[S];b&&(t==null?void 0:t.provider)!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${b}`):!b&&(t==null?void 0:t.provider)!=="codex"&&(Object.keys(p).length===0?(n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${r}`),n.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):n.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let y=V(C({},e),{annotations:x,styleModifications:e.styleModifications}),J=we(y,t==null?void 0:t.imagePaths);J&&(n.push(""),n.push(J))}}else{let p=we(e,t==null?void 0:t.imagePaths);p&&(n.push(""),n.push(p))}return n.push(""),n.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."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output a resolution block listing what you did for each annotation:"),n.push("<resolution>"),n.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),n.push("</resolution>"),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
111
- `)}function Pt(r){var t;let e=r.match(/<question>\s*([\s\S]*?)\s*<\/question>/);return(t=e==null?void 0:e[1])!=null?t:null}function Tt(r,e,t,n){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: ${r}`);let i=e.find(l=>l.role==="human"&&l.feedbackContext);if(i!=null&&i.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),e.length>0){o.push(""),o.push("## Conversation History");let l=0;for(let c of e)c.role==="human"?(l++,c.replyToQuestion?(o.push(`### Round ${l} (human) \u2014 reply`),o.push(`"${c.replyToQuestion}"`)):(o.push(`### Round ${l} (human)`),c.feedbackSummary&&o.push(`Annotations: ${c.feedbackSummary}`))):c.question?(o.push(`### Round ${l} (assistant) \u2014 question`),o.push(`"${c.question}"`)):(o.push(`### Round ${l} (assistant)`),c.responseText&&o.push(`Response: ${c.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."),n&&n.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let l of n)o.push(`Attached image: use the Read tool to view the image at: ${l}`)}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(`
112
- `)}function en(r){if(typeof r!="object"||r===null)return!1;let e=r;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function tn(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 e=r;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!en(e[t]))return!1;return!0}function bt(r){let e=r.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!e||!e[1])return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(tn):[]}catch(t){return[]}}function kt(r){let e=r.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!(e!=null&&e[1]))return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(n=>{if(typeof n!="object"||n===null)return!1;let o=n;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[]}}var Oe=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.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(e,t){t?this.activeProcesses.set(e,t):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){let o=this.bufferEvent(t,e);for(let i of this.listeners)i(o,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let o=V(C({},t),{seq:n.nextSeq++});return n.events.push(o),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),o}getBufferedEvents(e,t=-1){var c;let n=this.eventBuffers.get(e),o=(c=this.accumulators.get(e))!=null?c:{response:"",thinking:""},i=this.activeJobs.has(e);if(!n)return null;let l=t<0?n.events:n.events.filter(p=>p.seq>t);return{jobId:e,events:l,currentSeq:n.nextSeq-1,accumulated:C({},o),jobActive:i}}accumulateText(e,t,n){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[t]+=n}getAccumulated(e){var t;return(t=this.accumulators.get(e))!=null?t:null}scheduleBufferCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,n)}cancelJob(e){let t=this.activeProcesses.get(e),n=this.activeJobs.get(e);return!t||!n?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),n.status="error",n.error="Cancelled by user",this.broadcast({type:"error",jobId:n.id,message:"Cancelled by user",cancelled:!0},n.id,n.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let t of e)this.cancelJob(t);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=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 n of t)try{n.kill("SIGTERM")}catch(o){}await Promise.all(t.map(n=>new Promise(o=>{let i=!1,l=()=>{i||(i=!0,o())};n.on("exit",l),n.on("error",l),setTimeout(()=>{if(!i){try{n.kill("SIGKILL")}catch(c){}setTimeout(l,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let n of this.cleanupTimers.values())clearTimeout(n);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId},e.id,e.sourceId),this.processor(e).catch(t=>{e.status="error",e.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:e.id,message:e.error},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{mkdir as nn,readFile as sn,writeFile as on}from"fs/promises";import{dirname as rn,join as an}from"path";var cn={version:1,threads:{}},_e=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=an(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await sn(this.filePath,"utf-8"),t=JSON.parse(e);if(t&&t.version===1&&t.threads)return this.cache=t,this.cache}catch(e){}return this.cache=V(C({},cn),{threads:{}}),this.cache}async getThread(e){var n;return(n=(await this.load()).threads[e])!=null?n:null}async findContinuationThread(e){if(e.length===0)return null;let t=await this.load(),n=new Set(e);for(let o of Object.values(t.threads))if(o.elementIdentifiers.some(l=>n.has(l)))return o;return null}async createThread(e,t){let n=await this.load(),o={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=o,await this.persist(),o}async appendMessage(e,t){let o=(await this.load()).threads[e];o&&(o.messages.push(t),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(e,t){let o=(await this.load()).threads[e];if(!o)return;let i=new Set(o.elementIdentifiers);for(let l of t)i.has(l)||o.elementIdentifiers.push(l);o.updatedAt=Date.now(),await this.persist()}async getThreadHistory(e,t=6){let n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await nn(rn(this.filePath),{recursive:!0}),await on(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};var Mn={};var xn=1111,In=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Pn=1800*1e3,Tn=3600*1e3;function Mt(r){if(!r)return!1;try{let e=new URL(r);return e.hostname==="localhost"||e.hostname==="127.0.0.1"}catch(e){return!1}}function bn(r,e){let t=r.headers.origin;Mt(t)&&(e.setHeader("Access-Control-Allow-Origin",t),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type"))}function T(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}function kn(r,e){if(!r)return e;let t=r.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,o,i]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(o,16)};${parseInt(i,16)}m${e}\x1B[0m`}function We(r,e){try{r.res.write(`event: ${e.type}
109
+ `,E);if(P===-1)break;let R=s.slice(E,P).toString("utf-8"),M=P+4,O=s.indexOf(i,M),te=O!==-1?O-2:s.length;ie.push({headers:R,body:s.slice(M,te)}),U=O!==-1?O:s.length}for(let F of ie){let H=F.headers.match(/name="([^"]+)"/);if(!H)continue;let E=H[1];if(E==="screenshot")a=F.body;else if(E==="feedback")u=F.body.toString("utf-8");else if(E==="color")d=F.body.toString("utf-8");else if(E==="provider")v=F.body.toString("utf-8");else if(E==="model")y=F.body.toString("utf-8");else if(E==="goal")I=F.body.toString("utf-8");else if(E==="pageUrl")g=F.body.toString("utf-8");else if(E==="viewport")_=F.body.toString("utf-8");else if(E==="planId")W=F.body.toString("utf-8");else if(E==="manifest")J=F.body.toString("utf-8");else if(E==="tasks")k=F.body.toString("utf-8");else if(E==="sourceId")j=F.body.toString("utf-8");else if(E.startsWith("screenshot-")){let P=E.slice(11);try{let R=decodeURIComponent(P);Z.push({pathname:R,data:F.body})}catch(R){}}else if(E.startsWith("image-")){let P=E.split("-"),R=parseInt(P[P.length-1],10),M=P.slice(1,-1).join("-");M&&!isNaN(R)&&D.push({annotationId:M,index:R,data:F.body})}}if(!a)throw new Error("Missing screenshot field");return u||(u=""),{screenshot:a,feedback:u,color:d,provider:v,model:y,goal:I,pageUrl:g,viewport:_,planId:W,manifest:J,tasks:k,sourceId:j,pastedImages:D,pageScreenshots:Z}}function nn(r){return new Promise((e,t)=>{let n=[];r.on("data",s=>n.push(s)),r.on("end",()=>e(Buffer.concat(n))),r.on("error",t)})}function Se(r,e){var n,s;let t=[];if(r.annotations.length>0){t.push("## Annotations");for(let i of r.annotations){let l=i.elements.map(d=>{let v=[d.selector];return d.reactComponent&&v.push(`(${d.reactComponent})`),v.join(" ")}).join(", "),a=i.instruction||"No text";t.push(`- id=${i.id} [${i.type}] ${a} \u2192 Elements: ${l||"none"}`);let u=e==null?void 0:e[i.id];if(u&&u.length>0)for(let d of u)t.push(` Attached image: use the Read tool to view ${d}`)}}if(r.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 i of r.styleModifications){let l=(n=i.element)!=null&&n.reactComponent?`(${i.element.reactComponent})`:"";for(let a of i.changes)t.push(`- ${i.selector} ${l}: ${a.property} ${a.original} \u2192 ${a.modified}`)}}if((s=r.spacingTokenChanges)!=null&&s.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 i of r.spacingTokenChanges){t.push(`
110
+ ### ${i.tokenName}: ${i.originalPx}px \u2192 ${i.newPx}px`);for(let l of i.affectedElements){let a=l.reactComponent?` (${l.reactComponent})`:"";l.matchedClass&&l.suggestedClass?t.push(`- ${l.selector}${a}: \`${l.matchedClass}\` \u2192 \`${l.suggestedClass}\``):t.push(`- ${l.selector}${a}: ${l.property} ${i.originalPx}px \u2192 ${i.newPx}px`),t.push(` class="${l.className}"`)}}}if(r.inspectedElement){let i=r.inspectedElement;t.push(""),t.push("## Inspected Element"),t.push("The developer has this element selected in the inspector:");let l=[i.selector];i.reactComponent&&l.push(`(${i.reactComponent})`),i.context&&l.push(`in ${i.context}`),i.textContent&&l.push(`"${i.textContent.slice(0,80)}"`),t.push(`- ${l.join(" ")}`)}return t.join(`
111
+ `)}function bt(r,e,t){var l,a;let n=[],i=new Set(e.annotations.map(u=>u.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!i&&(t==null?void 0:t.provider)!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t!=null&&t.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let u=0;for(let d of t.threadHistory)if(d.role==="human")u++,d.replyToQuestion?(n.push(`### Round ${u} (human) \u2014 reply`),n.push(`"${d.replyToQuestion}"`)):(n.push(`### Round ${u} (human)`),d.feedbackSummary&&n.push(`Annotations: ${d.feedbackSummary}`),d.annotationIds&&d.annotationIds.length>0&&n.push(`Annotation IDs: ${d.annotationIds.join(", ")}`));else if(d.question)n.push(`### Round ${u} (assistant) \u2014 question`),n.push(`"${d.question}"`);else{if(n.push(`### Round ${u} (assistant)`),d.responseText&&n.push(`Response: ${d.responseText}`),d.resolutions&&d.resolutions.length>0)for(let v of d.resolutions){let y=(l=v.finalScope)!=null?l:v.inferredScope,I=y?` [${y.breadth} ${y.target}]`:"";n.push(`- ${v.annotationId}: ${v.status}${I} \u2014 ${v.summary}`),v.filesModified&&v.filesModified.length>0&&n.push(` Files: ${v.filesModified.join(", ")}`)}d.toolsUsed&&d.toolsUsed.length>0&&n.push(`Tools used: ${d.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(t!=null&&t.designModel){n.push(""),n.push("## Established Design Policies"),n.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 u=t.designModel.rules;if(Array.isArray(u)&&u.length>0){n.push(""),n.push("Rules:");for(let y of u)typeof y=="string"&&n.push(`- ${y}`)}let d=t.designModel.tokens;d&&typeof d=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(d,null,2)),n.push("```"));let v=t.designModel.components;v&&typeof v=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(v,null,2)),n.push("```")),n.push(""),n.push("### Novel Pattern Detection"),n.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:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you decided to do (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(t!=null&&t.designModel||(n.push(""),n.push("## Design Context"),n.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.")),i){let u=(a=t==null?void 0:t.screenshotPaths)!=null?a:{},d=new Map;for(let v of e.annotations){let y=v.pathname||new URL(e.url).pathname;d.has(y)||d.set(y,[]),d.get(y).push(v)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[v,y]of d){n.push(""),n.push(`## Page: ${v}`);let I=u[v];I&&(t==null?void 0:t.provider)!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${I}`):!I&&(t==null?void 0:t.provider)!=="codex"&&(Object.keys(u).length===0?(n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${r}`),n.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):n.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let g=K(C({},e),{annotations:y,styleModifications:e.styleModifications}),_=Se(g,t==null?void 0:t.imagePaths);_&&(n.push(""),n.push(_))}}else{let u=Se(e,t==null?void 0:t.imagePaths);u&&(n.push(""),n.push(u))}return n.push(""),n.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."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output a resolution block listing what you did for each annotation:"),n.push("<resolution>"),n.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),n.push("</resolution>"),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
112
+ `)}function kt(r){var t;let e=r.match(/<question>\s*([\s\S]*?)\s*<\/question>/);return(t=e==null?void 0:e[1])!=null?t:null}function Tt(r,e,t,n){let s=[];s.push("You are continuing work on a UI based on the developer's reply to your question."),s.push(""),t!=="codex"&&s.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`);let i=e.find(l=>l.role==="human"&&l.feedbackContext);if(i!=null&&i.feedbackContext&&(s.push(""),s.push(i.feedbackContext)),e.length>0){s.push(""),s.push("## Conversation History");let l=0;for(let a of e)a.role==="human"?(l++,a.replyToQuestion?(s.push(`### Round ${l} (human) \u2014 reply`),s.push(`"${a.replyToQuestion}"`)):(s.push(`### Round ${l} (human)`),a.feedbackSummary&&s.push(`Annotations: ${a.feedbackSummary}`))):a.question?(s.push(`### Round ${l} (assistant) \u2014 question`),s.push(`"${a.question}"`)):(s.push(`### Round ${l} (assistant)`),a.responseText&&s.push(`Response: ${a.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."),n&&n.length>0){s.push(""),s.push("## Attached Images"),s.push("The developer attached reference images with their reply:");for(let l of n)s.push(`Attached image: use the Read tool to view the image at: ${l}`)}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(`
113
+ `)}function sn(r){if(typeof r!="object"||r===null)return!1;let e=r;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function on(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 e=r;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!sn(e[t]))return!1;return!0}function $t(r){let e=r.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!e||!e[1])return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(on):[]}catch(t){return[]}}function Rt(r){let e=r.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!(e!=null&&e[1]))return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(n=>{if(typeof n!="object"||n===null)return!1;let s=n;return(s.category==="token"||s.category==="component"||s.category==="element")&&typeof s.element=="string"&&typeof s.decision=="string"&&typeof s.reason=="string"}):[]}catch(t){return[]}}var Ae=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.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(e,t){t?this.activeProcesses.set(e,t):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){let s=this.bufferEvent(t,e);for(let i of this.listeners)i(s,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let s=K(C({},t),{seq:n.nextSeq++});return n.events.push(s),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),s}getBufferedEvents(e,t=-1){var a;let n=this.eventBuffers.get(e),s=(a=this.accumulators.get(e))!=null?a:{response:"",thinking:""},i=this.activeJobs.has(e);if(!n)return null;let l=t<0?n.events:n.events.filter(u=>u.seq>t);return{jobId:e,events:l,currentSeq:n.nextSeq-1,accumulated:C({},s),jobActive:i}}accumulateText(e,t,n){let s=this.accumulators.get(e);s||(s={response:"",thinking:""},this.accumulators.set(e,s)),s[t]+=n}getAccumulated(e){var t;return(t=this.accumulators.get(e))!=null?t:null}scheduleBufferCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,n)}cancelJob(e){let t=this.activeProcesses.get(e),n=this.activeJobs.get(e);return!t||!n?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),n.status="error",n.error="Cancelled by user",this.broadcast({type:"error",jobId:n.id,message:"Cancelled by user",cancelled:!0},n.id,n.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let t of e)this.cancelJob(t);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=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 n of t)try{n.kill("SIGTERM")}catch(s){}await Promise.all(t.map(n=>new Promise(s=>{let i=!1,l=()=>{i||(i=!0,s())};n.on("exit",l),n.on("error",l),setTimeout(()=>{if(!i){try{n.kill("SIGKILL")}catch(a){}setTimeout(l,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let n of this.cleanupTimers.values())clearTimeout(n);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId},e.id,e.sourceId),this.processor(e).catch(t=>{e.status="error",e.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:e.id,message:e.error},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{mkdir as rn,readFile as an,writeFile as cn}from"fs/promises";import{dirname as ln,join as dn}from"path";var un={version:1,threads:{}},_e=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=dn(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await an(this.filePath,"utf-8"),t=JSON.parse(e);if(t&&t.version===1&&t.threads)return this.cache=t,this.cache}catch(e){}return this.cache=K(C({},un),{threads:{}}),this.cache}async getThread(e){var n;return(n=(await this.load()).threads[e])!=null?n:null}async findContinuationThread(e){if(e.length===0)return null;let t=await this.load(),n=new Set(e);for(let s of Object.values(t.threads))if(s.elementIdentifiers.some(l=>n.has(l)))return s;return null}async createThread(e,t){let n=await this.load(),s={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=s,await this.persist(),s}async appendMessage(e,t){let s=(await this.load()).threads[e];s&&(s.messages.push(t),s.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(e,t){let s=(await this.load()).threads[e];if(!s)return;let i=new Set(s.elementIdentifiers);for(let l of t)i.has(l)||s.elementIdentifiers.push(l);s.updatedAt=Date.now(),await this.persist()}async listRecent(e=5){let t=await this.load(),n=Object.values(t.threads);return n.sort((s,i)=>i.updatedAt-s.updatedAt),n.slice(0,e).map(s=>{let i=s.messages.find(a=>a.role==="human"),l=(i==null?void 0:i.feedbackSummary)||"[thread]";return{id:s.id,createdAt:s.createdAt,updatedAt:s.updatedAt,preview:l,messageCount:s.messages.length,elementIdentifiers:s.elementIdentifiers}})}async getThreadHistory(e,t=6){let n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await rn(ln(this.filePath),{recursive:!0}),await cn(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};var An={};var bn=1111,kn=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Tn=1800*1e3,$n=3600*1e3;function Ct(r){if(!r)return!1;try{let e=new URL(r);return e.hostname==="localhost"||e.hostname==="127.0.0.1"}catch(e){return!1}}function Rn(r){var t,n,s,i;let e=[];for(let l of r)if(l.type==="delta"){let a=l.text;if(!a)continue;let u=e[e.length-1];u&&u.kind==="text"?u.text+=a:e.push({kind:"text",text:a})}else if(l.type==="tool_use"){let a=l.tool||"",u=(t=l.file)!=null?t:void 0,d=(n=l.content)!=null?n:void 0,v=u?(s=u.split("/").pop())!=null?s:u:void 0,y;switch(a){case"Read":y=v?`Reading ${v}`:"Reading file";break;case"Edit":y=v?`Editing ${v}`:"Editing file";break;case"Write":y=v?`Writing ${v}`:"Writing file";break;case"Bash":y=d?d.split(`
114
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":y="Searching files";break;case"Grep":y="Searching code";break;case"WebFetch":y="Fetching page";break;case"WebSearch":y="Searching web";break;default:y=a?`Using ${a}`:"tool";break}let I=(i=u!=null?u:d)!=null?i:void 0,g=e[e.length-1];g&&g.kind==="tool_group"&&g.tool===a?g.items.push({label:y,detail:I}):e.push({kind:"tool_group",tool:a,items:[{label:y,detail:I}]})}return e}function En(r,e){let t=r.headers.origin;Ct(t)&&(e.setHeader("Access-Control-Allow-Origin",t),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type"))}function b(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}function Mn(r,e){if(!r)return e;let t=r.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,s,i]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(s,16)};${parseInt(i,16)}m${e}\x1B[0m`}function qe(r,e){try{r.res.write(`event: ${e.type}
113
115
  data: ${JSON.stringify(e)}
114
116
 
115
- `)}catch(t){}}async function $n(r){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${r}/status`,{signal:e.signal});return clearTimeout(t),n.ok?await n.json():null}catch(e){return null}}function Rn(r,e){return new Promise((t,n)=>{let o=l=>{r.removeListener("listening",i),n(l)},i=()=>{r.removeListener("error",o),t()};r.once("error",o),r.once("listening",i),r.listen(e,"127.0.0.1")})}async function qe(r={}){var Ye,Ve,Ke,Ze,et,tt,nt,st,ot;let e=(Ye=r.port)!=null?Ye:xn,t=(Ve=r.projectRoot)!=null?Ve:process.cwd(),n=un("sha256").update(t).digest("hex").slice(0,12),o=(Ke=r.devOrigin)!=null?Ke:process.env.PORT?`http://localhost:${process.env.PORT}`:null,i=(Ze=r.tempDir)!=null?Ze:ie(yn(),"popmelt-bridge"),l=(et=r.maxTurns)!=null?et:40,c=(tt=r.maxBudgetUsd)!=null?tt:1,p=[...(nt=r.allowedTools)!=null?nt:In],d=(st=r.claudePath)!=null?st:"claude",S=(ot=r.provider)!=null?ot:"claude",x=r.timeoutMs,b=e,y={};for(let s of["claude","codex"])try{let a=ln("which",[s],{encoding:"utf-8"}).trim();y[s]={available:!0,path:a}}catch(a){y[s]={available:!1,path:null}}function J(s,a){return new Promise(h=>{let u=dn(a,["--version"],{stdio:["ignore","ignore","ignore"]}),w=!1,f=R=>{w||(w=!0,h(R))},E=setTimeout(()=>{u.kill("SIGTERM"),f(!0)},5e3);u.on("error",()=>{clearTimeout(E),f(!1)}),u.on("close",R=>{clearTimeout(E),f(R===0)})})}let[F,U]=await Promise.all([Le(t),je(t)]);y.claude&&(y.claude.mcp=F),y.codex&&(y.codex.mcp=U),F.found&&F.name&&p.push(`mcp__${F.name}__*`),await pn(i,{recursive:!0}),Rt(i).catch(()=>{});let P=new Oe(1),L=new Set,A=new _e(t),j=new Me(t),W=new Ee(t,j,{claudePath:d,onEvent:s=>{for(let a of L)We(a,s)}}),oe=20,D=300*1e3,z=[],g=null,N;P.addListener((s,a,h)=>{for(let u of L)(!h||!u.sourceId||u.sourceId===h)&&We(u,s)}),P.setProcessor(async s=>{var X,Z,te,ee,de,ae;let a=s._replyPrompt,h=s._replyImagePaths,u=(X=s.provider)!=null?X:S,w;if(s.threadId){let $=await A.getThread(s.threadId);if($){for(let _=$.messages.length-1;_>=0;_--)if($.messages[_].sessionId){w=$.messages[_].sessionId;break}}}let f;if(w&&a){let $=(Z=await A.getThread(s.threadId))==null?void 0:Z.messages.filter(se=>se.role==="human").pop();if(f=($==null?void 0:$.replyToQuestion)||($==null?void 0:$.feedbackSummary)||"",h&&h.length>0){f+=`
117
+ `)}catch(t){}}async function Cn(r){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${r}/status`,{signal:e.signal});return clearTimeout(t),n.ok?await n.json():null}catch(e){return null}}function On(r,e){return new Promise((t,n)=>{let s=l=>{r.removeListener("listening",i),n(l)},i=()=>{r.removeListener("error",s),t()};r.once("error",s),r.once("listening",i),r.listen(e,"127.0.0.1")})}async function Qe(r={}){var Ve,Ke,Ze,et,tt,nt,st,ot,rt;let e=(Ve=r.port)!=null?Ve:bn,t=(Ke=r.projectRoot)!=null?Ke:process.cwd(),n=fn("sha256").update(t).digest("hex").slice(0,12),s=(Ze=r.devOrigin)!=null?Ze:process.env.PORT?`http://localhost:${process.env.PORT}`:null,i=(et=r.tempDir)!=null?et:ce(Sn(),"popmelt-bridge"),l=(tt=r.maxTurns)!=null?tt:40,a=(nt=r.maxBudgetUsd)!=null?nt:1,u=[...(st=r.allowedTools)!=null?st:kn],d=(ot=r.claudePath)!=null?ot:"claude",v=(rt=r.provider)!=null?rt:"claude",y=r.timeoutMs,I=e,g={};for(let o of["claude","codex"])try{let c=pn("which",[o],{encoding:"utf-8"}).trim();g[o]={available:!0,path:c}}catch(c){g[o]={available:!1,path:null}}function _(o,c){return new Promise(f=>{let p=hn(c,["--version"],{stdio:["ignore","ignore","ignore"]}),w=!1,h=L=>{w||(w=!0,f(L))},A=setTimeout(()=>{p.kill("SIGTERM"),h(!0)},5e3);p.on("error",()=>{clearTimeout(A),h(!1)}),p.on("close",L=>{clearTimeout(A),h(L===0)})})}let[W,J]=await Promise.all([ze(t),je(t)]);g.claude&&(g.claude.mcp=W),g.codex&&(g.codex.mcp=J),W.found&&W.name&&u.push(`mcp__${W.name}__*`),await mn(i,{recursive:!0}),Mt(i).catch(()=>{});let k=new Ae(1),j=new Set,D=new _e(t),Z=new Me(t),U=new Ce(t,Z,{claudePath:d,onEvent:o=>{for(let c of j)qe(c,o)}}),ie=20,F=300*1e3,H=[],E=null,P;k.addListener((o,c,f)=>{for(let p of j)(!f||!p.sourceId||p.sourceId===f)&&qe(p,o)}),k.setProcessor(async o=>{var Y,ee,se,ne,de,le;let c=o._replyPrompt,f=o._replyImagePaths,p=(Y=o.provider)!=null?Y:v,w;if(o.threadId){let T=await D.getThread(o.threadId);if(T){for(let B=T.messages.length-1;B>=0;B--)if(T.messages[B].sessionId){w=T.messages[B].sessionId;break}}}let h;if(w&&c){let T=(ee=await D.getThread(o.threadId))==null?void 0:ee.messages.filter(re=>re.role==="human").pop();if(h=(T==null?void 0:T.replyToQuestion)||(T==null?void 0:T.feedbackSummary)||"",f&&f.length>0){h+=`
116
118
 
117
- The developer attached reference images with their reply:`;for(let se of h)f+=`
118
- Attached image: use the Read tool to view the image at: ${se}`}f+=`
119
+ The developer attached reference images with their reply:`;for(let re of f)h+=`
120
+ Attached image: use the Read tool to view the image at: ${re}`}h+=`
119
121
 
120
- 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(w)f=we(s.feedback,s.imagePaths)+`
122
+ 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(w)h=Se(o.feedback,o.imagePaths)+`
121
123
 
122
124
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
123
125
 
124
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(u!=="codex"?`
126
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(p!=="codex"?`
125
127
 
126
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${s.screenshotPath}`:"");else{let $=!a&&s.threadId?await A.getThreadHistory(s.threadId):void 0,_=a?null:await W.loadModel();f=a!=null?a:It(s.screenshotPath,s.feedback,{threadHistory:$&&$.length>0?$:void 0,provider:u,imagePaths:s.imagePaths,designModel:_!=null?_:void 0,screenshotPaths:s.screenshotPaths})}let E=kn(s.color,`[\u22B9 ${b}:${s.id}]`),R=s.screenshotPaths&&Object.keys(s.screenshotPaths).length>0?`${Object.keys(s.screenshotPaths).length} pages [${Object.keys(s.screenshotPaths).join(", ")}]`:s.screenshotPath;console.log(`${E} Reviewing ${R} (provider: ${u})${s.threadId?` (thread: ${s.threadId})`:""}${w?` (resuming: ${w.slice(0,8)})`:""}`);let q=($,_)=>{$.type==="delta"&&"text"in $?P.accumulateText(_,"response",$.text):$.type==="thinking"&&"text"in $&&P.accumulateText(_,"thinking",$.text),P.broadcast($,_,s.sourceId)},{process:M,result:K}=u==="codex"?ct(s.id,{prompt:f,projectRoot:t,screenshotPath:s.screenshotPath,resumeSessionId:w,model:s.model,onEvent:q}):Re(s.id,{prompt:f,projectRoot:t,maxTurns:l,maxBudgetUsd:c,allowedTools:p,claudePath:d,resumeSessionId:w,model:s.model,timeoutMs:x,onEvent:q});P.setActiveProcess(s.id,M);let v=await K;if(s.result=v.text,v.success){console.log(`${E} Iteration complete`),v.fileEdits&&v.fileEdits.length>0&&console.log(`${E} Captured ${v.fileEdits.length} file edit(s): ${v.fileEdits.map(Y=>`${Y.tool} ${Y.file_path}`).join(", ")}`),s.status="done";let $=Pt(v.text),_=bt(v.text);if(_.length>0&&s.annotationIds&&s.annotationIds.length>0){let Y=new Set(s.annotationIds);_.every(I=>Y.has(I.annotationId))||(_=_.map((I,B)=>V(C({},I),{annotationId:s.annotationIds[B%s.annotationIds.length]})))}let se=v.fileEdits&&v.fileEdits.length>0?v.fileEdits.map(Y=>`${Y.tool} ${Y.file_path.split("/").pop()}`):void 0;s.threadId&&await A.appendMessage(s.threadId,{role:"assistant",timestamp:Date.now(),jobId:s.id,responseText:v.text,resolutions:_.length>0?_:void 0,question:$!=null?$:void 0,sessionId:v.sessionId,toolsUsed:se,model:s.model,provider:s.provider}),j.captureGitDiff(t).then(async Y=>{var ce;let m=Date.now(),I=s.imagePaths?Object.values(s.imagePaths).flat():[],B=[];if(s.imagePaths)for(let[_t,At]of Object.entries(s.imagePaths))for(let Ne=0;Ne<At.length;Ne++)B.push(`screenshots/p-${s.id}-${_t}-${Ne}.png`);await j.persist({version:1,id:s.id,createdAt:s.createdAt,completedAt:m,durationMs:m-s.createdAt,url:s.feedback.url,viewport:s.feedback.viewport,screenshotPath:`screenshots/s-${s.id}.png`,pastedImagePaths:B,annotations:s.feedback.annotations,styleModifications:s.feedback.styleModifications,inspectedElement:s.feedback.inspectedElement,provider:s.provider,model:s.model,sessionId:v.sessionId,threadId:s.threadId,responseText:v.text,resolutions:_.length>0?_:[],question:$!=null?$:void 0,fileEdits:(ce=v.fileEdits)!=null?ce:[],toolsUsed:se,gitDiff:Y},s.screenshotPath,I)}).catch(()=>{}),_.length>0&&_.some(m=>{var B;let I=(B=m.finalScope)!=null?B:m.inferredScope;return(I==null?void 0:I.breadth)==="pattern"})&&W.run().catch(()=>{}),$&&(console.log(`${E} \u{1F4AC} Question detected: "${$.slice(0,120)}" \u2192 broadcasting to ${L.size} SSE clients (threadId=${(te=s.threadId)!=null?te:s.id}, annotationIds=${(de=(ee=s.annotationIds)==null?void 0:ee.join(","))!=null?de:"none"})`),P.broadcast({type:"question",jobId:s.id,threadId:(ae=s.threadId)!=null?ae:s.id,question:$,annotationIds:s.annotationIds},s.id,s.sourceId));let fe=kt(v.text);fe.length>0&&(console.log(`${E} Novel pattern(s): ${fe.map(Y=>`${Y.category}/${Y.element}`).join(", ")}`),P.broadcast({type:"novel_patterns",jobId:s.id,patterns:fe,threadId:s.threadId},s.id,s.sourceId)),P.broadcast({type:"done",jobId:s.id,success:!0,resolutions:_.length>0?_:void 0,responseText:v.text,threadId:s.threadId},s.id,s.sourceId),z.push({id:s.id,status:"done",completedAt:Date.now(),threadId:s.threadId,annotationIds:s.annotationIds})}else console.error(`${E} Error: ${v.error}`),s.status="error",s.error=v.error,s.threadId&&await A.appendMessage(s.threadId,{role:"assistant",timestamp:Date.now(),jobId:s.id,error:v.error||"Unknown error",model:s.model,provider:s.provider}),P.broadcast({type:"error",jobId:s.id,threadId:s.threadId,message:v.error||"Unknown error"},s.id,s.sourceId),z.push({id:s.id,status:"error",completedAt:Date.now(),error:v.error,threadId:s.threadId,annotationIds:s.annotationIds});let G=Date.now()-D;for(;z.length>0&&(z[0].completedAt<G||z.length>oe);)z.shift()});let k=gn(async(s,a)=>{var E;if(bn(s,a),s.method==="OPTIONS"){a.writeHead(204),a.end();return}let h=s.url||"/",u=h.split("?")[0],w=new URL(h,`http://127.0.0.1:${b}`),f=w.pathname;try{if(s.method==="POST"&&f==="/send")await H(s,a);else if(s.method==="GET"&&f==="/events")he(s,a);else if(s.method==="GET"&&f==="/status")ve(a);else if(s.method==="GET"&&f==="/capabilities")T(a,200,{providers:y});else if(s.method==="POST"&&f==="/mcp/install")await Ie(s,a);else if(s.method==="POST"&&f==="/reply")await ne(s,a);else if(s.method==="POST"&&f==="/cancel")Se(s,a);else if(s.method==="POST"&&f==="/materialize")await xe(a);else if(s.method==="POST"&&f==="/model/component")await Pe(s,a);else if(s.method==="DELETE"&&f==="/model/component")await Te(s,a);else if(s.method==="PATCH"&&f==="/model/token")await Q(s,a);else if(s.method==="DELETE"&&f==="/model/token")await De(s,a);else if(s.method==="GET"&&f==="/model"){let R=await W.loadModel();T(a,200,{model:R})}else if(s.method==="GET"&&f.startsWith("/jobs/")&&f.endsWith("/events")){let R=f.slice(6,f.length-7),q=parseInt((E=w.searchParams.get("afterSeq"))!=null?E:"-1",10),M=P.getBufferedEvents(R,isNaN(q)?-1:q);M?T(a,200,M):T(a,404,{error:"Unknown job"})}else if(s.method==="GET"&&u.startsWith("/files/"))await Et(u.slice(7),a);else if(s.method==="GET"&&f.startsWith("/thread/")){let R=f.slice(8);await Ct(R,a)}else s.method==="GET"&&(f==="/canvas"||f==="/canvas/")?O(s,a):s.method==="GET"&&f==="/canvas/manifest"?await be(a):s.method==="GET"&&f==="/canvas/app.mjs"?await ke(a):T(a,404,{error:"Not found"})}catch(R){console.error("[Bridge] Request error:",R),T(a,500,{error:R instanceof Error?R.message:"Internal error"})}});async function H(s,a){let{screenshot:h,feedback:u,color:w,provider:f,model:E,sourceId:R,pastedImages:q,pageScreenshots:M}=await He(s),K;try{K=JSON.parse(u)}catch(m){T(a,400,{error:"Invalid feedback JSON"});return}let v=Ge().slice(0,8),G={};if(M.length>0)for(let m of M){let I=encodeURIComponent(m.pathname),B=ie(i,`screenshot-${v}-${I}.png`);await Ae(B,m.data),G[m.pathname]=B}let X=ie(i,`screenshot-${v}.png`);await Ae(X,h);let Z={};if(q.length>0)for(let m of q){let I=ie(i,`pasted-${v}-${m.annotationId}-${m.index}.png`);await Ae(I,m.data),Z[m.annotationId]||(Z[m.annotationId]=[]),Z[m.annotationId].push(I)}let te=K.annotations.map(m=>m.linkedSelector?m.pathname?`${m.pathname}:${m.linkedSelector}`:m.linkedSelector:null).filter(m=>!!m),ee;if(te.length>0){let m=await A.findContinuationThread(te);m?(ee=m.id,await A.addElementIdentifiers(ee,te)):ee=(await A.createThread(v,te)).id}else ee=(await A.createThread(v,[])).id;let de=K.annotations.map(m=>m.id),ae=Object.keys(G).length>0,$=C(V(C({id:v,status:"queued",screenshotPath:X,feedback:K,createdAt:Date.now(),color:w,threadId:ee,annotationIds:de,provider:f==="claude"||f==="codex"?f:void 0,model:E||void 0},Object.keys(Z).length>0?{imagePaths:Z}:{}),{sourceId:R||void 0}),ae?{screenshotPaths:G}:{}),_=new Set(K.annotations.map(m=>m.pathname).filter(Boolean)),se;if(_.size>1){let m=new Map;for(let I of K.annotations){let B=I.pathname||"(unknown)";m.has(B)||m.set(B,[]),m.get(B).push(I.instruction||`[${I.type}]`)}se=[...m.entries()].map(([I,B])=>`\`${I}\`
127
- ${B.map(ce=>`- ${ce}`).join(`
128
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${o.screenshotPath}`:"");else{let T=!c&&o.threadId?await D.getThreadHistory(o.threadId):void 0,B=c?null:await U.loadModel();h=c!=null?c:bt(o.screenshotPath,o.feedback,{threadHistory:T&&T.length>0?T:void 0,provider:p,imagePaths:o.imagePaths,designModel:B!=null?B:void 0,screenshotPaths:o.screenshotPaths})}let A=Mn(o.color,`[\u22B9 ${I}:${o.id}]`),L=o.screenshotPaths&&Object.keys(o.screenshotPaths).length>0?`${Object.keys(o.screenshotPaths).length} pages [${Object.keys(o.screenshotPaths).join(", ")}]`:o.screenshotPath;console.log(`${A} Reviewing ${L} (provider: ${p})${o.threadId?` (thread: ${o.threadId})`:""}${w?` (resuming: ${w.slice(0,8)})`:""}`);let z=(T,B)=>{T.type==="delta"&&"text"in T?k.accumulateText(B,"response",T.text):T.type==="thinking"&&"text"in T&&k.accumulateText(B,"thinking",T.text),k.broadcast(T,B,o.sourceId)},{process:$,result:X}=p==="codex"?dt(o.id,{prompt:h,projectRoot:t,screenshotPath:o.screenshotPath,resumeSessionId:w,model:o.model,onEvent:z}):Ee(o.id,{prompt:h,projectRoot:t,maxTurns:l,maxBudgetUsd:a,allowedTools:u,claudePath:d,resumeSessionId:w,model:o.model,timeoutMs:y,onEvent:z});k.setActiveProcess(o.id,$);let S=await X;if(o.result=S.text,S.success){console.log(`${A} Iteration complete`),S.fileEdits&&S.fileEdits.length>0&&console.log(`${A} Captured ${S.fileEdits.length} file edit(s): ${S.fileEdits.map(x=>`${x.tool} ${x.file_path}`).join(", ")}`),o.status="done";let T=kt(S.text),B=$t(S.text);if(B.length>0&&o.annotationIds&&o.annotationIds.length>0){let x=new Set(o.annotationIds);B.every(V=>x.has(V.annotationId))||(B=B.map((V,ue)=>K(C({},V),{annotationId:o.annotationIds[ue%o.annotationIds.length]})))}let re=S.fileEdits&&S.fileEdits.length>0?S.fileEdits.map(x=>`${x.tool} ${x.file_path.split("/").pop()}`):S.toolsUsed,we=k.getBufferedEvents(o.id),me=we?Rn(we.events):void 0;o.threadId&&await D.appendMessage(o.threadId,{role:"assistant",timestamp:Date.now(),jobId:o.id,responseText:S.text,resolutions:B.length>0?B:void 0,question:T!=null?T:void 0,sessionId:S.sessionId,toolsUsed:re,segments:me&&me.length>0?me:void 0,model:o.model,provider:o.provider}),Z.captureGitDiff(t).then(async x=>{var it;let G=Date.now(),V=o.imagePaths?Object.values(o.imagePaths).flat():[],ue=[];if(o.imagePaths)for(let[Dt,Nt]of Object.entries(o.imagePaths))for(let Be=0;Be<Nt.length;Be++)ue.push(`screenshots/p-${o.id}-${Dt}-${Be}.png`);await Z.persist({version:1,id:o.id,createdAt:o.createdAt,completedAt:G,durationMs:G-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:S.sessionId,threadId:o.threadId,responseText:S.text,resolutions:B.length>0?B:[],question:T!=null?T:void 0,fileEdits:(it=S.fileEdits)!=null?it:[],toolsUsed:re,gitDiff:x},o.screenshotPath,V)}).catch(()=>{}),B.length>0&&B.some(G=>{var ue;let V=(ue=G.finalScope)!=null?ue:G.inferredScope;return(V==null?void 0:V.breadth)==="pattern"})&&U.run().catch(()=>{}),T&&(console.log(`${A} \u{1F4AC} Question detected: "${T.slice(0,120)}" \u2192 broadcasting to ${j.size} SSE clients (threadId=${(se=o.threadId)!=null?se:o.id}, annotationIds=${(de=(ne=o.annotationIds)==null?void 0:ne.join(","))!=null?de:"none"})`),k.broadcast({type:"question",jobId:o.id,threadId:(le=o.threadId)!=null?le:o.id,question:T,annotationIds:o.annotationIds},o.id,o.sourceId));let m=Rt(S.text);m.length>0&&(console.log(`${A} Novel pattern(s): ${m.map(x=>`${x.category}/${x.element}`).join(", ")}`),k.broadcast({type:"novel_patterns",jobId:o.id,patterns:m,threadId:o.threadId},o.id,o.sourceId)),k.broadcast({type:"done",jobId:o.id,success:!0,resolutions:B.length>0?B:void 0,responseText:S.text,threadId:o.threadId},o.id,o.sourceId),H.push({id:o.id,status:"done",completedAt:Date.now(),threadId:o.threadId,annotationIds:o.annotationIds})}else console.error(`${A} Error: ${S.error}`),o.status="error",o.error=S.error,o.threadId&&await D.appendMessage(o.threadId,{role:"assistant",timestamp:Date.now(),jobId:o.id,error:S.error||"Unknown error",model:o.model,provider:o.provider}),k.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:S.error||"Unknown error"},o.id,o.sourceId),H.push({id:o.id,status:"error",completedAt:Date.now(),error:S.error,threadId:o.threadId,annotationIds:o.annotationIds});let q=Date.now()-F;for(;H.length>0&&(H[0].completedAt<q||H.length>ie);)H.shift()});let R=vn(async(o,c)=>{var A,L;if(En(o,c),o.method==="OPTIONS"){c.writeHead(204),c.end();return}let f=o.url||"/",p=f.split("?")[0],w=new URL(f,`http://127.0.0.1:${I}`),h=w.pathname;try{if(o.method==="POST"&&h==="/send")await M(o,c);else if(o.method==="GET"&&h==="/events")te(o,c);else if(o.method==="GET"&&h==="/status")fe(c);else if(o.method==="GET"&&h==="/capabilities")b(c,200,{providers:g});else if(o.method==="POST"&&h==="/mcp/install")await Ie(o,c);else if(o.method==="POST"&&h==="/reply")await O(o,c);else if(o.method==="POST"&&h==="/cancel")xe(o,c);else if(o.method==="POST"&&h==="/materialize")await Pe(c);else if(o.method==="POST"&&h==="/model/component")await be(o,c);else if(o.method==="DELETE"&&h==="/model/component")await ke(o,c);else if(o.method==="PATCH"&&h==="/model/token")await Q(o,c);else if(o.method==="DELETE"&&h==="/model/token")await Ne(o,c);else if(o.method==="GET"&&h==="/model"){let z=await U.loadModel();b(c,200,{model:z})}else if(o.method==="GET"&&h.startsWith("/jobs/")&&h.endsWith("/events")){let z=h.slice(6,h.length-7),$=parseInt((A=w.searchParams.get("afterSeq"))!=null?A:"-1",10),X=k.getBufferedEvents(z,isNaN($)?-1:$);X?b(c,200,X):b(c,404,{error:"Unknown job"})}else if(o.method==="GET"&&p.startsWith("/files/"))await Ot(p.slice(7),c);else if(o.method==="GET"&&h==="/threads/recent"){let z=Math.min(Math.max(parseInt((L=w.searchParams.get("limit"))!=null?L:"5",10)||5,1),20),$=await D.listRecent(z);b(c,200,$)}else if(o.method==="GET"&&h.startsWith("/thread/")){let z=h.slice(8);await At(z,c)}else o.method==="GET"&&(h==="/canvas"||h==="/canvas/")?N(o,c):o.method==="GET"&&h==="/canvas/manifest"?await Te(c):o.method==="GET"&&h==="/canvas/app.mjs"?await $e(c):b(c,404,{error:"Not found"})}catch(z){console.error("[Bridge] Request error:",z),b(c,500,{error:z instanceof Error?z.message:"Internal error"})}});async function M(o,c){let{screenshot:f,feedback:p,color:w,provider:h,model:A,sourceId:L,pastedImages:z,pageScreenshots:$}=await We(o),X;try{X=JSON.parse(p)}catch(m){b(c,400,{error:"Invalid feedback JSON"});return}let S=He().slice(0,8),q={};if($.length>0)for(let m of $){let x=encodeURIComponent(m.pathname),G=ce(i,`screenshot-${S}-${x}.png`);await De(G,m.data),q[m.pathname]=G}let Y=ce(i,`screenshot-${S}.png`);await De(Y,f);let ee={};if(z.length>0)for(let m of z){let x=ce(i,`pasted-${S}-${m.annotationId}-${m.index}.png`);await De(x,m.data),ee[m.annotationId]||(ee[m.annotationId]=[]),ee[m.annotationId].push(x)}let se=X.annotations.map(m=>m.linkedSelector?m.pathname?`${m.pathname}:${m.linkedSelector}`:m.linkedSelector:null).filter(m=>!!m),ne;if(se.length>0){let m=await D.findContinuationThread(se);m?(ne=m.id,await D.addElementIdentifiers(ne,se)):ne=(await D.createThread(S,se)).id}else ne=(await D.createThread(S,[])).id;let de=X.annotations.map(m=>m.id),le=Object.keys(q).length>0,T=C(K(C({id:S,status:"queued",screenshotPath:Y,feedback:X,createdAt:Date.now(),color:w,threadId:ne,annotationIds:de,provider:h==="claude"||h==="codex"?h:void 0,model:A||void 0},Object.keys(ee).length>0?{imagePaths:ee}:{}),{sourceId:L||void 0}),le?{screenshotPaths:q}:{}),B=new Set(X.annotations.map(m=>m.pathname).filter(Boolean)),re;if(B.size>1){let m=new Map;for(let x of X.annotations){let G=x.pathname||"(unknown)";m.has(G)||m.set(G,[]),m.get(G).push(x.instruction||`[${x.type}]`)}re=[...m.entries()].map(([x,G])=>`\`${x}\`
129
+ ${G.map(V=>`- ${V}`).join(`
128
130
  `)}`).join(`
129
- `)}else se=K.annotations.map(m=>m.instruction||`[${m.type}]`).join("; ");let fe=we(K,Object.keys(Z).length>0?Z:void 0);await A.appendMessage(ee,V(C(C({role:"human",timestamp:Date.now(),jobId:v,screenshotPath:X},ae?{screenshotPaths:G}:{}),Object.keys(Z).length>0?{imagePaths:Z}:{}),{annotationIds:de,feedbackSummary:se,feedbackContext:fe||void 0}));let Y=P.enqueue($);T(a,200,{jobId:v,position:Y,threadId:ee})}async function ne(s,a){let h=s.headers["content-type"]||"",u,w,f,E,R,q,M=[];if(h.includes("multipart/form-data")){let m=await He(s),I=m.feedback?JSON.parse(m.feedback):{};u=I.threadId,w=I.reply,f=I.color,E=I.provider,R=I.model,q=I.sourceId||m.sourceId;for(let B of m.pastedImages)M.push(B.data)}else{let m=[];try{for(var _=ue(s),se,fe,Y;se=!(fe=await _.next()).done;se=!1){let ce=fe.value;m.push(typeof ce=="string"?Buffer.from(ce):ce)}}catch(fe){Y=[fe]}finally{try{se&&(fe=_.return)&&await fe.call(_)}finally{if(Y)throw Y[0]}}let I=Buffer.concat(m).toString("utf-8"),B;try{B=JSON.parse(I)}catch(ce){T(a,400,{error:"Invalid JSON"});return}u=B.threadId,w=B.reply,f=B.color,E=B.provider,R=B.model,q=B.sourceId}if(!u||!w){T(a,400,{error:"Missing threadId or reply"});return}if(!await A.getThread(u)){T(a,404,{error:"Thread not found"});return}let v=Ge().slice(0,8),G=[];for(let m=0;m<M.length;m++){let I=ie(i,`reply-${v}-${m}.png`);await Ae(I,M[m]),G.push(I)}let X="";{let m=await A.getThreadHistory(u);for(let I=m.length-1;I>=0;I--)if(m[I].screenshotPath){X=m[I].screenshotPath;break}}if(!X){T(a,400,{error:"No screenshot available"});return}await A.appendMessage(u,C({role:"human",timestamp:Date.now(),jobId:v,replyToQuestion:w,screenshotPath:X},G.length>0?{replyImagePaths:G}:{}));let Z=await A.getThreadHistory(u),te=[];for(let m of Z)if(m.annotationIds)for(let I of m.annotationIds)te.includes(I)||te.push(I);let ee=E==="claude"||E==="codex"?E:void 0,de=Tt(X,Z,ee,G.length>0?G:void 0),ae={id:v,status:"queued",screenshotPath:X,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:f,threadId:u,annotationIds:te.length>0?te:void 0,provider:ee,model:R||void 0,sourceId:q||void 0};ae._replyPrompt=de,G.length>0&&(ae._replyImagePaths=G);let $=P.enqueue(ae);T(a,200,{jobId:v,position:$,threadId:u})}function he(s,a){a.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),a.write(`event: connected
131
+ `)}else re=X.annotations.map(m=>m.instruction||`[${m.type}]`).join("; ");let we=Se(X,Object.keys(ee).length>0?ee:void 0);await D.appendMessage(ne,K(C(C({role:"human",timestamp:Date.now(),jobId:S,screenshotPath:Y},le?{screenshotPaths:q}:{}),Object.keys(ee).length>0?{imagePaths:ee}:{}),{annotationIds:de,feedbackSummary:re,feedbackContext:we||void 0}));let me=k.enqueue(T);b(c,200,{jobId:S,position:me,threadId:ne})}async function O(o,c){let f=o.headers["content-type"]||"",p,w,h,A,L,z,$=[];if(f.includes("multipart/form-data")){let m=await We(o),x=m.feedback?JSON.parse(m.feedback):{};p=x.threadId,w=x.reply,h=x.color,A=x.provider,L=x.model,z=x.sourceId||m.sourceId;for(let G of m.pastedImages)$.push(G.data)}else{let m=[];try{for(var B=pe(o),re,we,me;re=!(we=await B.next()).done;re=!1){let V=we.value;m.push(typeof V=="string"?Buffer.from(V):V)}}catch(we){me=[we]}finally{try{re&&(we=B.return)&&await we.call(B)}finally{if(me)throw me[0]}}let x=Buffer.concat(m).toString("utf-8"),G;try{G=JSON.parse(x)}catch(V){b(c,400,{error:"Invalid JSON"});return}p=G.threadId,w=G.reply,h=G.color,A=G.provider,L=G.model,z=G.sourceId}if(!p||!w){b(c,400,{error:"Missing threadId or reply"});return}if(!await D.getThread(p)){b(c,404,{error:"Thread not found"});return}let S=He().slice(0,8),q=[];for(let m=0;m<$.length;m++){let x=ce(i,`reply-${S}-${m}.png`);await De(x,$[m]),q.push(x)}let Y="";{let m=await D.getThreadHistory(p);for(let x=m.length-1;x>=0;x--)if(m[x].screenshotPath){Y=m[x].screenshotPath;break}}if(!Y){b(c,400,{error:"No screenshot available"});return}await D.appendMessage(p,C({role:"human",timestamp:Date.now(),jobId:S,replyToQuestion:w,screenshotPath:Y},q.length>0?{replyImagePaths:q}:{}));let ee=await D.getThreadHistory(p),se=[];for(let m of ee)if(m.annotationIds)for(let x of m.annotationIds)se.includes(x)||se.push(x);let ne=A==="claude"||A==="codex"?A:void 0,de=Tt(Y,ee,ne,q.length>0?q:void 0),le={id:S,status:"queued",screenshotPath:Y,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:h,threadId:p,annotationIds:se.length>0?se:void 0,provider:ne,model:L||void 0,sourceId:z||void 0};le._replyPrompt=de,q.length>0&&(le._replyImagePaths=q);let T=k.enqueue(le);b(c,200,{jobId:S,position:T,threadId:p})}function te(o,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
130
132
  data: {"status":"connected"}
131
133
 
132
- `),!o&&s.headers.origin&&Mt(s.headers.origin)&&(o=s.headers.origin);let u=new URL(s.url||"/",`http://127.0.0.1:${b}`).searchParams.get("sourceId")||void 0,w={id:Ge().slice(0,8),res:a,sourceId:u};L.add(w),s.on("close",()=>{L.delete(w)})}function ve(s){let a=P.allActive;T(s,200,{ok:!0,projectId:n,devOrigin:o,activeJob:a[0]?{id:a[0].id,status:a[0].status}:null,activeJobs:a.map(h=>({id:h.id,status:h.status,threadId:h.threadId,annotationIds:h.annotationIds,color:h.color})),queueDepth:P.depth,recentJobs:z})}async function Se(s,a){let u=new URL(s.url||"/",`http://127.0.0.1:${b}`).searchParams.get("jobId"),f=(u?P.allActive.filter(R=>R.id===u):P.allActive).map(R=>R.threadId).filter(Boolean),E=u?P.cancelJob(u):P.cancelActive();for(let R of f)await A.appendMessage(R,{role:"assistant",timestamp:Date.now(),jobId:u||"",cancelled:!0});T(a,200,{cancelled:E})}async function xe(s){if(W.isRunning){T(s,200,{skipped:!0,reason:"Already running"});return}let a=await W.getUnmaterializedPatternDecisions();if(a.length===0){T(s,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}W.run().catch(()=>{}),T(s,200,{started:!0,decisionCount:a.length,decisionIds:a.map(h=>h.id)})}async function Ie(s,a){var v,G;let h=[];try{for(var R=ue(s),q,M,K;q=!(M=await R.next()).done;q=!1){let X=M.value;h.push(typeof X=="string"?Buffer.from(X):X)}}catch(M){K=[M]}finally{try{q&&(M=R.return)&&await M.call(R)}finally{if(K)throw K[0]}}let u;if(h.length>0)try{u=JSON.parse(Buffer.concat(h).toString("utf-8")).serverUrl}catch(X){}let w=[];(v=y.claude)!=null&&v.available&&y.claude.mcp&&!y.claude.mcp.found&&w.push(await St(u)),(G=y.codex)!=null&&G.available&&y.codex.mcp&&!y.codex.mcp.found&&w.push(await xt(u));let[f,E]=await Promise.all([Le(t),je(t)]);y.claude&&(y.claude.mcp=f),y.codex&&(y.codex.mcp=E),T(a,200,{results:w,capabilities:{providers:y}})}async function Pe(s,a){let h=[];try{for(var f=ue(s),E,R,q;E=!(R=await f.next()).done;E=!1){let M=R.value;h.push(typeof M=="string"?Buffer.from(M):M)}}catch(R){q=[R]}finally{try{E&&(R=f.return)&&await R.call(f)}finally{if(q)throw q[0]}}let u;try{u=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch(M){T(a,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){T(a,400,{error:"Missing or invalid name"});return}let w=await W.addComponent(u.name);T(a,200,w)}async function Te(s,a){let h=[];try{for(var f=ue(s),E,R,q;E=!(R=await f.next()).done;E=!1){let M=R.value;h.push(typeof M=="string"?Buffer.from(M):M)}}catch(R){q=[R]}finally{try{E&&(R=f.return)&&await R.call(f)}finally{if(q)throw q[0]}}let u;try{u=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch(M){T(a,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){T(a,400,{error:"Missing or invalid name"});return}let w=await W.removeComponent(u.name);T(a,200,w)}async function Q(s,a){let h=[];try{for(var f=ue(s),E,R,q;E=!(R=await f.next()).done;E=!1){let M=R.value;h.push(typeof M=="string"?Buffer.from(M):M)}}catch(R){q=[R]}finally{try{E&&(R=f.return)&&await R.call(f)}finally{if(q)throw q[0]}}let u;try{u=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch(M){T(a,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"||typeof u.value!="string"){T(a,400,{error:"Missing or invalid path/value"});return}let w=await W.updateToken(u.path,u.value);T(a,200,w)}async function De(s,a){let h=[];try{for(var f=ue(s),E,R,q;E=!(R=await f.next()).done;E=!1){let M=R.value;h.push(typeof M=="string"?Buffer.from(M):M)}}catch(R){q=[R]}finally{try{E&&(R=f.return)&&await R.call(f)}finally{if(q)throw q[0]}}let u;try{u=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch(M){T(a,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"){T(a,400,{error:"Missing or invalid path"});return}let w=await W.removeToken(u.path);T(a,200,w)}function O(s,a){let h=o!=null?o:"http://localhost:3000";if(!o){let w=s.headers.referer||s.headers.origin;if(w)try{let f=new URL(typeof w=="string"?w:w[0]||"");(f.hostname==="localhost"||f.hostname==="127.0.0.1")&&(h=f.origin)}catch(f){}}let u=it(b,h);a.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),a.end(u)}async function be(s){let a=Date.now();if(g&&a<g.expires){T(s,200,g.data);return}try{let{scanForComponents:h}=await import("./react-scanner-MSMGKCIV.mjs"),{generateRenderFiles:u}=await import("./render-generator-QV5BYGPF.mjs"),w=await h(t);g={data:w,expires:a+5e3},u(w,t,N).then(f=>{N=f}).catch(f=>console.warn("[Bridge] Render generation failed:",f)),T(s,200,w)}catch(h){console.error("[Bridge] Scanner error:",h),T(s,500,{error:"Failed to scan components"})}}async function ke(s){let a=[ie(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ie(t,"packages","popmelt","dist","canvas.mjs")];try{let h=Sn(Mn.url);a.unshift(ie(vn(h),"canvas.mjs"))}catch(h){}for(let h of a)try{let u=await $t(h,"utf-8");s.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),s.end(u);return}catch(u){}console.error("[Bridge] Canvas bundle not found in:",a),T(s,404,{error:"Canvas bundle not found"})}async function Et(s,a){var h;if(!s||s.includes("/")||s.includes("\\")||s.includes("..")){T(a,400,{error:"Invalid filename"});return}try{let u=await $t(ie(i,s)),w=(h=s.split(".").pop())==null?void 0:h.toLowerCase(),f=w==="png"?"image/png":w==="jpg"||w==="jpeg"?"image/jpeg":"application/octet-stream";a.writeHead(200,{"Content-Type":f,"Cache-Control":"public, max-age=3600"}),a.end(u)}catch(u){T(a,404,{error:"File not found"})}}function $e(s){return`/files/${wn(s)}`}async function Ct(s,a){let h=await A.getThread(s);if(!h){T(a,404,{error:"Thread not found"});return}let u=h.messages.map(M=>{var K=M,{screenshotPath:w,screenshotPaths:f,imagePaths:E,replyImagePaths:R}=K,q=rt(K,["screenshotPath","screenshotPaths","imagePaths","replyImagePaths"]);return C(C(C(C(C({},q),w?{screenshotUrl:$e(w)}:{}),f?{screenshotUrls:Object.fromEntries(Object.entries(f).map(([v,G])=>[v,$e(G)]))}:{}),E?{imageUrls:Object.fromEntries(Object.entries(E).map(([v,G])=>[v,G.map($e)]))}:{}),R?{replyImageUrls:R.map($e)}:{})});T(a,200,{id:h.id,createdAt:h.createdAt,messages:u})}let Qe=9,Xe=!1;for(let s=e;s<e+Qe;s++)try{await Rn(k,s),b=s,Xe=!0,console.log(`[\u22B9 is watching :${b}]`);break}catch(a){if(a.code==="EADDRINUSE"){let h=await $n(s);if(h&&h.projectId===n)return console.log(`[\u22B9 already watching :${s}]`),{port:s,projectId:n,close:async()=>{}};continue}throw a}if(!Xe)throw new Error(`[Bridge] All ports ${e}\u2013${e+Qe-1} in use`);for(let[s,a]of Object.entries(y))!a.available||!a.path||J(s,a.path).then(h=>{if(h)console.log(`[Bridge] ${s} warmed up`);else{console.warn(`[Bridge] ${s} warm-up failed \u2014 marking unavailable`),a.available=!1,a.path=null;for(let u of L)We(u,{type:"capabilities_changed",data:{}})}});let Ot=setInterval(()=>{Rt(i).catch(()=>{})},Pn);return{port:b,projectId:n,close:async()=>{clearInterval(Ot),await P.destroyAsync();for(let s of L)try{s.res.end()}catch(a){}return L.clear(),new Promise(s=>{k.close(()=>s())})}}}async function Rt(r){try{let e=await hn(r),t=Date.now();for(let n of e){let o=ie(r,n);try{let i=await fn(o);t-i.mtimeMs>Tn&&await mn(o)}catch(i){}}}catch(e){}}var le="\x1B[35m[popmelt]\x1B[0m";async function Cn(){let r=process.argv.slice(2);if(r[0]==="wrap"){let e=r.indexOf("--");(e===-1||e===r.length-1)&&(console.error(`${le} Usage: popmelt wrap -- <dev command>`),console.error(`${le} Example: popmelt wrap -- next dev`),console.error(`${le} Example: popmelt wrap -- astro dev`),process.exit(1));let t=r.slice(e+1);await _n(t);return}if(r[0]==="bridge"){await On();return}console.log(`${le} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}async function On(){let r=await qe({projectRoot:process.cwd()});console.log(`${le} Bridge running on http://localhost:${r.port}`),await new Promise(e=>{let t=async()=>{console.log(`
133
- ${le} Shutting down bridge...`),await r.close(),e()};process.on("SIGINT",t),process.on("SIGTERM",t)})}async function _n(r){let e=await qe({projectRoot:process.cwd()});console.log(`${le} Bridge running on http://localhost:${e.port}`);let[t,...n]=r;console.log(`${le} Starting: ${r.join(" ")}`);let o=En(t,n,{stdio:"inherit",shell:!0,env:V(C({},process.env),{POPMELT_BRIDGE_URL:`http://localhost:${e.port}`})}),i=l=>{o.kill(l)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),o.on("exit",async(l,c)=>{await e.close(),c?process.kill(process.pid,c):process.exit(l!=null?l:0)})}Cn().catch(r=>{console.error(`${le} Fatal:`,r),process.exit(1)});
134
+ `),!s&&o.headers.origin&&Ct(o.headers.origin)&&(s=o.headers.origin);let p=new URL(o.url||"/",`http://127.0.0.1:${I}`).searchParams.get("sourceId")||void 0,w={id:He().slice(0,8),res:c,sourceId:p};j.add(w),o.on("close",()=>{j.delete(w)})}function fe(o){let c=k.allActive;b(o,200,{ok:!0,projectId:n,devOrigin:s,activeJob:c[0]?{id:c[0].id,status:c[0].status}:null,activeJobs:c.map(f=>({id:f.id,status:f.status,threadId:f.threadId,annotationIds:f.annotationIds,color:f.color})),queueDepth:k.depth,recentJobs:H})}async function xe(o,c){let p=new URL(o.url||"/",`http://127.0.0.1:${I}`).searchParams.get("jobId"),h=(p?k.allActive.filter(L=>L.id===p):k.allActive).map(L=>L.threadId).filter(Boolean),A=p?k.cancelJob(p):k.cancelActive();for(let L of h)await D.appendMessage(L,{role:"assistant",timestamp:Date.now(),jobId:p||"",cancelled:!0});b(c,200,{cancelled:A})}async function Pe(o){if(U.isRunning){b(o,200,{skipped:!0,reason:"Already running"});return}let c=await U.getUnmaterializedPatternDecisions();if(c.length===0){b(o,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}U.run().catch(()=>{}),b(o,200,{started:!0,decisionCount:c.length,decisionIds:c.map(f=>f.id)})}async function Ie(o,c){var S,q;let f=[];try{for(var L=pe(o),z,$,X;z=!($=await L.next()).done;z=!1){let Y=$.value;f.push(typeof Y=="string"?Buffer.from(Y):Y)}}catch($){X=[$]}finally{try{z&&($=L.return)&&await $.call(L)}finally{if(X)throw X[0]}}let p;if(f.length>0)try{p=JSON.parse(Buffer.concat(f).toString("utf-8")).serverUrl}catch(Y){}let w=[];(S=g.claude)!=null&&S.available&&g.claude.mcp&&!g.claude.mcp.found&&w.push(await Pt(p)),(q=g.codex)!=null&&q.available&&g.codex.mcp&&!g.codex.mcp.found&&w.push(await It(p));let[h,A]=await Promise.all([ze(t),je(t)]);g.claude&&(g.claude.mcp=h),g.codex&&(g.codex.mcp=A),b(c,200,{results:w,capabilities:{providers:g}})}async function be(o,c){let f=[];try{for(var h=pe(o),A,L,z;A=!(L=await h.next()).done;A=!1){let $=L.value;f.push(typeof $=="string"?Buffer.from($):$)}}catch(L){z=[L]}finally{try{A&&(L=h.return)&&await L.call(h)}finally{if(z)throw z[0]}}let p;try{p=JSON.parse(Buffer.concat(f).toString("utf-8"))}catch($){b(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){b(c,400,{error:"Missing or invalid name"});return}let w=await U.addComponent(p.name);b(c,200,w)}async function ke(o,c){let f=[];try{for(var h=pe(o),A,L,z;A=!(L=await h.next()).done;A=!1){let $=L.value;f.push(typeof $=="string"?Buffer.from($):$)}}catch(L){z=[L]}finally{try{A&&(L=h.return)&&await L.call(h)}finally{if(z)throw z[0]}}let p;try{p=JSON.parse(Buffer.concat(f).toString("utf-8"))}catch($){b(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){b(c,400,{error:"Missing or invalid name"});return}let w=await U.removeComponent(p.name);b(c,200,w)}async function Q(o,c){let f=[];try{for(var h=pe(o),A,L,z;A=!(L=await h.next()).done;A=!1){let $=L.value;f.push(typeof $=="string"?Buffer.from($):$)}}catch(L){z=[L]}finally{try{A&&(L=h.return)&&await L.call(h)}finally{if(z)throw z[0]}}let p;try{p=JSON.parse(Buffer.concat(f).toString("utf-8"))}catch($){b(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"||typeof p.value!="string"){b(c,400,{error:"Missing or invalid path/value"});return}let w=await U.updateToken(p.path,p.value);b(c,200,w)}async function Ne(o,c){let f=[];try{for(var h=pe(o),A,L,z;A=!(L=await h.next()).done;A=!1){let $=L.value;f.push(typeof $=="string"?Buffer.from($):$)}}catch(L){z=[L]}finally{try{A&&(L=h.return)&&await L.call(h)}finally{if(z)throw z[0]}}let p;try{p=JSON.parse(Buffer.concat(f).toString("utf-8"))}catch($){b(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"){b(c,400,{error:"Missing or invalid path"});return}let w=await U.removeToken(p.path);b(c,200,w)}function N(o,c){let f=s!=null?s:"http://localhost:3000";if(!s){let w=o.headers.referer||o.headers.origin;if(w)try{let h=new URL(typeof w=="string"?w:w[0]||"");(h.hostname==="localhost"||h.hostname==="127.0.0.1")&&(f=h.origin)}catch(h){}}let p=ct(I,f);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(p)}async function Te(o){let c=Date.now();if(E&&c<E.expires){b(o,200,E.data);return}try{let{scanForComponents:f}=await import("./react-scanner-MSMGKCIV.mjs"),{generateRenderFiles:p}=await import("./render-generator-QV5BYGPF.mjs"),w=await f(t);E={data:w,expires:c+5e3},p(w,t,P).then(h=>{P=h}).catch(h=>console.warn("[Bridge] Render generation failed:",h)),b(o,200,w)}catch(f){console.error("[Bridge] Scanner error:",f),b(o,500,{error:"Failed to scan components"})}}async function $e(o){let c=[ce(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ce(t,"packages","popmelt","dist","canvas.mjs")];try{let f=In(An.url);c.unshift(ce(Pn(f),"canvas.mjs"))}catch(f){}for(let f of c)try{let p=await Et(f,"utf-8");o.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),o.end(p);return}catch(p){}console.error("[Bridge] Canvas bundle not found in:",c),b(o,404,{error:"Canvas bundle not found"})}async function Ot(o,c){var f;if(!o||o.includes("/")||o.includes("\\")||o.includes("..")){b(c,400,{error:"Invalid filename"});return}try{let p=await Et(ce(i,o)),w=(f=o.split(".").pop())==null?void 0:f.toLowerCase(),h=w==="png"?"image/png":w==="jpg"||w==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":h,"Cache-Control":"public, max-age=3600"}),c.end(p)}catch(p){b(c,404,{error:"File not found"})}}function Re(o){return`/files/${xn(o)}`}async function At(o,c){let f=await D.getThread(o);if(!f){b(c,404,{error:"Thread not found"});return}let p=f.messages.map($=>{var X=$,{screenshotPath:w,screenshotPaths:h,imagePaths:A,replyImagePaths:L}=X,z=at(X,["screenshotPath","screenshotPaths","imagePaths","replyImagePaths"]);return C(C(C(C(C({},z),w?{screenshotUrl:Re(w)}:{}),h?{screenshotUrls:Object.fromEntries(Object.entries(h).map(([S,q])=>[S,Re(q)]))}:{}),A?{imageUrls:Object.fromEntries(Object.entries(A).map(([S,q])=>[S,q.map(Re)]))}:{}),L?{replyImageUrls:L.map(Re)}:{})});b(c,200,{id:f.id,createdAt:f.createdAt,messages:p})}let Xe=9,Ye=!1;for(let o=e;o<e+Xe;o++)try{await On(R,o),I=o,Ye=!0,console.log(`[\u22B9 is watching :${I}]`);break}catch(c){if(c.code==="EADDRINUSE"){let f=await Cn(o);if(f&&f.projectId===n)return console.log(`[\u22B9 already watching :${o}]`),{port:o,projectId:n,close:async()=>{}};continue}throw c}if(!Ye)throw new Error(`[Bridge] All ports ${e}\u2013${e+Xe-1} in use`);for(let[o,c]of Object.entries(g))!c.available||!c.path||_(o,c.path).then(f=>{if(f)console.log(`[Bridge] ${o} warmed up`);else{console.warn(`[Bridge] ${o} warm-up failed \u2014 marking unavailable`),c.available=!1,c.path=null;for(let p of j)qe(p,{type:"capabilities_changed",data:{}})}});let _t=setInterval(()=>{Mt(i).catch(()=>{})},Tn);return{port:I,projectId:n,close:async()=>{clearInterval(_t),await k.destroyAsync();for(let o of j)try{o.res.end()}catch(c){}return j.clear(),new Promise(o=>{R.close(()=>o())})}}}async function Mt(r){try{let e=await gn(r),t=Date.now();for(let n of e){let s=ce(r,n);try{let i=await yn(s);t-i.mtimeMs>$n&&await wn(s)}catch(i){}}}catch(e){}}var oe="\x1B[35m[popmelt]\x1B[0m";async function Jn(){let r=process.argv.slice(2);if(r[0]==="wrap"){let e=r.indexOf("--");(e===-1||e===r.length-1)&&(console.error(`${oe} Usage: popmelt wrap -- <dev command>`),console.error(`${oe} Example: popmelt wrap -- next dev`),console.error(`${oe} Example: popmelt wrap -- astro dev`),process.exit(1));let t=r.slice(e+1);await Ln(t);return}if(r[0]==="bridge"){await Un();return}if(r[0]==="stop"){await Fn();return}console.log(`${oe} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}async function Un(){let r=await Qe({projectRoot:process.cwd()});console.log(`${oe} Bridge running on http://localhost:${r.port}`),await new Promise(e=>{let t=async()=>{console.log(`
135
+ ${oe} Shutting down bridge...`),await r.close(),e()};process.on("SIGINT",t),process.on("SIGTERM",t)})}async function Fn(){let r=Bn(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await Dn(r,"utf8"))}catch(t){console.log(`${oe} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${oe} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(t){if(t.code==="ESRCH")console.log(`${oe} Bridge process ${e.pid} already dead`);else throw t}try{await Nn(r)}catch(t){}}async function Ln(r){let e=await Qe({projectRoot:process.cwd()});console.log(`${oe} Bridge running on http://localhost:${e.port}`);let[t,...n]=r;console.log(`${oe} Starting: ${r.join(" ")}`);let s=_n(t,n,{stdio:"inherit",shell:!0,env:K(C({},process.env),{POPMELT_BRIDGE_URL:`http://localhost:${e.port}`})}),i=l=>{s.kill(l)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),s.on("exit",async(l,a)=>{await e.close(),a?process.kill(process.pid,a):process.exit(l!=null?l:0)})}Jn().catch(r=>{console.error(`${oe} Fatal:`,r),process.exit(1)});