@popmelt.com/core 0.5.22 → 0.6.0

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