@popmelt.com/core 0.5.9 → 0.5.11

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