@popmelt.com/core 0.5.22 → 0.6.1
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/README.md +51 -36
- package/dist/cli.mjs +38 -35
- package/dist/index.d.mts +6 -1
- package/dist/index.mjs +19 -21
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-RSWDAN3X.mjs +130 -0
- package/dist/server.mjs +37 -34
- package/package.json +1 -1
- package/dist/server-CNHKE6KT.mjs +0 -127
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
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: '${
|
|
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
|
-
`),
|
|
32
|
-
`),
|
|
31
|
+
`),c=o.annotations.map(d=>d.instruction).filter(Boolean).join(`
|
|
32
|
+
`),p=o.gitDiff?`
|
|
33
33
|
\`\`\`diff
|
|
34
|
-
${
|
|
35
|
-
\`\`\``:"";return`### Decision ${
|
|
36
|
-
Page: ${
|
|
34
|
+
${o.gitDiff.slice(0,2e3)}
|
|
35
|
+
\`\`\``:"";return`### Decision ${o.id} (${new Date(o.createdAt).toISOString()})
|
|
36
|
+
Page: ${o.url}
|
|
37
37
|
${l}
|
|
38
|
-
${
|
|
39
|
-
${
|
|
38
|
+
${p}
|
|
39
|
+
${c?`
|
|
40
40
|
Original instructions:
|
|
41
|
-
${
|
|
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
|
-
${
|
|
50
|
+
${e?`## Current Model
|
|
51
51
|
\`\`\`json
|
|
52
|
-
${JSON.stringify(
|
|
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
|
-
${
|
|
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
|
|
98
|
-
`),
|
|
99
|
-
`)}),n={name:
|
|
100
|
-
`)}),n=null):n&&n.bodyLines.push(
|
|
101
|
-
`)}),
|
|
102
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
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
|
|
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
|
-
`,
|
|
108
|
-
### ${
|
|
109
|
-
`)}function
|
|
110
|
-
`)}function
|
|
111
|
-
`)}function
|
|
112
|
-
data: ${JSON.stringify(
|
|
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(
|
|
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
|
|
117
|
-
Attached image: use the Read tool to view the image at: ${
|
|
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(
|
|
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.`+(
|
|
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: ${
|
|
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
|
|
129
|
-
${
|
|
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
|
};
|