@popmelt.com/core 0.5.17 → 0.5.19
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/LICENSE +20 -4
- package/dist/cli.mjs +14 -14
- package/dist/index.mjs +24 -16
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/{server-A5ZYTJTS.mjs → server-CNHKE6KT.mjs} +12 -12
- package/dist/server.mjs +12 -12
- package/package.json +1 -1
package/LICENSE
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# PolyForm Shield License 1.0.0 + No Redistribution Addendum
|
|
2
2
|
|
|
3
3
|
<https://polyformproject.org/licenses/shield/1.0.0>
|
|
4
4
|
|
|
5
|
+
## Additional Restriction: No Redistribution for Commercial Gain
|
|
6
|
+
|
|
7
|
+
You may not sell, resell, sublicense, or distribute the software —
|
|
8
|
+
whether modified or unmodified — as part of a paid product or
|
|
9
|
+
service, or offer it as a hosted or managed service to third parties.
|
|
10
|
+
Internal use within your organization is permitted. For commercial
|
|
11
|
+
distribution or managed-service licensing, contact the licensor.
|
|
12
|
+
|
|
5
13
|
## Acceptance
|
|
6
14
|
|
|
7
15
|
In order to get any license under these terms, you must agree to
|
|
@@ -105,9 +113,9 @@ software, under any kind of legal claim.***
|
|
|
105
113
|
|
|
106
114
|
## Definitions
|
|
107
115
|
|
|
108
|
-
The **licensor** is the entity offering these terms,
|
|
109
|
-
**software** is the software the licensor makes available
|
|
110
|
-
terms.
|
|
116
|
+
The **licensor** is the individual or entity offering these terms,
|
|
117
|
+
and the **software** is the software the licensor makes available
|
|
118
|
+
under these terms.
|
|
111
119
|
|
|
112
120
|
**You** refers to the individual or entity agreeing to these terms.
|
|
113
121
|
|
|
@@ -124,3 +132,11 @@ software under these terms.
|
|
|
124
132
|
|
|
125
133
|
**Use** means anything you do with the software requiring one of
|
|
126
134
|
your licenses.
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## Commercial Licensing
|
|
139
|
+
|
|
140
|
+
For commercial distribution or managed-service licensing, contact
|
|
141
|
+
**[hello@popmelt.com](mailto:hello@popmelt.com)** or visit
|
|
142
|
+
**[https://popmelt.com](https://popmelt.com)**.
|
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
|
|
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>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8">
|
|
@@ -26,7 +26,7 @@ import{a as Y,b as te,c as st,d as le}from"./chunk-4LDJX6BW.mjs";import{spawn as
|
|
|
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})}),j=new Promise(B=>{var L;let J,w=[],U=[],E=!1,F="",z=!1,O=setTimeout(()=>{z=!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,xe,Ie,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 R=typeof W.result=="string"?W.result:"";R&&(w.push(R),T==null||T({type:"delta",jobId:r,text:R},r))}if(W.type==="assistant"&&Array.isArray((ye=W.message)==null?void 0:ye.content))for(let R of W.message.content){if(R.type==="text"&&R.text&&(w.push(R.text),T==null||T({type:"delta",jobId:r,text:R.text},r)),R.type==="tool_use"&&R.name){let be=((we=R.input)==null?void 0:we.file_path)||((ve=R.input)==null?void 0:ve.path)||void 0;T==null||T(Y({type:"tool_use",jobId:r,tool:R.name},be?{file:be}:{}),r),R.name==="Edit"&&((Se=R.input)!=null&&Se.file_path)?U.push({tool:"Edit",file_path:R.input.file_path,old_string:R.input.old_string,new_string:R.input.new_string,replace_all:R.input.replace_all}):R.name==="Write"&&((xe=R.input)!=null&&xe.file_path)&&U.push({tool:"Write",file_path:R.input.file_path,content:R.input.content})}R.type==="thinking"&&R.thinking&&(T==null||T({type:"thinking",jobId:r,text:R.thinking},r))}W.type==="user"&&((Pe=(Ie=W.tool_use_result)==null?void 0:Ie.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=[];(L=f.stderr)==null||L.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(", ")}`),z?(E=!0,F=`Timed out after ${Math.round(A/6e4)} minutes`):S!==0&&S!==null&&(E=!0,F=g.join("")||`Claude process exited with code ${S}`),B({sessionId:J,text:w.join(""),success:!E,error:E?F:void 0,fileEdits:U.length>0?U:void 0})}),f.on("error",S=>{clearTimeout(O),E=!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:j}}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 E;let k,f=[],j=!1,B="",J=Dt({input:h.stdout}),w=new Set;J.on("line",F=>{var z,O,Z,v;if(F.trim())try{let g=JSON.parse(F),L=(z=g.type)!=null?z:"unknown";if(w.add(L),L==="thread.started"&&g.thread_id&&!k&&(k=g.thread_id),(L==="item.agentMessage.delta"||L==="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)),(L==="item.reasoning.delta"||L==="item/reasoning/delta")&&((Z=g.delta)!=null&&Z.text)&&(i==null||i({type:"thinking",jobId:r,text:g.delta.text},r)),(L==="item.started"||L==="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((L==="item.completed"||L==="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))}}L==="turn.failed"&&(j=!0,B=((v=g.error)==null?void 0:v.message)||g.message||"Turn failed")}catch(g){}});let U=[];(E=h.stderr)==null||E.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&&(j=!0,B=U.join("")||`Codex process exited with code ${F}`),T({sessionId:k,text:f.join(""),success:!j,error:j?B:void 0})}),h.on("error",F=>{j=!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 j=await this.loadIndex(),B=new Set(j.materializedIds);for(let J of h)B.add(J);return j.materializedIds=[...B],j.lastRunAt=Date.now(),j.lastRunDecisionIds=h,j.lastRunError=f!=null?f:null,await this.persistIndex(j),(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,j,B,J;let A=(f=h.finalScope)!=null?f:h.inferredScope,T=(j=A==null?void 0:A.target)!=null?j:"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 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}]
|
|
30
30
|
Files modified: ${k}`}).join(`
|
|
31
31
|
`),i=s.annotations.map(h=>h.instruction).filter(Boolean).join(`
|
|
32
32
|
`),u=s.gitDiff?`
|
|
@@ -94,27 +94,27 @@ 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
|
|
98
|
-
`),e=[],n=null;for(let s of t){let a=s.match(
|
|
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
99
|
`)}),n={name:a[1],bodyLines:[]}):s.startsWith("[")?n&&(e.push({name:n.name,body:n.bodyLines.join(`
|
|
100
100
|
`)}),n=null):n&&n.bodyLines.push(s)}return n&&e.push({name:n.name,body:n.bodyLines.join(`
|
|
101
|
-
`)}),e}function
|
|
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
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=`
|
|
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
|
|
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
|
|
106
106
|
\r
|
|
107
|
-
`,v);if(g===-1)break;let
|
|
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
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
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
|
|
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
|
|
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
112
|
data: ${JSON.stringify(t)}
|
|
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
|
|
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+=`
|
|
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 E of p)y+=`
|
|
117
|
+
Attached image: use the Read tool to view the image at: ${E}`}y+=`
|
|
118
118
|
|
|
119
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)+`
|
|
120
120
|
|
|
@@ -122,8 +122,8 @@ Follow the developer's instructions. If they ask for changes, apply them to the
|
|
|
122
122
|
|
|
123
123
|
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
|
|
124
124
|
|
|
125
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${o.screenshotPath}`:"");else{let
|
|
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
|
|
126
126
|
data: {"status":"connected"}
|
|
127
127
|
|
|
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:
|
|
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
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)});
|