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