@popmelt.com/core 0.5.8 → 0.5.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +30 -30
- package/dist/index.mjs +16 -15
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-next.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server.d.mts +2 -0
- package/dist/server.mjs +29 -29
- package/package.json +1 -1
package/dist/plugin-astro.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as c,b as g}from"./chunk-HGGX55FR.mjs";import{request as
|
|
1
|
+
import{a as c,b as g}from"./chunk-HGGX55FR.mjs";import{request as b}from"http";function y(t){var o,h;let a=(o=t==null?void 0:t.port)!=null?o:parseInt(process.env.POPMELT_BRIDGE_PORT||"1111",10),s=(h=t==null?void 0:t.basePath)!=null?h:"/popmelt",l=`http://localhost:${a}`;return{name:"popmelt-canvas",hooks:{"astro:server:setup"({server:m}){m.middlewares.use((e,r,u)=>{let p=e.url||"";if(!p.startsWith(s))return u();let P="/canvas"+p.slice(s.length),d=new URL(P,l),i=b(d,{method:e.method,headers:g(c({},e.headers),{host:d.host})},n=>{r.writeHead(n.statusCode||502,n.headers),n.pipe(r)});i.on("error",()=>{r.writeHead(502,{"Content-Type":"text/plain"}),r.end(`Popmelt bridge not running on port ${a}`)}),e.pipe(i)})}}}}export{y as popmelt};
|
package/dist/plugin-next.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty,d=Object.defineProperties;var f=Object.getOwnPropertyDescriptors;var h=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable;var u=(t,e,r)=>e in t?m(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,
|
|
1
|
+
var m=Object.defineProperty,d=Object.defineProperties;var f=Object.getOwnPropertyDescriptors;var h=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable;var u=(t,e,r)=>e in t?m(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,p=(t,e)=>{for(var r in e||(e={}))N.call(e,r)&&u(t,r,e[r]);if(h)for(var r of h(e))w.call(e,r)&&u(t,r,e[r]);return t},c=(t,e)=>d(t,f(e));import{NextResponse as i}from"next/server";var x=parseInt(process.env.POPMELT_BRIDGE_PORT||"1111",10);function P(t,e){var a,s;let r=(a=e==null?void 0:e.basePath)!=null?a:"/popmelt",l=(s=e==null?void 0:e.port)!=null?s:x;if(t.nextUrl.searchParams.get("popmelt")==="canvas"){if(process.env.NODE_ENV==="production")return null;let n=new Headers(t.headers);return n.set("x-popmelt-canvas","1"),i.next({request:{headers:n}})}if(t.nextUrl.pathname.startsWith(r+"/render")){if(process.env.NODE_ENV==="production")return null;let n=new Headers(t.headers);return n.set("x-popmelt-canvas","1"),i.next({request:{headers:n}})}if(t.nextUrl.pathname===r||t.nextUrl.pathname.startsWith(r+"/")){let n="/canvas"+t.nextUrl.pathname.slice(r.length);return i.rewrite(new URL(n||"/canvas",`http://localhost:${l}`))}return null}function g(t,e){var s;if(process.env.NODE_ENV==="production")return t;let l=`http://localhost:${(s=e==null?void 0:e.port)!=null?s:x}`,a=t.rewrites;return c(p({},t),{async rewrites(){let n=a?await a():[],o=[{source:"/popmelt",destination:`${l}/canvas`},{source:"/popmelt/:path*",destination:`${l}/canvas/:path*`}];return Array.isArray(n)?{beforeFiles:o,afterFiles:n,fallback:[]}:c(p({},n),{beforeFiles:[...n.beforeFiles||[],...o]})}})}export{P as popmeltMiddleware,g as withPopmelt};
|
package/dist/plugin-vite.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as u,b as d}from"./chunk-HGGX55FR.mjs";import{request as v}from"http";function y(e){var h,o;let a=(h=e==null?void 0:e.port)!=null?h:parseInt(process.env.POPMELT_BRIDGE_PORT||"1111",10),s=(o=e==null?void 0:e.basePath)!=null?o:"/popmelt",g=`http://localhost:${a}`;return{name:"popmelt-canvas",configureServer(p){p.middlewares.use((t,r,m)=>{let c=t.url||"";if(!c.startsWith(s))return m();let P="/canvas"+c.slice(s.length),i=new URL(P,g),l=v(i,{method:t.method,headers:d(u({},t.headers),{host:i.host})},n=>{r.writeHead(n.statusCode||502,n.headers),n.pipe(r)});l.on("error",()=>{r.writeHead(502,{"Content-Type":"text/plain"}),r.end(`Popmelt bridge not running on port ${a}`)}),t.pipe(l)})}}}export{y as popmelt};
|
package/dist/server.d.mts
CHANGED
package/dist/server.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as te,b as ce,c as ot,d as de}from"./chunk-3HWT3PC2.mjs";import{execFileSync as yn}from"child_process";import{createHash as wn,randomUUID as fe}from"crypto";import{mkdir as vn,readFile as Sn,readdir as In,stat as xn,unlink as Pn,writeFile as ve}from"fs/promises";import{createServer as kn}from"http";import{tmpdir as bn}from"os";import{dirname as Tn,join as oe}from"path";import{fileURLToPath as Rn}from"url";function rt(r,n){return`<!DOCTYPE html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -18,23 +18,23 @@ import{a as ee,b as ce,c as tt,d as de}from"./chunk-3HWT3PC2.mjs";import{execFil
|
|
|
18
18
|
}}
|
|
19
19
|
</script>
|
|
20
20
|
<script type="module">
|
|
21
|
-
import { mountCanvas } from 'http://localhost:${
|
|
21
|
+
import { mountCanvas } from 'http://localhost:${r}/canvas/app.mjs';
|
|
22
22
|
mountCanvas(document.getElementById('root'), {
|
|
23
23
|
devOrigin: '${n}',
|
|
24
|
-
bridgeOrigin: 'http://localhost:${
|
|
24
|
+
bridgeOrigin: 'http://localhost:${r}',
|
|
25
25
|
});
|
|
26
26
|
</script>
|
|
27
27
|
</body>
|
|
28
|
-
</html>`}import{spawn as Ut}from"child_process";import{createInterface as Ft}from"readline";function Oe(i,n){let{prompt:t,projectRoot:e,maxTurns:o=40,maxBudgetUsd:a=1,allowedTools:r=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:l="claude",resumeSessionId:p,model:f,timeoutMs:I=3e5,onEvent:O}=n,L=[];p?L.push("--resume",p,"-p",t):L.push("-p",t),L.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(a)),f&&L.push("--model",f);for(let P of r)L.push("--allowedTools",P);let m=Ut(l,L,{cwd:e,stdio:["ignore","pipe","pipe"],env:ce(ee({},process.env),{ANTHROPIC_API_KEY:void 0})}),_=new Promise(P=>{var W;let U,N=[],H=[],te=!1,G="",V=!1,E=setTimeout(()=>{V=!0,m.kill("SIGTERM"),setTimeout(()=>{try{m.kill("SIGKILL")}catch(T){}},5e3)},I),ne=Ft({input:m.stdout}),C=new Set;ne.on("line",T=>{var K,me,Pe,ke,be,Te,Re,$e,Me;if(T.trim())try{let Q=JSON.parse(T);Q.session_id&&!U&&(U=Q.session_id);let Ne=(me=Q.type)!=null?me:(K=Q.event)!=null&&K.type?`event.${Q.event.type}`:"unknown";if(C.add(Ne),Q.type==="result"&&Q.result&&N.length===0){let B=typeof Q.result=="string"?Q.result:"";B&&(N.push(B),O==null||O({type:"delta",jobId:i,text:B},i))}if(Q.type==="assistant"&&Array.isArray((Pe=Q.message)==null?void 0:Pe.content))for(let B of Q.message.content){if(B.type==="text"&&B.text&&(N.push(B.text),O==null||O({type:"delta",jobId:i,text:B.text},i)),B.type==="tool_use"&&B.name){let Ce=((ke=B.input)==null?void 0:ke.file_path)||((be=B.input)==null?void 0:be.path)||void 0;O==null||O(ee({type:"tool_use",jobId:i,tool:B.name},Ce?{file:Ce}:{}),i),B.name==="Edit"&&((Te=B.input)!=null&&Te.file_path)?H.push({tool:"Edit",file_path:B.input.file_path,old_string:B.input.old_string,new_string:B.input.new_string,replace_all:B.input.replace_all}):B.name==="Write"&&((Re=B.input)!=null&&Re.file_path)&&H.push({tool:"Write",file_path:B.input.file_path,content:B.input.content})}B.type==="thinking"&&B.thinking&&(O==null||O({type:"thinking",jobId:i,text:B.thinking},i))}Q.type==="user"&&((Me=($e=Q.tool_use_result)==null?void 0:$e.file)!=null&&Me.filePath)&&(O==null||O({type:"tool_use",jobId:i,tool:"Read",file:Q.tool_use_result.file.filePath},i))}catch(Q){}});let x=[];(W=m.stderr)==null||W.on("data",T=>{x.push(T.toString())}),m.on("close",T=>{clearTimeout(E),ne.close(),N.length===0&&C.size>0&&console.warn(`[Claude:${i}] No text captured. Event types seen: ${[...C].join(", ")}`),V?(te=!0,G=`Timed out after ${Math.round(I/6e4)} minutes`):T!==0&&T!==null&&(te=!0,G=x.join("")||`Claude process exited with code ${T}`),P({sessionId:U,text:N.join(""),success:!te,error:te?G:void 0,fileEdits:H.length>0?H:void 0})}),m.on("error",T=>{clearTimeout(E),te=!0,G=T.message,P({sessionId:U,text:N.join(""),success:!1,error:G,fileEdits:H.length>0?H:void 0})})});return{process:m,result:_}}import{spawn as zt}from"child_process";import{createInterface as Lt}from"readline";function st(i,n){let{prompt:t,projectRoot:e,screenshotPath:o,resumeSessionId:a,model:r,onEvent:l}=n,p=[];a?(p.push("exec","resume",a),r&&p.push("-m",r),p.push("--json","--full-auto",t),o&&p.push("--image",o)):(p.push("exec","--json","--full-auto"),r&&p.push("-m",r),p.push(t),o&&p.push("--image",o));let f=zt("codex",p,{cwd:e,stdio:["ignore","pipe","pipe"],env:ee({},process.env)}),I=new Promise(O=>{var te;let L,m=[],_=!1,P="",U=Lt({input:f.stdout}),N=new Set;U.on("line",G=>{var V,E,ne,C;if(G.trim())try{let x=JSON.parse(G),W=(V=x.type)!=null?V:"unknown";if(N.add(W),W==="thread.started"&&x.thread_id&&!L&&(L=x.thread_id),(W==="item.agentMessage.delta"||W==="item/agentMessage/delta")&&((E=x.delta)!=null&&E.text)&&(m.push(x.delta.text),l==null||l({type:"delta",jobId:i,text:x.delta.text},i)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&((ne=x.delta)!=null&&ne.text)&&(l==null||l({type:"thinking",jobId:i,text:x.delta.text},i)),(W==="item.started"||W==="item/started")&&x.item){let T=x.item.type;if(T==="command_execution")l==null||l({type:"tool_use",jobId:i,tool:"Bash"},i);else if(T==="file_change"){let K=x.item.filename||x.item.path;l==null||l(ee({type:"tool_use",jobId:i,tool:"Edit"},K?{file:K}:{}),i)}else if(T==="file_read"){let K=x.item.filename||x.item.path;l==null||l(ee({type:"tool_use",jobId:i,tool:"Read"},K?{file:K}:{}),i)}else if(T==="web_search")l==null||l({type:"tool_use",jobId:i,tool:"WebSearch"},i);else if(T==="mcp_tool_call"){let K=x.item.tool_name||x.item.name||"MCP";l==null||l({type:"tool_use",jobId:i,tool:K},i)}}if((W==="item.completed"||W==="item/completed")&&x.item){if(x.item.type==="agent_message"){let T=x.item.text;typeof T=="string"&&T&&(m.push(T),l==null||l({type:"delta",jobId:i,text:T},i))}else if(x.item.type==="reasoning"){let T=x.item.text;typeof T=="string"&&T&&(l==null||l({type:"thinking",jobId:i,text:T},i))}}W==="turn.failed"&&(_=!0,P=((C=x.error)==null?void 0:C.message)||x.message||"Turn failed")}catch(x){}});let H=[];(te=f.stderr)==null||te.on("data",G=>{H.push(G.toString())}),f.on("close",G=>{U.close(),m.length===0&&N.size>0&&console.warn(`[Codex:${i}] No text captured. Event types seen: ${[...N].join(", ")}`),G!==0&&G!==null&&(_=!0,P=H.join("")||`Codex process exited with code ${G}`),O({sessionId:L,text:m.join(""),success:!_,error:_?P:void 0})}),f.on("error",G=>{_=!0,P=G.message,O({sessionId:L,text:m.join(""),success:!1,error:P})})});return{process:f,result:I}}import{execFile as Ht}from"child_process";import{copyFile as ot,mkdir as rt,readdir as Gt,readFile as jt,writeFile as Wt}from"fs/promises";import{join as he}from"path";var Ee=class{constructor(n){this.projectRoot=n;let t=he(n,".popmelt");this.decisionsDir=he(t,"decisions"),this.screenshotsDir=he(t,"screenshots")}async persist(n,t,e){try{await rt(this.decisionsDir,{recursive:!0}),await rt(this.screenshotsDir,{recursive:!0});try{await ot(t,he(this.screenshotsDir,`s-${n.id}.png`))}catch(o){}for(let o=0;o<e.length;o++)try{let a=n.pastedImagePaths[o];a&&await ot(e[o],he(this.screenshotsDir,a.replace("screenshots/","")))}catch(a){}await Wt(he(this.decisionsDir,`d-${n.id}.json`),JSON.stringify(n,null,2))}catch(o){console.error("[DecisionStore] Failed to persist decision record:",o)}}async listDecisionIds(){try{return(await Gt(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch(n){return[]}}async loadDecision(n){try{let t=await jt(he(this.decisionsDir,`d-${n}.json`),"utf-8");return JSON.parse(t)}catch(t){return null}}async loadDecisions(n){return(await Promise.all(n.map(e=>this.loadDecision(e)))).filter(e=>e!==null)}captureGitDiff(n){return new Promise(t=>{Ht("git",["diff","HEAD"],{cwd:n,timeout:5e3,maxBuffer:1024*1024},(e,o)=>{if(e){t(null);return}t(o||null)})})}};import{readFile as it,writeFile as ge}from"fs/promises";import{join as Ue}from"path";var ie="[Materializer]",Yt={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Ae=class{constructor(n,t,e={}){this.projectRoot=n;this.decisionStore=t;this.options=e;this.cachedIndex=null;this.running=!1;let o=Ue(n,".popmelt");this.indexPath=Ue(o,"materialized.json"),this.modelPath=Ue(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let n=await it(this.modelPath,"utf-8");return JSON.parse(n)}catch(n){return null}}async addComponent(n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]}),(!t.components||typeof t.components!="object")&&(t.components={});let e=t.components;return e[n]?{added:!1,alreadyExists:!0}:(e[n]={description:""},await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} Added component "${n}" to model`),{added:!0,alreadyExists:!1})}async updateToken(n,t){let e=await this.loadModel();e||(e={tokens:{},components:{},rules:[]});let o=n.split("."),a=e;for(let p=0;p<o.length-1;p++){let f=o[p];(!a[f]||typeof a[f]!="object")&&(a[f]={}),a=a[f]}let r=o[o.length-1],l;try{l=JSON.parse(t)}catch(p){l=null}if(l&&typeof l=="object"&&l!==null&&"value"in l)a[r]=l;else{let p=a[r];p&&typeof p=="object"&&p!==null&&"value"in p?p.value=t:a[r]=t}return await ge(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ie} Updated token "${n}" \u2192 "${t.slice(0,80)}"`),{updated:!0}}async removeToken(n){let t=await this.loadModel();if(!t)return{removed:!1};let e=n.split("."),o=t;for(let r=0;r<e.length-1;r++){let l=e[r];if(!o[l]||typeof o[l]!="object")return{removed:!1};o=o[l]}let a=e[e.length-1];return a in o?(delete o[a],await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} Removed token "${n}" from model`),{removed:!0}):{removed:!1}}async removeComponent(n){let t=await this.loadModel();if(!t)return{removed:!1};let e=t.components;return!e||!e[n]?{removed:!1}:(delete e[n],await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} Removed component "${n}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let n=await this.loadIndex(),t=new Set(n.materializedIds),o=(await this.decisionStore.listDecisionIds()).filter(r=>!t.has(r));return o.length===0?[]:(await this.decisionStore.loadDecisions(o)).filter(r=>r.resolutions.some(l=>{var f;let p=(f=l.finalScope)!=null?f:l.inferredScope;return(p==null?void 0:p.breadth)==="pattern"}))}async run(){var n,t,e,o,a,r,l;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 f=p.map(U=>U.id);console.log(`${ie} Processing ${f.length} pattern-scoped decision(s): ${f.join(", ")}`),(t=(n=this.options).onEvent)==null||t.call(n,{type:"materialize_started",decisionIds:f});let I=await this.loadModel(),O=Qt(p,I),L=!0,m;try{let{result:U}=Oe(`mat-${Date.now()}`,{prompt:O,projectRoot:this.projectRoot,maxTurns:(e=this.options.maxTurns)!=null?e:5,maxBudgetUsd:(o=this.options.maxBudgetUsd)!=null?o:.5,allowedTools:["Read"],claudePath:(a=this.options.claudePath)!=null?a:"claude"}),N=await U;if(!N.success)L=!1,m=N.error,console.error(`${ie} Claude spawn error:`,m);else{let H=qt(N.text);H?(await ge(this.modelPath,JSON.stringify(H,null,2)),console.log(`${ie} Successfully materialized ${f.length} decision(s) \u2192 ${this.modelPath}`)):(L=!1,m="No <model> block found in response",console.error(`${ie} ${m}`))}}catch(U){L=!1,m=U instanceof Error?U.message:String(U),console.error(`${ie} Error:`,m)}let _=await this.loadIndex(),P=new Set(_.materializedIds);for(let U of f)P.add(U);return _.materializedIds=[...P],_.lastRunAt=Date.now(),_.lastRunDecisionIds=f,_.lastRunError=m!=null?m:null,await this.persistIndex(_),(l=(r=this.options).onEvent)==null||l.call(r,{type:"materialize_done",decisionIds:f,success:L,error:m}),{processedIds:f,success:L,error:m}}finally{this.running=!1}}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let n=await it(this.indexPath,"utf-8"),t=JSON.parse(n);return this.cachedIndex=t,t}catch(n){return this.cachedIndex=ce(ee({},Yt),{materializedIds:[],lastRunDecisionIds:[]}),this.cachedIndex}}async persistIndex(n){this.cachedIndex=n;try{await ge(this.indexPath,JSON.stringify(n,null,2))}catch(t){console.error(`${ie} Failed to write index:`,t)}}};function qt(i){let n=i.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!(n!=null&&n[1]))return null;try{let t=JSON.parse(n[1]);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch(t){return null}}function Qt(i,n){let t=i.map(o=>{let r=o.resolutions.filter(f=>{var O;let I=(O=f.finalScope)!=null?O:f.inferredScope;return(I==null?void 0:I.breadth)==="pattern"}).map(f=>{var m,_,P,U;let I=(m=f.finalScope)!=null?m:f.inferredScope,O=(_=I==null?void 0:I.target)!=null?_:"unknown",L=(U=(P=f.filesModified)==null?void 0:P.join(", "))!=null?U:"none";return`- **${f.summary}** [scope: pattern/${O}]
|
|
29
|
-
Files modified: ${
|
|
28
|
+
</html>`}import{spawn as Wt}from"child_process";import{createInterface as Yt}from"readline";function Ce(r,n){let{prompt:t,projectRoot:e,maxTurns:o=40,maxBudgetUsd:a=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:l="claude",resumeSessionId:h,model:f,timeoutMs:J=3e5,onEvent:A}=n,O=[];h?O.push("--resume",h,"-p",t):O.push("-p",t),O.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(a)),f&&O.push("--model",f);for(let W of i)O.push("--allowedTools",W);let g=Wt(l,O,{cwd:e,stdio:["ignore","pipe","pipe"],env:ce(te({},process.env),{ANTHROPIC_API_KEY:void 0})}),H=new Promise(W=>{var G;let v,L=[],C=[],V=!1,E="",X=!1,U=setTimeout(()=>{X=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch(k){}},5e3)},J),ne=Yt({input:g.stdout}),P=new Set;ne.on("line",k=>{var K,me,Pe,ke,be,Te,Re,$e,Me;if(k.trim())try{let q=JSON.parse(k);q.session_id&&!v&&(v=q.session_id);let Ne=(me=q.type)!=null?me:(K=q.event)!=null&&K.type?`event.${q.event.type}`:"unknown";if(P.add(Ne),q.type==="result"&&q.result&&L.length===0){let B=typeof q.result=="string"?q.result:"";B&&(L.push(B),A==null||A({type:"delta",jobId:r,text:B},r))}if(q.type==="assistant"&&Array.isArray((Pe=q.message)==null?void 0:Pe.content))for(let B of q.message.content){if(B.type==="text"&&B.text&&(L.push(B.text),A==null||A({type:"delta",jobId:r,text:B.text},r)),B.type==="tool_use"&&B.name){let Oe=((ke=B.input)==null?void 0:ke.file_path)||((be=B.input)==null?void 0:be.path)||void 0;A==null||A(te({type:"tool_use",jobId:r,tool:B.name},Oe?{file:Oe}:{}),r),B.name==="Edit"&&((Te=B.input)!=null&&Te.file_path)?C.push({tool:"Edit",file_path:B.input.file_path,old_string:B.input.old_string,new_string:B.input.new_string,replace_all:B.input.replace_all}):B.name==="Write"&&((Re=B.input)!=null&&Re.file_path)&&C.push({tool:"Write",file_path:B.input.file_path,content:B.input.content})}B.type==="thinking"&&B.thinking&&(A==null||A({type:"thinking",jobId:r,text:B.thinking},r))}q.type==="user"&&((Me=($e=q.tool_use_result)==null?void 0:$e.file)!=null&&Me.filePath)&&(A==null||A({type:"tool_use",jobId:r,tool:"Read",file:q.tool_use_result.file.filePath},r))}catch(q){}});let x=[];(G=g.stderr)==null||G.on("data",k=>{x.push(k.toString())}),g.on("close",k=>{clearTimeout(U),ne.close(),L.length===0&&P.size>0&&console.warn(`[Claude:${r}] No text captured. Event types seen: ${[...P].join(", ")}`),X?(V=!0,E=`Timed out after ${Math.round(J/6e4)} minutes`):k!==0&&k!==null&&(V=!0,E=x.join("")||`Claude process exited with code ${k}`),W({sessionId:v,text:L.join(""),success:!V,error:V?E:void 0,fileEdits:C.length>0?C:void 0})}),g.on("error",k=>{clearTimeout(U),V=!0,E=k.message,W({sessionId:v,text:L.join(""),success:!1,error:E,fileEdits:C.length>0?C:void 0})})});return{process:g,result:H}}import{spawn as Qt}from"child_process";import{createInterface as qt}from"readline";function it(r,n){let{prompt:t,projectRoot:e,screenshotPath:o,resumeSessionId:a,model:i,onEvent:l}=n,h=[];a?(h.push("exec","resume",a),i&&h.push("-m",i),h.push("--json","--full-auto",t),o&&h.push("--image",o)):(h.push("exec","--json","--full-auto"),i&&h.push("-m",i),h.push(t),o&&h.push("--image",o));let f=Qt("codex",h,{cwd:e,stdio:["ignore","pipe","pipe"],env:te({},process.env)}),J=new Promise(A=>{var V;let O,g=[],H=!1,W="",v=qt({input:f.stdout}),L=new Set;v.on("line",E=>{var X,U,ne,P;if(E.trim())try{let x=JSON.parse(E),G=(X=x.type)!=null?X:"unknown";if(L.add(G),G==="thread.started"&&x.thread_id&&!O&&(O=x.thread_id),(G==="item.agentMessage.delta"||G==="item/agentMessage/delta")&&((U=x.delta)!=null&&U.text)&&(g.push(x.delta.text),l==null||l({type:"delta",jobId:r,text:x.delta.text},r)),(G==="item.reasoning.delta"||G==="item/reasoning/delta")&&((ne=x.delta)!=null&&ne.text)&&(l==null||l({type:"thinking",jobId:r,text:x.delta.text},r)),(G==="item.started"||G==="item/started")&&x.item){let k=x.item.type;if(k==="command_execution")l==null||l({type:"tool_use",jobId:r,tool:"Bash"},r);else if(k==="file_change"){let K=x.item.filename||x.item.path;l==null||l(te({type:"tool_use",jobId:r,tool:"Edit"},K?{file:K}:{}),r)}else if(k==="file_read"){let K=x.item.filename||x.item.path;l==null||l(te({type:"tool_use",jobId:r,tool:"Read"},K?{file:K}:{}),r)}else if(k==="web_search")l==null||l({type:"tool_use",jobId:r,tool:"WebSearch"},r);else if(k==="mcp_tool_call"){let K=x.item.tool_name||x.item.name||"MCP";l==null||l({type:"tool_use",jobId:r,tool:K},r)}}if((G==="item.completed"||G==="item/completed")&&x.item){if(x.item.type==="agent_message"){let k=x.item.text;typeof k=="string"&&k&&(g.push(k),l==null||l({type:"delta",jobId:r,text:k},r))}else if(x.item.type==="reasoning"){let k=x.item.text;typeof k=="string"&&k&&(l==null||l({type:"thinking",jobId:r,text:k},r))}}G==="turn.failed"&&(H=!0,W=((P=x.error)==null?void 0:P.message)||x.message||"Turn failed")}catch(x){}});let C=[];(V=f.stderr)==null||V.on("data",E=>{C.push(E.toString())}),f.on("close",E=>{v.close(),g.length===0&&L.size>0&&console.warn(`[Codex:${r}] No text captured. Event types seen: ${[...L].join(", ")}`),E!==0&&E!==null&&(H=!0,W=C.join("")||`Codex process exited with code ${E}`),A({sessionId:O,text:g.join(""),success:!H,error:H?W:void 0})}),f.on("error",E=>{H=!0,W=E.message,A({sessionId:O,text:g.join(""),success:!1,error:W})})});return{process:f,result:J}}import{execFile as Kt}from"child_process";import{copyFile as at,mkdir as ct,readdir as Xt,readFile as Vt,writeFile as Zt}from"fs/promises";import{join as he}from"path";var Ee=class{constructor(n){this.projectRoot=n;let t=he(n,".popmelt");this.decisionsDir=he(t,"decisions"),this.screenshotsDir=he(t,"screenshots")}async persist(n,t,e){try{await ct(this.decisionsDir,{recursive:!0}),await ct(this.screenshotsDir,{recursive:!0});try{await at(t,he(this.screenshotsDir,`s-${n.id}.png`))}catch(o){}for(let o=0;o<e.length;o++)try{let a=n.pastedImagePaths[o];a&&await at(e[o],he(this.screenshotsDir,a.replace("screenshots/","")))}catch(a){}await Zt(he(this.decisionsDir,`d-${n.id}.json`),JSON.stringify(n,null,2))}catch(o){console.error("[DecisionStore] Failed to persist decision record:",o)}}async listDecisionIds(){try{return(await Xt(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch(n){return[]}}async loadDecision(n){try{let t=await Vt(he(this.decisionsDir,`d-${n}.json`),"utf-8");return JSON.parse(t)}catch(t){return null}}async loadDecisions(n){return(await Promise.all(n.map(e=>this.loadDecision(e)))).filter(e=>e!==null)}captureGitDiff(n){return new Promise(t=>{Kt("git",["diff","HEAD"],{cwd:n,timeout:5e3,maxBuffer:1024*1024},(e,o)=>{if(e){t(null);return}t(o||null)})})}};import{readFile as lt,writeFile as ge}from"fs/promises";import{join as Ue}from"path";var ie="[Materializer]",en={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Ae=class{constructor(n,t,e={}){this.projectRoot=n;this.decisionStore=t;this.options=e;this.cachedIndex=null;this.running=!1;let o=Ue(n,".popmelt");this.indexPath=Ue(o,"materialized.json"),this.modelPath=Ue(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let n=await lt(this.modelPath,"utf-8");return JSON.parse(n)}catch(n){return null}}async addComponent(n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]}),(!t.components||typeof t.components!="object")&&(t.components={});let e=t.components;return e[n]?{added:!1,alreadyExists:!0}:(e[n]={description:""},await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} Added component "${n}" to model`),{added:!0,alreadyExists:!1})}async updateToken(n,t){let e=await this.loadModel();e||(e={tokens:{},components:{},rules:[]});let o=n.split("."),a=e;for(let h=0;h<o.length-1;h++){let f=o[h];(!a[f]||typeof a[f]!="object")&&(a[f]={}),a=a[f]}let i=o[o.length-1],l;try{l=JSON.parse(t)}catch(h){l=null}if(l&&typeof l=="object"&&l!==null&&"value"in l)a[i]=l;else{let h=a[i];h&&typeof h=="object"&&h!==null&&"value"in h?h.value=t:a[i]=t}return await ge(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ie} Updated token "${n}" \u2192 "${t.slice(0,80)}"`),{updated:!0}}async removeToken(n){let t=await this.loadModel();if(!t)return{removed:!1};let e=n.split("."),o=t;for(let i=0;i<e.length-1;i++){let l=e[i];if(!o[l]||typeof o[l]!="object")return{removed:!1};o=o[l]}let a=e[e.length-1];return a in o?(delete o[a],await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} Removed token "${n}" from model`),{removed:!0}):{removed:!1}}async removeComponent(n){let t=await this.loadModel();if(!t)return{removed:!1};let e=t.components;return!e||!e[n]?{removed:!1}:(delete e[n],await ge(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} Removed component "${n}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let n=await this.loadIndex(),t=new Set(n.materializedIds),o=(await this.decisionStore.listDecisionIds()).filter(i=>!t.has(i));return o.length===0?[]:(await this.decisionStore.loadDecisions(o)).filter(i=>i.resolutions.some(l=>{var f;let h=(f=l.finalScope)!=null?f:l.inferredScope;return(h==null?void 0:h.breadth)==="pattern"}))}async run(){var n,t,e,o,a,i,l;if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;try{let h=await this.getUnmaterializedPatternDecisions();if(h.length===0)return{processedIds:[],success:!0};let f=h.map(v=>v.id);console.log(`${ie} Processing ${f.length} pattern-scoped decision(s): ${f.join(", ")}`),(t=(n=this.options).onEvent)==null||t.call(n,{type:"materialize_started",decisionIds:f});let J=await this.loadModel(),A=nn(h,J),O=!0,g;try{let{result:v}=Ce(`mat-${Date.now()}`,{prompt:A,projectRoot:this.projectRoot,maxTurns:(e=this.options.maxTurns)!=null?e:5,maxBudgetUsd:(o=this.options.maxBudgetUsd)!=null?o:.5,allowedTools:["Read"],claudePath:(a=this.options.claudePath)!=null?a:"claude"}),L=await v;if(!L.success)O=!1,g=L.error,console.error(`${ie} Claude spawn error:`,g);else{let C=tn(L.text);C?(await ge(this.modelPath,JSON.stringify(C,null,2)),console.log(`${ie} Successfully materialized ${f.length} decision(s) \u2192 ${this.modelPath}`)):(O=!1,g="No <model> block found in response",console.error(`${ie} ${g}`))}}catch(v){O=!1,g=v instanceof Error?v.message:String(v),console.error(`${ie} Error:`,g)}let H=await this.loadIndex(),W=new Set(H.materializedIds);for(let v of f)W.add(v);return H.materializedIds=[...W],H.lastRunAt=Date.now(),H.lastRunDecisionIds=f,H.lastRunError=g!=null?g:null,await this.persistIndex(H),(l=(i=this.options).onEvent)==null||l.call(i,{type:"materialize_done",decisionIds:f,success:O,error:g}),{processedIds:f,success:O,error:g}}finally{this.running=!1}}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let n=await lt(this.indexPath,"utf-8"),t=JSON.parse(n);return this.cachedIndex=t,t}catch(n){return this.cachedIndex=ce(te({},en),{materializedIds:[],lastRunDecisionIds:[]}),this.cachedIndex}}async persistIndex(n){this.cachedIndex=n;try{await ge(this.indexPath,JSON.stringify(n,null,2))}catch(t){console.error(`${ie} Failed to write index:`,t)}}};function tn(r){let n=r.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!(n!=null&&n[1]))return null;try{let t=JSON.parse(n[1]);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch(t){return null}}function nn(r,n){let t=r.map(o=>{let i=o.resolutions.filter(f=>{var A;let J=(A=f.finalScope)!=null?A:f.inferredScope;return(J==null?void 0:J.breadth)==="pattern"}).map(f=>{var g,H,W,v;let J=(g=f.finalScope)!=null?g:f.inferredScope,A=(H=J==null?void 0:J.target)!=null?H:"unknown",O=(v=(W=f.filesModified)==null?void 0:W.join(", "))!=null?v:"none";return`- **${f.summary}** [scope: pattern/${A}]
|
|
29
|
+
Files modified: ${O}`}).join(`
|
|
30
30
|
`),l=o.annotations.map(f=>f.instruction).filter(Boolean).join(`
|
|
31
|
-
`),
|
|
31
|
+
`),h=o.gitDiff?`
|
|
32
32
|
\`\`\`diff
|
|
33
33
|
${o.gitDiff.slice(0,2e3)}
|
|
34
34
|
\`\`\``:"";return`### Decision ${o.id} (${new Date(o.createdAt).toISOString()})
|
|
35
35
|
Page: ${o.url}
|
|
36
|
-
${
|
|
37
|
-
${
|
|
36
|
+
${i}
|
|
37
|
+
${h}
|
|
38
38
|
${l?`
|
|
39
39
|
Original instructions:
|
|
40
40
|
${l}`:""}`}).join(`
|
|
@@ -93,39 +93,39 @@ Example:
|
|
|
93
93
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
94
94
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
95
95
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
96
|
-
Include property and bindings when the decision context has class-level evidence.`}import{readFile as
|
|
97
|
-
`),t=[],e=null;for(let o of n){let a=o.match(
|
|
96
|
+
Include property and bindings when the decision context has class-level evidence.`}import{readFile as pt}from"fs/promises";import{homedir as ht}from"os";import{join as ye}from"path";var Le=/popmelt/i;function ze(){return{found:!1,name:null,scope:null,disabled:!1}}function Ie(r,n,t=!1){return{found:!0,name:r,scope:n,disabled:t}}function De(r){for(let n of Object.keys(r))if(Le.test(n))return n;return null}async function Fe(r){try{let n=await pt(r,"utf-8");return JSON.parse(n)}catch(n){return null}}async function He(r){let n=ht(),t=await Fe(ye(n,".claude.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=De(o.mcpServers);if(a)return Ie(a,"user")}if(o.projects&&typeof o.projects=="object"){let i=o.projects[r];if(i&&typeof i=="object"){let l=i;if(l.mcpServers&&typeof l.mcpServers=="object"){let h=De(l.mcpServers);if(h){let f=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(J=>Le.test(J));return Ie(h,"project",f)}}}}}let e=await Fe(ye(r,".mcp.json"));if(e&&typeof e=="object"){let o=e;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=De(o.mcpServers);if(i){let l=await dt(r,i);return Ie(i,"mcp.json",l)}}let a=De(o);if(a&&a!=="mcpServers"){let i=await dt(r,a);return Ie(a,"mcp.json",i)}}return ze()}async function dt(r,n){let t=ye(r,".claude","settings.local.json"),e=await Fe(t);if(e&&typeof e=="object"){let o=e;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(a=>a===n)}return!1}var sn=/^\[mcp_servers\.([^\]]+)\]/;function on(r){let n=r.split(`
|
|
97
|
+
`),t=[],e=null;for(let o of n){let a=o.match(sn);a?(e&&t.push({name:e.name,body:e.bodyLines.join(`
|
|
98
98
|
`)}),e={name:a[1],bodyLines:[]}):o.startsWith("[")?e&&(t.push({name:e.name,body:e.bodyLines.join(`
|
|
99
99
|
`)}),e=null):e&&e.bodyLines.push(o)}return e&&t.push({name:e.name,body:e.bodyLines.join(`
|
|
100
|
-
`)}),t}function
|
|
101
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
100
|
+
`)}),t}function rn(r){return/enabled\s*=\s*false/i.test(r)}async function Ge(r){let n=process.env.CODEX_HOME||ye(ht(),".codex"),t=await ut(ye(n,"config.toml"),"user");if(t.found)return t;let e=await ut(ye(r,".codex","config.toml"),"project");return e.found?e:ze()}async function ut(r,n){try{let t=await pt(r,"utf-8"),e=on(t);for(let o of e)if(Le.test(o.name)){let a=rn(o.body);return Ie(o.name,n,a)}}catch(t){}return ze()}import{mkdir as an,readFile as ft,writeFile as mt}from"fs/promises";import{homedir as gt}from"os";import{dirname as cn,join as je}from"path";var yt="https://mcp.popmelt.com/mcp";async function wt(r=yt){let n=je(gt(),".claude.json"),t;try{let o=await ft(n,"utf-8");t=JSON.parse(o)}catch(o){t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let e=t.mcpServers;for(let o of Object.keys(e))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return e.popmelt={type:"http",url:r},await mt(n,JSON.stringify(t,null,2)+`
|
|
101
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function vt(r=yt){let n=process.env.CODEX_HOME||je(gt(),".codex"),t=je(n,"config.toml"),e;try{e=await ft(t,"utf-8")}catch(a){e=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(e))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await an(cn(t),{recursive:!0});let o=`
|
|
102
102
|
[mcp_servers.popmelt]
|
|
103
|
-
url = "${
|
|
104
|
-
`;return await
|
|
103
|
+
url = "${r}"
|
|
104
|
+
`;return await mt(t,e+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 e=t[1]||t[2],o=await ln(r),a=Buffer.from(`--${e}`),i=Buffer.from(`--${e}--`),l,h,f,J,A,O,g,H,W,v,L,C,V=[],E=0,X=[];for(;E<o.length;){let U=o.indexOf(a,E);if(U===-1)break;let ne=U+a.length;if(o.slice(U,U+i.length).equals(i))break;let P=ne;o[P]===13&&o[P+1]===10&&(P+=2);let x=o.indexOf(`\r
|
|
105
105
|
\r
|
|
106
|
-
`,
|
|
107
|
-
### ${a.tokenName}: ${a.originalPx}px \u2192 ${a.newPx}px`);for(let
|
|
108
|
-
`)}function
|
|
109
|
-
`)}function
|
|
110
|
-
`)}function
|
|
111
|
-
`)}function
|
|
112
|
-
`)}function
|
|
113
|
-
`)}function
|
|
106
|
+
`,P);if(x===-1)break;let G=o.slice(P,x).toString("utf-8"),k=x+4,K=o.indexOf(a,k),me=K!==-1?K-2:o.length;X.push({headers:G,body:o.slice(k,me)}),E=K!==-1?K:o.length}for(let U of X){let ne=U.headers.match(/name="([^"]+)"/);if(!ne)continue;let P=ne[1];if(P==="screenshot")l=U.body;else if(P==="feedback")h=U.body.toString("utf-8");else if(P==="color")f=U.body.toString("utf-8");else if(P==="provider")J=U.body.toString("utf-8");else if(P==="model")A=U.body.toString("utf-8");else if(P==="goal")O=U.body.toString("utf-8");else if(P==="pageUrl")g=U.body.toString("utf-8");else if(P==="viewport")H=U.body.toString("utf-8");else if(P==="planId")W=U.body.toString("utf-8");else if(P==="manifest")v=U.body.toString("utf-8");else if(P==="tasks")L=U.body.toString("utf-8");else if(P==="sourceId")C=U.body.toString("utf-8");else if(P.startsWith("image-")){let x=P.split("-"),G=parseInt(x[x.length-1],10),k=x.slice(1,-1).join("-");k&&!isNaN(G)&&V.push({annotationId:k,index:G,data:U.body})}}if(!l)throw new Error("Missing screenshot field");return h||(h=""),{screenshot:l,feedback:h,color:f,provider:J,model:A,goal:O,pageUrl:g,viewport:H,planId:W,manifest:v,tasks:L,sourceId:C,pastedImages:V}}function ln(r){return new Promise((n,t)=>{let e=[];r.on("data",o=>e.push(o)),r.on("end",()=>n(Buffer.concat(e))),r.on("error",t)})}function xe(r,n){var e,o;let t=[];if(r.annotations.length>0){t.push("## Annotations");for(let a of r.annotations){let i=a.elements.map(f=>{let J=[f.selector];return f.reactComponent&&J.push(`(${f.reactComponent})`),J.join(" ")}).join(", "),l=a.instruction||"No text";t.push(`- id=${a.id} [${a.type}] ${l} \u2192 Elements: ${i||"none"}`);let h=n==null?void 0:n[a.id];if(h&&h.length>0)for(let f of h)t.push(` Attached image: use the Read tool to view ${f}`)}}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 a of r.styleModifications){let i=(e=a.element)!=null&&e.reactComponent?`(${a.element.reactComponent})`:"";for(let l of a.changes)t.push(`- ${a.selector} ${i}: ${l.property} ${l.original} \u2192 ${l.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 a of r.spacingTokenChanges){t.push(`
|
|
107
|
+
### ${a.tokenName}: ${a.originalPx}px \u2192 ${a.newPx}px`);for(let i of a.affectedElements){let l=i.reactComponent?` (${i.reactComponent})`:"";i.matchedClass&&i.suggestedClass?t.push(`- ${i.selector}${l}: \`${i.matchedClass}\` \u2192 \`${i.suggestedClass}\``):t.push(`- ${i.selector}${l}: ${i.property} ${a.originalPx}px \u2192 ${a.newPx}px`),t.push(` class="${i.className}"`)}}}if(r.inspectedElement){let a=r.inspectedElement;t.push(""),t.push("## Inspected Element"),t.push("The developer has this element selected in the inspector:");let i=[a.selector];a.reactComponent&&i.push(`(${a.reactComponent})`),a.context&&i.push(`in ${a.context}`),a.textContent&&i.push(`"${a.textContent.slice(0,80)}"`),t.push(`- ${i.join(" ")}`)}return t.join(`
|
|
108
|
+
`)}function St(r,n,t){var a;let e=[];if(e.push("You are reviewing a UI screenshot with developer annotations."),e.push(""),(t==null?void 0:t.provider)!=="codex"&&(e.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),e.push("")),e.push(`The developer annotated their running app at ${n.url} (${n.viewport.width}x${n.viewport.height}).`),t!=null&&t.threadHistory&&t.threadHistory.length>0){e.push(""),e.push("## Previous Conversation");let i=0;for(let l of t.threadHistory)if(l.role==="human")i++,l.replyToQuestion?(e.push(`### Round ${i} (human) \u2014 reply`),e.push(`"${l.replyToQuestion}"`)):(e.push(`### Round ${i} (human)`),l.feedbackSummary&&e.push(`Annotations: ${l.feedbackSummary}`),l.annotationIds&&l.annotationIds.length>0&&e.push(`Annotation IDs: ${l.annotationIds.join(", ")}`));else if(l.question)e.push(`### Round ${i} (assistant) \u2014 question`),e.push(`"${l.question}"`);else{if(e.push(`### Round ${i} (assistant)`),l.responseText&&e.push(`Response: ${l.responseText}`),l.resolutions&&l.resolutions.length>0)for(let h of l.resolutions){let f=(a=h.finalScope)!=null?a:h.inferredScope,J=f?` [${f.breadth} ${f.target}]`:"";e.push(`- ${h.annotationId}: ${h.status}${J} \u2014 ${h.summary}`),h.filesModified&&h.filesModified.length>0&&e.push(` Files: ${h.filesModified.join(", ")}`)}l.toolsUsed&&l.toolsUsed.length>0&&e.push(`Tools used: ${l.toolsUsed.join(", ")}`)}e.push(""),e.push("The current round is shown in full below.")}if(t!=null&&t.designModel){e.push(""),e.push("## Established Design Policies"),e.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 i=t.designModel.rules;if(Array.isArray(i)&&i.length>0){e.push(""),e.push("Rules:");for(let f of i)typeof f=="string"&&e.push(`- ${f}`)}let l=t.designModel.tokens;l&&typeof l=="object"&&(e.push(""),e.push("Design tokens:"),e.push("```json"),e.push(JSON.stringify(l,null,2)),e.push("```"));let h=t.designModel.components;h&&typeof h=="object"&&(e.push(""),e.push("Component patterns:"),e.push("```json"),e.push(JSON.stringify(h,null,2)),e.push("```")),e.push(""),e.push("### Novel Pattern Detection"),e.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:"),e.push("<novel>"),e.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),e.push("</novel>"),e.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),e.push("- `element`: What you are styling or creating"),e.push("- `decision`: What you decided to do (specific values)"),e.push("- `reason`: Why this is novel (what is missing from the model)"),e.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}t!=null&&t.designModel||(e.push(""),e.push("## Design Context"),e.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code."));let o=xe(n,t==null?void 0:t.imagePaths);return o&&(e.push(""),e.push(o)),e.push(""),e.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."),e.push(""),e.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e.push(""),e.push("## Resolution"),e.push("After completing all work, output a resolution block listing what you did for each annotation:"),e.push("<resolution>"),e.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),e.push("</resolution>"),e.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),e.push(""),e.push("### Scope classification"),e.push("Each resolution MUST include scope fields:"),e.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),e.push("- `inferredScope`: What scope the change actually has, based on what you modified."),e.push("Scope has two dimensions:"),e.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),e.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),e.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),e.push("If you cannot confidently determine scope, set it to null."),e.push(""),e.push("## Questions"),e.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),e.push('<question>What do you mean by "..."?</question>'),e.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),e.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),e.join(`
|
|
109
|
+
`)}function It(r){var t;let n=r.match(/<question>\s*([\s\S]*?)\s*<\/question>/);return(t=n==null?void 0:n[1])!=null?t:null}function xt(r,n,t,e){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 a=n.find(i=>i.role==="human"&&i.feedbackContext);if(a!=null&&a.feedbackContext&&(o.push(""),o.push(a.feedbackContext)),n.length>0){o.push(""),o.push("## Conversation History");let i=0;for(let l of n)l.role==="human"?(i++,l.replyToQuestion?(o.push(`### Round ${i} (human) \u2014 reply`),o.push(`"${l.replyToQuestion}"`)):(o.push(`### Round ${i} (human)`),l.feedbackSummary&&o.push(`Annotations: ${l.feedbackSummary}`))):l.question?(o.push(`### Round ${i} (assistant) \u2014 question`),o.push(`"${l.question}"`)):(o.push(`### Round ${i} (assistant)`),l.responseText&&o.push(`Response: ${l.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."),e&&e.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let i of e)o.push(`Attached image: use the Read tool to view the image at: ${i}`)}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(`
|
|
110
|
+
`)}function dn(r){if(typeof r!="object"||r===null)return!1;let n=r;return(n.breadth==="instance"||n.breadth==="pattern")&&(n.target==="element"||n.target==="component"||n.target==="token")}function Pt(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 n=r;for(let t of["declaredScope","inferredScope","finalScope"])if(n[t]!==void 0&&n[t]!==null&&!dn(n[t]))return!1;return!0}function kt(r){let n=r.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!n||!n[1])return[];try{let t=JSON.parse(n[1]);return Array.isArray(t)?t.filter(Pt):[]}catch(t){return[]}}function bt(r){let n=[],t=/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g,e;for(;(e=t.exec(r))!==null;)if(e[1])try{let o=JSON.parse(e[1]);Array.isArray(o)&&n.push(...o.filter(Pt))}catch(o){}return n}function Tt(r){let n=r.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!(n!=null&&n[1]))return[];try{let t=JSON.parse(n[1]);return Array.isArray(t)?t.filter(e=>{if(typeof e!="object"||e===null)return!1;let o=e;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[]}}function Rt(r,n,t,e,o,a){let i=[];return i.push("You are a UI design planner. You are looking at a full-page screenshot of a web application."),i.push(""),i.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),i.push(""),i.push(`Page: ${t}`),i.push(`Viewport: ${e.width}x${e.height}`),o&&(i.push(""),i.push("## Page Elements (ground truth)"),i.push("Below is a structured inventory of actual DOM elements on this page. Cross-reference"),i.push("against this list \u2014 do NOT reference elements that aren't listed here."),i.push(""),i.push("<manifest>"),i.push(o),i.push("</manifest>")),a&&(i.push(""),i.push("## Developer Context"),i.push("The developer has the following annotations and style changes on their canvas. Factor these into your plan:"),i.push(a)),i.push(""),i.push("## Goal"),i.push(n),i.push(""),i.push("## Your Task"),i.push("Analyze the screenshot and decompose the goal into specific, element-level tasks."),i.push("Each task targets a specific region of the page and gives a clear instruction for a worker agent."),i.push(""),i.push("Output your plan as a JSON array inside a <plan> tag. Each task has:"),i.push('- `id`: A short unique identifier (e.g., "t1", "t2")'),i.push("- `instruction`: Clear, specific instruction for a worker agent (what to change and how)"),i.push("- `region`: Bounding box in page coordinates `{x, y, width, height}` \u2014 where (x,y) is top-left corner"),i.push("- `priority`: Optional 1-5 (1=highest). Tasks with no dependency can share a priority level."),i.push(""),i.push("Example:"),i.push("<plan>"),i.push("["),i.push(' {"id":"t1","instruction":"Increase heading font-size to 48px and change font-weight to 700","region":{"x":100,"y":50,"width":600,"height":80},"priority":1},'),i.push(' {"id":"t2","instruction":"Add a subtle box-shadow to the card container","region":{"x":80,"y":200,"width":640,"height":300},"priority":2}'),i.push("]"),i.push("</plan>"),i.push(""),i.push("Guidelines:"),i.push("- CRITICAL: Cross-check all element references against the <manifest>. Only reference elements that actually exist. Use the manifest's text content, component names, and bounding rects for precise instructions."),i.push('- Be specific about values (colors, sizes, spacing) rather than vague ("make it look better")'),i.push("- Each task should be independently actionable by a worker that can only see its region"),i.push("- Regions should tightly bound the relevant UI element(s)"),i.push("- Keep tasks atomic \u2014 one change per task, not multiple unrelated changes"),i.push("- Order by priority: structural changes first, then visual polish"),i.push("- If the goal can be accomplished as a single change, return a plan with just one task. Only decompose when the goal genuinely requires multiple independent changes."),i.push("- If the goal is unclear or you need more context, output a question instead:"),i.push("<question>Your question here</question>"),i.push(""),i.push("Do NOT modify any files. You are a planner only \u2014 output a <plan> or <question>, nothing else."),i.join(`
|
|
111
|
+
`)}function $t(r){let n=r.match(/<plan>\s*([\s\S]*?)\s*<\/plan>/);if(!(n!=null&&n[1]))return null;try{let t=JSON.parse(n[1]);return Array.isArray(t)?t.filter(e=>{if(typeof e!="object"||e===null)return!1;let o=e;if(typeof o.id!="string"||typeof o.instruction!="string"||typeof o.region!="object"||o.region===null)return!1;let a=o.region;return typeof a.x=="number"&&typeof a.y=="number"&&typeof a.width=="number"&&typeof a.height=="number"}):null}catch(t){return null}}function Mt(r,n,t){let e=[];e.push("You are reviewing whether a series of UI changes achieved the original design goal."),e.push(""),e.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),e.push(""),e.push("## Original Goal"),e.push(n),e.push(""),e.push("## Completed Tasks");for(let o of t)e.push(`- [${o.id}] ${o.instruction} \u2192 ${o.summary}`);return e.push(""),e.push("## Your Task"),e.push("Look at the current screenshot and determine if the goal has been achieved."),e.push("Output your verdict inside a <review> tag:"),e.push("<review>"),e.push('{"verdict":"pass","summary":"The changes look good..."}'),e.push("</review>"),e.push(""),e.push("Or if issues remain:"),e.push("<review>"),e.push('{"verdict":"fail","summary":"Some issues remain...","issues":["Issue 1","Issue 2"]}'),e.push("</review>"),e.push(""),e.push("Do NOT modify any files. Output only a <review> block."),e.join(`
|
|
112
|
+
`)}function Ot(r,n,t,e,o){let a=[];a.push("You are implementing a series of UI changes on a web application."),a.push(""),o!=="codex"&&(a.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),a.push("")),a.push(`Page: ${t} (${e.width}x${e.height})`),a.push(""),a.push("## Tasks"),a.push("Each task targets a specific region of the page. Complete them in order."),a.push("");for(let i of n){if(a.push(`### Task ${i.planTaskId} (annotationId: ${i.annotationId})`),a.push(`Instruction: ${i.instruction}`),a.push(`Region: (${i.region.x}, ${i.region.y}) ${i.region.width}x${i.region.height}`),i.linkedSelector&&a.push(`Target element: ${i.linkedSelector}`),i.elements&&i.elements.length>0){let l=i.elements.map(h=>{let f=[h.selector];return h.reactComponent&&f.push(`(${h.reactComponent})`),f.join(" ")}).join(", ");a.push(`Elements: ${l}`)}a.push("")}return a.push("## Instructions"),a.push("- Apply each change to the source files \u2014 the dev server has HMR so changes appear immediately."),a.push("- IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source."),a.push("- You may use parallel subagents (Task tool) for independent changes, or work serially \u2014 use your judgment."),a.push(""),a.push("## Resolution"),a.push("CRITICAL: After completing EACH task, immediately output a <resolution> block for that task."),a.push("Do NOT wait until all tasks are done \u2014 output each resolution as soon as that task is finished."),a.push("<resolution>"),a.push('[{"annotationId":"<annotationId>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),a.push("</resolution>"),a.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),a.push(""),a.push("### Scope classification"),a.push("Each resolution MUST include scope fields:"),a.push("- `declaredScope`: What scope the task instruction implies. null if no signal."),a.push("- `inferredScope`: What scope the change actually has, based on what you modified."),a.push("Scope has two dimensions:"),a.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),a.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),a.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),a.push("If you cannot confidently determine scope, set it to null."),a.join(`
|
|
113
|
+
`)}function Ct(r){let n=r.match(/<review>\s*([\s\S]*?)\s*<\/review>/);if(!(n!=null&&n[1]))return null;try{let t=JSON.parse(n[1]);return typeof t!="object"||t===null||t.verdict!=="pass"&&t.verdict!=="fail"||typeof t.summary!="string"?null:{verdict:t.verdict,summary:t.summary,issues:Array.isArray(t.issues)?t.issues.filter(e=>typeof e=="string"):void 0}}catch(t){return null}}var _e=class{constructor(n=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.maxConcurrency=n}setProcessor(n){this.processor=n}get active(){let n=this.activeJobs.values().next();return n.done?null:n.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(n,t){t?this.activeProcesses.set(n,t):this.activeProcesses.delete(n)}enqueue(n){return this.queue.push(n),this.processNext(),this.queue.length+this.activeJobs.size}addListener(n){return this.listeners.add(n),()=>this.listeners.delete(n)}broadcast(n,t,e){for(let o of this.listeners)o(n,t,e)}cancelJob(n){let t=this.activeProcesses.get(n),e=this.activeJobs.get(n);return!t||!e?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(n),this.activeJobs.delete(n),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,message:"Cancelled by user",cancelled:!0},e.id,e.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let n=Array.from(this.activeJobs.keys());for(let t of n)this.cancelJob(t);return!0}destroy(){for(let n of this.activeProcesses.values())n.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear()}async destroyAsync(n=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 e of t)try{e.kill("SIGTERM")}catch(o){}await Promise.all(t.map(e=>new Promise(o=>{let a=!1,i=()=>{a||(a=!0,o())};e.on("exit",i),e.on("error",i),setTimeout(()=>{if(!a){try{e.kill("SIGKILL")}catch(l){}setTimeout(i,500)}},n)}))),this.activeProcesses.clear(),this.activeJobs.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let n=this.queue.shift();this.activeJobs.set(n.id,n),n.status="running",this.broadcast({type:"job_started",jobId:n.id,position:0},n.id,n.sourceId),this.processor(n).catch(t=>{n.status="error",n.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:n.id,message:n.error},n.id,n.sourceId)}).finally(()=>{this.activeJobs.delete(n.id),this.activeProcesses.delete(n.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},n.id)})}}};import{mkdir as un,readFile as pn,writeFile as hn}from"fs/promises";import{dirname as fn,join as mn}from"path";var gn={version:1,threads:{}},Je=class{constructor(n){this.cache=null;this.writeChain=Promise.resolve();this.filePath=mn(n,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let n=await pn(this.filePath,"utf-8"),t=JSON.parse(n);if(t&&t.version===1&&t.threads)return this.cache=t,this.cache}catch(n){}return this.cache=ce(te({},gn),{threads:{}}),this.cache}async getThread(n){var e;return(e=(await this.load()).threads[n])!=null?e:null}async findContinuationThread(n){if(n.length===0)return null;let t=await this.load(),e=new Set(n);for(let o of Object.values(t.threads))if(o.elementIdentifiers.some(i=>e.has(i)))return o;return null}async createThread(n,t){let e=await this.load(),o={id:n,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return e.threads[n]=o,await this.persist(),o}async appendMessage(n,t){let o=(await this.load()).threads[n];o&&(o.messages.push(t),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(n,t){let o=(await this.load()).threads[n];if(!o)return;let a=new Set(o.elementIdentifiers);for(let i of t)a.has(i)||o.elementIdentifiers.push(i);o.updatedAt=Date.now(),await this.persist()}async getThreadHistory(n,t=6){let e=await this.getThread(n);return!e||e.messages.length===0?[]:e.messages.length<=t?e.messages:[e.messages[0],...e.messages.slice(-(t-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await un(fn(this.filePath),{recursive:!0}),await hn(this.filePath,JSON.stringify(this.cache,null,2))}catch(n){console.error("[ThreadStore] Failed to persist:",n)}}),await this.writeChain}};var Jn={};var $n=1111,Mn=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],On=1800*1e3,Cn=3600*1e3;function Dt(r){if(!r)return!1;try{let n=new URL(r);return n.hostname==="localhost"||n.hostname==="127.0.0.1"}catch(n){return!1}}function En(r,n){let t=r.headers.origin;Dt(t)&&(n.setHeader("Access-Control-Allow-Origin",t),n.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),n.setHeader("Access-Control-Allow-Headers","Content-Type"))}function m(r,n,t){r.writeHead(n,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}function An(r,n){if(!r)return n;let t=r.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return n;let[,e,o,a]=t;return`\x1B[38;2;${parseInt(e,16)};${parseInt(o,16)};${parseInt(a,16)}m${n}\x1B[0m`}function Et(r,n){try{r.res.write(`event: ${n.type}
|
|
114
114
|
data: ${JSON.stringify(n)}
|
|
115
115
|
|
|
116
|
-
`)}catch(t){}}async function
|
|
116
|
+
`)}catch(t){}}async function Dn(r){try{let n=new AbortController,t=setTimeout(()=>n.abort(),500),e=await fetch(`http://127.0.0.1:${r}/status`,{signal:n.signal});return clearTimeout(t),e.ok?await e.json():null}catch(n){return null}}function _n(r,n){return new Promise((t,e)=>{let o=i=>{r.removeListener("listening",a),e(i)},a=()=>{r.removeListener("error",o),t()};r.once("error",o),r.once("listening",a),r.listen(n,"127.0.0.1")})}async function _t(r={}){var Qe,qe,Ke,Xe,Ve,Ze,et,tt,nt;let n=(Qe=r.port)!=null?Qe:$n,t=(qe=r.projectRoot)!=null?qe:process.cwd(),e=wn("sha256").update(t).digest("hex").slice(0,12),o=(Ke=r.devOrigin)!=null?Ke:process.env.PORT?`http://localhost:${process.env.PORT}`:null,a=(Xe=r.tempDir)!=null?Xe:oe(bn(),"popmelt-bridge"),i=(Ve=r.maxTurns)!=null?Ve:40,l=(Ze=r.maxBudgetUsd)!=null?Ze:1,h=(et=r.allowedTools)!=null?et:Mn,f=(tt=r.claudePath)!=null?tt:"claude",J=(nt=r.provider)!=null?nt:"claude",A=r.timeoutMs,O=n,g={};for(let s of["claude","codex"])try{let c=yn("which",[s],{encoding:"utf-8"}).trim();g[s]={available:!0,path:c}}catch(c){g[s]={available:!1,path:null}}let[H,W]=await Promise.all([He(t),Ge(t)]);g.claude&&(g.claude.mcp=H),g.codex&&(g.codex.mcp=W),await vn(a,{recursive:!0}),At(a).catch(()=>{});let v=new _e(1),L=new Set,C=new Je(t),V=new Ee(t),E=new Ae(t,V,{claudePath:f,onEvent:s=>{for(let c of L)Et(c,s)}}),X=new Map,U=20,ne=300*1e3,P=[],x=null,G;v.addListener((s,c,u)=>{for(let d of L)(!u||!d.sourceId||d.sourceId===u)&&Et(d,s)}),v.setProcessor(async s=>{var Z,re,_,se,le,Se,ue;let c=s._replyPrompt,u=s._replyImagePaths,d=(Z=s.provider)!=null?Z:J,p;if(s.threadId){let $=await C.getThread(s.threadId);if($){for(let y=$.messages.length-1;y>=0;y--)if($.messages[y].sessionId){p=$.messages[y].sessionId;break}}}let S;if(p&&c){let $=(re=await C.getThread(s.threadId))==null?void 0:re.messages.filter(M=>M.role==="human").pop();if(S=($==null?void 0:$.replyToQuestion)||($==null?void 0:$.feedbackSummary)||"",u&&u.length>0){S+=`
|
|
117
117
|
|
|
118
|
-
The developer attached reference images with their reply:`;for(let M of u)
|
|
119
|
-
Attached image: use the Read tool to view the image at: ${M}`}
|
|
118
|
+
The developer attached reference images with their reply:`;for(let M of u)S+=`
|
|
119
|
+
Attached image: use the Read tool to view the image at: ${M}`}S+=`
|
|
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(p)S=xe(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
125
|
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
|
|
126
126
|
|
|
127
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${s.screenshotPath}`:"");else{let $=!c&&s.threadId?await
|
|
127
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${s.screenshotPath}`:"");else{let $=!c&&s.threadId?await C.getThreadHistory(s.threadId):void 0,y=c?null:await E.loadModel();S=c!=null?c:St(s.screenshotPath,s.feedback,{threadHistory:$&&$.length>0?$:void 0,provider:d,imagePaths:s.imagePaths,designModel:y!=null?y:void 0})}let R=An(s.color,`[\u22B9 ${O}:${s.id}]`);console.log(`${R} Reviewing feedback ${s.screenshotPath} (provider: ${d})${s.threadId?` (thread: ${s.threadId})`:""}${p?` (resuming: ${p.slice(0,8)})`:""}`);let b=!!s._isPlanExecutor,D="",w=0,Y=($,y)=>{if(v.broadcast($,y,s.sourceId),b&&$.type==="delta"&&"text"in $){D+=$.text;let M=bt(D);if(M.length>w){let ee=M.slice(w);w=M.length,v.broadcast({type:"task_resolved",jobId:y,planId:s.planId,resolutions:ee,threadId:s.threadId},y,s.sourceId)}}},z=(_=s._allowedTools)!=null?_:h,{process:N,result:T}=d==="codex"?it(s.id,{prompt:S,projectRoot:t,screenshotPath:s.screenshotPath,resumeSessionId:p,model:s.model,onEvent:Y}):Ce(s.id,{prompt:S,projectRoot:t,maxTurns:i,maxBudgetUsd:l,allowedTools:z,claudePath:f,resumeSessionId:p,model:s.model,timeoutMs:A,onEvent:Y});v.setActiveProcess(s.id,N);let I=await T;if(s.result=I.text,I.success){console.log(`${R} Iteration complete`),I.fileEdits&&I.fileEdits.length>0&&console.log(`${R} Captured ${I.fileEdits.length} file edit(s): ${I.fileEdits.map(F=>`${F.tool} ${F.file_path}`).join(", ")}`),s.status="done";let $=It(I.text),y=kt(I.text);if(y.length>0&&s.annotationIds&&s.annotationIds.length>0){let F=new Set(s.annotationIds);y.every(ae=>F.has(ae.annotationId))||(y=y.map((ae,pe)=>ce(te({},ae),{annotationId:s.annotationIds[pe%s.annotationIds.length]})))}let M=I.fileEdits&&I.fileEdits.length>0?I.fileEdits.map(F=>`${F.tool} ${F.file_path.split("/").pop()}`):void 0;if(s.threadId&&await C.appendMessage(s.threadId,{role:"assistant",timestamp:Date.now(),jobId:s.id,responseText:I.text,resolutions:y.length>0?y:void 0,question:$!=null?$:void 0,sessionId:I.sessionId,toolsUsed:M}),V.captureGitDiff(t).then(async F=>{var st;let Q=Date.now(),ae=s.imagePaths?Object.values(s.imagePaths).flat():[],pe=[];if(s.imagePaths)for(let[Gt,jt]of Object.entries(s.imagePaths))for(let Be=0;Be<jt.length;Be++)pe.push(`screenshots/p-${s.id}-${Gt}-${Be}.png`);await V.persist({version:1,id:s.id,createdAt:s.createdAt,completedAt:Q,durationMs:Q-s.createdAt,url:s.feedback.url,viewport:s.feedback.viewport,screenshotPath:`screenshots/s-${s.id}.png`,pastedImagePaths:pe,annotations:s.feedback.annotations,styleModifications:s.feedback.styleModifications,inspectedElement:s.feedback.inspectedElement,provider:s.provider,model:s.model,sessionId:I.sessionId,threadId:s.threadId,planId:s.planId,planTaskId:s.planTaskId,responseText:I.text,resolutions:y.length>0?y:[],question:$!=null?$:void 0,fileEdits:(st=I.fileEdits)!=null?st:[],toolsUsed:M,gitDiff:F},s.screenshotPath,ae)}).catch(()=>{}),y.length>0&&y.some(Q=>{var pe;let ae=(pe=Q.finalScope)!=null?pe:Q.inferredScope;return(ae==null?void 0:ae.breadth)==="pattern"})&&E.run().catch(()=>{}),s.planId&&!s.planTaskId){let F=X.get(s.planId);if(F){let Q=$t(I.text);Q&&Q.length>0?(F.plan=Q,F.status="awaiting_approval",F.plannerThreadId=s.threadId,console.log(`${R} Plan ready: ${Q.length} tasks for group ${s.planId}`),v.broadcast({type:"plan_ready",jobId:s.id,planId:s.planId,tasks:Q,threadId:s.threadId},s.id,s.sourceId)):$||(F.status="error",console.error(`${R} Failed to parse plan from planner response`))}}if(s.planId&&s._isReview){let F=X.get(s.planId);if(F){let Q=Ct(I.text);Q&&(F.status=Q.verdict==="pass"?"done":"executing",console.log(`${R} Review verdict: ${Q.verdict} \u2014 ${Q.summary}`),v.broadcast({type:"plan_review",planId:s.planId,verdict:Q.verdict,summary:Q.summary,issues:Q.issues},s.id,s.sourceId))}}$&&(console.log(`${R} \u{1F4AC} Question detected: "${$.slice(0,120)}" \u2192 broadcasting to ${L.size} SSE clients (threadId=${(se=s.threadId)!=null?se:s.id}, annotationIds=${(Se=(le=s.annotationIds)==null?void 0:le.join(","))!=null?Se:"none"})`),v.broadcast({type:"question",jobId:s.id,threadId:(ue=s.threadId)!=null?ue:s.id,question:$,annotationIds:s.annotationIds},s.id,s.sourceId));let ee=Tt(I.text);ee.length>0&&(console.log(`${R} Novel pattern(s): ${ee.map(F=>`${F.category}/${F.element}`).join(", ")}`),v.broadcast({type:"novel_patterns",jobId:s.id,patterns:ee,threadId:s.threadId},s.id,s.sourceId)),v.broadcast({type:"done",jobId:s.id,success:!0,resolutions:y.length>0?y:void 0,responseText:I.text,threadId:s.threadId},s.id,s.sourceId),P.push({id:s.id,status:"done",completedAt:Date.now(),threadId:s.threadId})}else console.error(`${R} Error: ${I.error}`),s.status="error",s.error=I.error,v.broadcast({type:"error",jobId:s.id,message:I.error||"Unknown error"},s.id,s.sourceId),P.push({id:s.id,status:"error",completedAt:Date.now(),error:I.error,threadId:s.threadId});let j=Date.now()-ne;for(;P.length>0&&(P[0].completedAt<j||P.length>U);)P.shift()});let k=kn(async(s,c)=>{if(En(s,c),s.method==="OPTIONS"){c.writeHead(204),c.end();return}let d=new URL(s.url||"/",`http://127.0.0.1:${O}`).pathname;try{if(s.method==="POST"&&d==="/send")await K(s,c);else if(s.method==="GET"&&d==="/events")Pe(s,c);else if(s.method==="GET"&&d==="/status")ke(c);else if(s.method==="GET"&&d==="/capabilities")m(c,200,{providers:g});else if(s.method==="POST"&&d==="/mcp/install")await B(s,c);else if(s.method==="POST"&&d==="/reply")await me(s,c);else if(s.method==="POST"&&d==="/cancel")be(s,c);else if(s.method==="POST"&&d==="/materialize")await Te(c);else if(s.method==="POST"&&d==="/plan")await Re(s,c);else if(s.method==="POST"&&d==="/plan/approve")await $e(s,c);else if(s.method==="POST"&&d==="/plan/execute")await Me(s,c);else if(s.method==="POST"&&d==="/plan/review")await q(s,c);else if(s.method==="GET"&&d.startsWith("/plan/"))Ne(d.slice(6),c);else if(s.method==="POST"&&d==="/model/component")await Oe(s,c);else if(s.method==="DELETE"&&d==="/model/component")await Jt(s,c);else if(s.method==="PATCH"&&d==="/model/token")await Nt(s,c);else if(s.method==="DELETE"&&d==="/model/token")await Bt(s,c);else if(s.method==="GET"&&d==="/model"){let p=await E.loadModel();m(c,200,{model:p})}else if(s.method==="GET"&&d.startsWith("/thread/")){let p=d.slice(8);await zt(p,c)}else s.method==="GET"&&(d==="/canvas"||d==="/canvas/")?Ut(s,c):s.method==="GET"&&d==="/canvas/manifest"?await Ft(c):s.method==="GET"&&d==="/canvas/app.mjs"?await Lt(c):m(c,404,{error:"Not found"})}catch(p){console.error("[Bridge] Request error:",p),m(c,500,{error:p instanceof Error?p.message:"Internal error"})}});async function K(s,c){let{screenshot:u,feedback:d,color:p,provider:S,model:R,sourceId:b,pastedImages:D}=await we(s),w;try{w=JSON.parse(d)}catch(_){m(c,400,{error:"Invalid feedback JSON"});return}let Y=fe().slice(0,8),z=oe(a,`screenshot-${Y}.png`);await ve(z,u);let N={};if(D.length>0)for(let _ of D){let se=oe(a,`pasted-${Y}-${_.annotationId}-${_.index}.png`);await ve(se,_.data),N[_.annotationId]||(N[_.annotationId]=[]),N[_.annotationId].push(se)}let T=w.annotations.map(_=>_.linkedSelector).filter(_=>!!_),I;if(T.length>0){let _=await C.findContinuationThread(T);_?(I=_.id,await C.addElementIdentifiers(I,T)):I=(await C.createThread(Y,T)).id}let j=w.annotations.map(_=>_.id),Z=ce(te({id:Y,status:"queued",screenshotPath:z,feedback:w,createdAt:Date.now(),color:p,threadId:I,annotationIds:j,provider:S==="claude"||S==="codex"?S:void 0,model:R||void 0},Object.keys(N).length>0?{imagePaths:N}:{}),{sourceId:b||void 0});if(I){let _=w.annotations.map(le=>le.instruction||`[${le.type}]`).join("; "),se=xe(w,Object.keys(N).length>0?N:void 0);await C.appendMessage(I,{role:"human",timestamp:Date.now(),jobId:Y,screenshotPath:z,annotationIds:j,feedbackSummary:_,feedbackContext:se||void 0})}let re=v.enqueue(Z);m(c,200,{jobId:Y,position:re,threadId:I})}async function me(s,c){let u=s.headers["content-type"]||"",d,p,S,R,b,D,w=[];if(u.includes("multipart/form-data")){let y=await we(s),M=y.feedback?JSON.parse(y.feedback):{};d=M.threadId,p=M.reply,S=M.color,R=M.provider,b=M.model,D=M.sourceId||y.sourceId;for(let ee of y.pastedImages)w.push(ee.data)}else{let y=[];try{for(var le=de(s),Se,ue,$;Se=!(ue=await le.next()).done;Se=!1){let F=ue.value;y.push(typeof F=="string"?Buffer.from(F):F)}}catch(ue){$=[ue]}finally{try{Se&&(ue=le.return)&&await ue.call(le)}finally{if($)throw $[0]}}let M=Buffer.concat(y).toString("utf-8"),ee;try{ee=JSON.parse(M)}catch(F){m(c,400,{error:"Invalid JSON"});return}d=ee.threadId,p=ee.reply,S=ee.color,R=ee.provider,b=ee.model,D=ee.sourceId}if(!d||!p){m(c,400,{error:"Missing threadId or reply"});return}if(!await C.getThread(d)){m(c,404,{error:"Thread not found"});return}let z=fe().slice(0,8),N=[];for(let y=0;y<w.length;y++){let M=oe(a,`reply-${z}-${y}.png`);await ve(M,w[y]),N.push(M)}let T="";{let y=await C.getThreadHistory(d);for(let M=y.length-1;M>=0;M--)if(y[M].screenshotPath){T=y[M].screenshotPath;break}}if(!T){m(c,400,{error:"No screenshot available"});return}await C.appendMessage(d,{role:"human",timestamp:Date.now(),jobId:z,replyToQuestion:p,screenshotPath:T});let I=await C.getThreadHistory(d),j=[];for(let y of I)if(y.annotationIds)for(let M of y.annotationIds)j.includes(M)||j.push(M);let Z=R==="claude"||R==="codex"?R:void 0,re=xt(T,I,Z,N.length>0?N:void 0),_={id:z,status:"queued",screenshotPath:T,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:S,threadId:d,annotationIds:j.length>0?j:void 0,provider:Z,model:b||void 0,sourceId:D||void 0};_._replyPrompt=re,N.length>0&&(_._replyImagePaths=N);let se=v.enqueue(_);m(c,200,{jobId:z,position:se,threadId:d})}function Pe(s,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
|
|
128
128
|
data: {"status":"connected"}
|
|
129
129
|
|
|
130
|
-
`);let d=new URL(s.url||"/",`http://127.0.0.1:${
|
|
131
|
-
Page: ${z}`});let Se=
|
|
130
|
+
`),!o&&s.headers.origin&&Dt(s.headers.origin)&&(o=s.headers.origin);let d=new URL(s.url||"/",`http://127.0.0.1:${O}`).searchParams.get("sourceId")||void 0,p={id:fe().slice(0,8),res:c,sourceId:d};L.add(p),s.on("close",()=>{L.delete(p)})}function ke(s){let c=v.allActive;m(s,200,{ok:!0,projectId:e,devOrigin:o,activeJob:c[0]?{id:c[0].id,status:c[0].status}:null,activeJobs:c.map(u=>({id:u.id,status:u.status})),queueDepth:v.depth,recentJobs:P})}function be(s,c){let d=new URL(s.url||"/",`http://127.0.0.1:${O}`).searchParams.get("jobId"),p=d?v.cancelJob(d):v.cancelActive();m(c,200,{cancelled:p})}async function Te(s){if(E.isRunning){m(s,200,{skipped:!0,reason:"Already running"});return}let c=await E.getUnmaterializedPatternDecisions();if(c.length===0){m(s,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}E.run().catch(()=>{}),m(s,200,{started:!0,decisionCount:c.length,decisionIds:c.map(u=>u.id)})}async function Re(s,c){let{screenshot:u,feedback:d,goal:p,pageUrl:S,viewport:R,provider:b,model:D,manifest:w,sourceId:Y}=await we(s);if(!u||!p){m(c,400,{error:"Missing screenshot or goal"});return}let z=S||"",N={width:1440,height:900};try{R&&(N=JSON.parse(R))}catch(y){}let T;if(d)try{let y=JSON.parse(d),M=xe(y);M&&(T=M)}catch(y){}let I=fe().slice(0,8),j=fe().slice(0,8),Z=oe(a,`screenshot-plan-${I}.png`);await ve(Z,u);let _=(await C.createThread(j,[])).id,se={id:I,goal:p,status:"planning",plannerJobId:j,plannerThreadId:_,workerJobIds:[],screenshotPath:Z,pageUrl:z,viewport:N,createdAt:Date.now()};X.set(I,se);let le=Rt(Z,p,z,N,w,T);await C.appendMessage(_,{role:"human",timestamp:Date.now(),jobId:j,screenshotPath:Z,feedbackSummary:`Plan: ${p}`,feedbackContext:`Goal: ${p}
|
|
131
|
+
Page: ${z}`});let Se=b==="claude"||b==="codex"?b:J,ue={id:j,status:"queued",screenshotPath:Z,feedback:{timestamp:new Date().toISOString(),url:z,viewport:N,scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:_,provider:Se,model:D||void 0,planId:I,sourceId:Y||void 0};ue._replyPrompt=le,ue._allowedTools=["Read"];let $=v.enqueue(ue);m(c,200,{planId:I,jobId:j,position:$,threadId:_})}async function $e(s,c){let u=[];try{for(var w=de(s),Y,z,N;Y=!(z=await w.next()).done;Y=!1){let T=z.value;u.push(typeof T=="string"?Buffer.from(T):T)}}catch(z){N=[z]}finally{try{Y&&(z=w.return)&&await z.call(w)}finally{if(N)throw N[0]}}let d=Buffer.concat(u).toString("utf-8"),p;try{p=JSON.parse(d)}catch(T){m(c,400,{error:"Invalid JSON"});return}let{planId:S,approvedTaskIds:R}=p;if(!S){m(c,400,{error:"Missing planId"});return}let b=X.get(S);if(!b){m(c,404,{error:"Plan not found"});return}if(!b.plan){m(c,400,{error:"Plan has no tasks"});return}let D=R?b.plan.filter(T=>R.includes(T.id)):b.plan;b.status="executing",m(c,200,{planId:S,tasks:D,status:"executing"})}async function Me(s,c){let{screenshot:u,planId:d,tasks:p,provider:S,model:R,sourceId:b}=await we(s);if(!d||!p||!u){m(c,400,{error:"Missing planId, tasks, or screenshot"});return}let D=X.get(d);if(!D){m(c,404,{error:"Plan not found"});return}if(D.status!=="executing"){m(c,400,{error:`Plan status is ${D.status}, expected executing`});return}let w;try{w=JSON.parse(p)}catch(re){m(c,400,{error:"Invalid tasks JSON"});return}let Y=fe().slice(0,8),z=oe(a,`screenshot-exec-${d}.png`);await ve(z,u);let N=S==="claude"||S==="codex"?S:J,T=Ot(z,w,D.pageUrl,D.viewport,N),I=w.map(re=>re.annotationId),j={id:Y,status:"queued",screenshotPath:z,feedback:{timestamp:new Date().toISOString(),url:D.pageUrl,viewport:D.viewport,scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),provider:N,model:R||void 0,planId:d,annotationIds:I,sourceId:b||void 0};j._replyPrompt=T,j._isPlanExecutor=!0,D.executorJobId=Y;let Z=v.enqueue(j);m(c,200,{jobId:Y,planId:d,position:Z})}async function q(s,c){let{screenshot:u,planId:d,provider:p,model:S,sourceId:R}=await we(s);if(!d){m(c,400,{error:"Missing planId"});return}let b=X.get(d);if(!b){m(c,404,{error:"Plan not found"});return}b.status="reviewing";let D=fe().slice(0,8),w=b.screenshotPath;u&&(w=oe(a,`screenshot-review-${d}.png`),await ve(w,u));let Y=(b.plan||[]).map(j=>({id:j.id,instruction:j.instruction,summary:"completed"})),z=Mt(w,b.goal,Y),N=p==="claude"||p==="codex"?p:J,T={id:D,status:"queued",screenshotPath:w,feedback:{timestamp:new Date().toISOString(),url:b.pageUrl,viewport:b.viewport,scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),provider:N,model:S||void 0,planId:d,sourceId:R||void 0};T._replyPrompt=z,T._isReview=!0,T._allowedTools=["Read"];let I=v.enqueue(T);m(c,200,{jobId:D,planId:d,position:I})}function Ne(s,c){let u=X.get(s);if(!u){m(c,404,{error:"Plan not found"});return}m(c,200,u)}async function B(s,c){var z,N;let u=[];try{for(var b=de(s),D,w,Y;D=!(w=await b.next()).done;D=!1){let T=w.value;u.push(typeof T=="string"?Buffer.from(T):T)}}catch(w){Y=[w]}finally{try{D&&(w=b.return)&&await w.call(b)}finally{if(Y)throw Y[0]}}let d;if(u.length>0)try{d=JSON.parse(Buffer.concat(u).toString("utf-8")).serverUrl}catch(T){}let p=[];(z=g.claude)!=null&&z.available&&g.claude.mcp&&!g.claude.mcp.found&&p.push(await wt(d)),(N=g.codex)!=null&&N.available&&g.codex.mcp&&!g.codex.mcp.found&&p.push(await vt(d));let[S,R]=await Promise.all([He(t),Ge(t)]);g.claude&&(g.claude.mcp=S),g.codex&&(g.codex.mcp=R),m(c,200,{results:p,capabilities:{providers:g}})}async function Oe(s,c){let u=[];try{for(var S=de(s),R,b,D;R=!(b=await S.next()).done;R=!1){let w=b.value;u.push(typeof w=="string"?Buffer.from(w):w)}}catch(b){D=[b]}finally{try{R&&(b=S.return)&&await b.call(S)}finally{if(D)throw D[0]}}let d;try{d=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch(w){m(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let p=await E.addComponent(d.name);m(c,200,p)}async function Jt(s,c){let u=[];try{for(var S=de(s),R,b,D;R=!(b=await S.next()).done;R=!1){let w=b.value;u.push(typeof w=="string"?Buffer.from(w):w)}}catch(b){D=[b]}finally{try{R&&(b=S.return)&&await b.call(S)}finally{if(D)throw D[0]}}let d;try{d=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch(w){m(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let p=await E.removeComponent(d.name);m(c,200,p)}async function Nt(s,c){let u=[];try{for(var S=de(s),R,b,D;R=!(b=await S.next()).done;R=!1){let w=b.value;u.push(typeof w=="string"?Buffer.from(w):w)}}catch(b){D=[b]}finally{try{R&&(b=S.return)&&await b.call(S)}finally{if(D)throw D[0]}}let d;try{d=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch(w){m(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"||typeof d.value!="string"){m(c,400,{error:"Missing or invalid path/value"});return}let p=await E.updateToken(d.path,d.value);m(c,200,p)}async function Bt(s,c){let u=[];try{for(var S=de(s),R,b,D;R=!(b=await S.next()).done;R=!1){let w=b.value;u.push(typeof w=="string"?Buffer.from(w):w)}}catch(b){D=[b]}finally{try{R&&(b=S.return)&&await b.call(S)}finally{if(D)throw D[0]}}let d;try{d=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch(w){m(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"){m(c,400,{error:"Missing or invalid path"});return}let p=await E.removeToken(d.path);m(c,200,p)}function Ut(s,c){let u=o!=null?o:"http://localhost:3000";if(!o){let p=s.headers.referer||s.headers.origin;if(p)try{let S=new URL(typeof p=="string"?p:p[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(u=S.origin)}catch(S){}}let d=rt(O,u);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(d)}async function Ft(s){let c=Date.now();if(x&&c<x.expires){m(s,200,x.data);return}try{let{scanForComponents:u}=await import("./react-scanner-5NIJ6ZPL.mjs"),{generateRenderFiles:d}=await import("./render-generator-ZNV3RDU7.mjs"),p=await u(t);x={data:p,expires:c+5e3},d(p,t,G).then(S=>{G=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),m(s,200,p)}catch(u){console.error("[Bridge] Scanner error:",u),m(s,500,{error:"Failed to scan components"})}}async function Lt(s){let c=[oe(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),oe(t,"packages","popmelt","dist","canvas.mjs")];try{let u=Rn(Jn.url);c.unshift(oe(Tn(u),"canvas.mjs"))}catch(u){}for(let u of c)try{let d=await Sn(u,"utf-8");s.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),s.end(d);return}catch(d){}console.error("[Bridge] Canvas bundle not found in:",c),m(s,404,{error:"Canvas bundle not found"})}async function zt(s,c){let u=await C.getThread(s);if(!u){m(c,404,{error:"Thread not found"});return}let d=u.messages.map(R=>{var b=R,{screenshotPath:p}=b,S=ot(b,["screenshotPath"]);return S});m(c,200,{id:u.id,createdAt:u.createdAt,messages:d})}let We=9,Ye=!1;for(let s=n;s<n+We;s++)try{await _n(k,s),O=s,Ye=!0,console.log(`[\u22B9 is watching :${O}]`);break}catch(c){if(c.code==="EADDRINUSE"){let u=await Dn(s);if(u&&u.projectId===e)return console.log(`[\u22B9 already watching :${s}]`),{port:s,projectId:e,close:async()=>{}};continue}throw c}if(!Ye)throw new Error(`[Bridge] All ports ${n}\u2013${n+We-1} in use`);let Ht=setInterval(()=>{At(a).catch(()=>{})},On);return{port:O,projectId:e,close:async()=>{clearInterval(Ht),await v.destroyAsync();for(let s of L)try{s.res.end()}catch(c){}return L.clear(),new Promise(s=>{k.close(()=>s())})}}}async function At(r){try{let n=await In(r),t=Date.now();for(let e of n){let o=oe(r,e);try{let a=await xn(o);t-a.mtimeMs>Cn&&await Pn(o)}catch(a){}}}catch(n){}}async function Ns(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.");let n=await _t(r);return process.env.POPMELT_BRIDGE_PORT=String(n.port),n}export{Ns as startPopmelt};
|
package/package.json
CHANGED