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