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