@popmelt.com/core 0.7.8 → 0.8.0

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.
@@ -1,4 +1,4 @@
1
- import{mkdir as hr,unlink as fr,writeFile as mr}from"fs/promises";import{join as On}from"path";import{execFileSync as it,spawn as Rn}from"child_process";import{createHash as Go,randomUUID as ye}from"crypto";import{mkdir as qo,readFile as Tn,readdir as Qo,realpath as Xo,stat as Yo,unlink as Ko,writeFile as Ne}from"fs/promises";import{createServer as Vo}from"http";import{tmpdir as Zo}from"os";import{basename as ot,dirname as er,join as fe}from"path";import{fileURLToPath as tr}from"url";function Mt(s,e){return`<!DOCTYPE html>
1
+ import{mkdir as br,unlink as xr,writeFile as Pr}from"fs/promises";import{join as Nn}from"path";import{execFileSync as at,spawn as Tn}from"child_process";import{createHash as er,randomUUID as we}from"crypto";import{mkdir as tr,readFile as Cn,readdir as nr,realpath as sr,stat as or,unlink as rr,writeFile as Je}from"fs/promises";import{createServer as ir}from"http";import{tmpdir as ar}from"os";import{basename as rt,dirname as lr,join as me}from"path";import{fileURLToPath as cr}from"url";function Rt(s,e){return`<!DOCTYPE html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8">
@@ -25,12 +25,12 @@ import{mkdir as hr,unlink as fr,writeFile as mr}from"fs/promises";import{join as
25
25
  });
26
26
  </script>
27
27
  </body>
28
- </html>`}import{spawn as ps}from"child_process";import{createInterface as hs}from"readline";var fs=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),Et=1e5;function ms(s){let e=s.input?.file_path||s.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!fs.has(n))return;let t;if(s.name==="Write"&&typeof s.input?.content=="string"?t=s.input.content:s.name==="Edit"&&typeof s.input?.new_string=="string"&&(t=s.input.new_string),!!t)return t.length>Et?t.slice(0,Et)+`
29
- \u2026[truncated]`:t}function Fe(s,e){let{prompt:n,projectRoot:t,maxTurns:o=40,maxBudgetUsd:i=1,allowedTools:a=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:f,model:x,timeoutMs:b=3e5,onEvent:M}=e,O=[];f?O.push("--resume",f,"-p",n):O.push("-p",n),O.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(i)),x&&O.push("--model",x);for(let z of a)O.push("--allowedTools",z);let $=ps(c,O,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),G=new Promise(z=>{let w,B=[],Y=[],L=[],q=!1,D="",K,k,J=!1,P=setTimeout(()=>{J=!0,$.kill("SIGTERM"),setTimeout(()=>{try{$.kill("SIGKILL")}catch{}},5e3)},b),m=hs({input:$.stdout}),W=new Set;m.on("line",g=>{if(g.trim())try{let T=JSON.parse(g);T.session_id&&!w&&(w=T.session_id);let ee=T.type??(T.event?.type?`event.${T.event.type}`:"unknown");if(W.add(ee),T.type==="result"&&T.result&&B.length===0){let R=typeof T.result=="string"?T.result:"";R&&(B.push(R),M?.({type:"delta",jobId:s,text:R},s))}if(T.type==="assistant"&&Array.isArray(T.message?.content)){typeof T.error=="string"&&(K=T.error);for(let R of T.message.content){if(R.type==="text"&&R.text&&(B.push(R.text),M?.({type:"delta",jobId:s,text:R.text},s)),R.type==="tool_use"&&R.name){let ie=R.input?.file_path||R.input?.path||void 0,V=ms(R);if(M?.({type:"tool_use",jobId:s,tool:R.name,...ie?{file:ie}:{},...V?{content:V}:{}},s),R.name==="Edit"&&R.input?.file_path){let ne={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};Y.push(ne),L.push({sequence:L.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:ne.file_path,oldString:typeof ne.old_string=="string"?ne.old_string:void 0,newString:typeof ne.new_string=="string"?ne.new_string:void 0,replaceAll:typeof ne.replace_all=="boolean"?ne.replace_all:void 0})}else R.name==="Write"&&R.input?.file_path&&(Y.push({tool:"Write",file_path:R.input.file_path,content:R.input.content}),L.push({sequence:L.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:R.input.file_path,content:typeof R.input.content=="string"?R.input.content:void 0}))}R.type==="thinking"&&R.thinking&&M?.({type:"thinking",jobId:s,text:R.thinking},s)}}T.type==="result"&&T.is_error===!0&&(q=!0,typeof T.error=="string"&&(K=T.error),typeof T.result=="string"&&(k=T.result)),T.type==="user"&&T.tool_use_result?.file?.filePath&&M?.({type:"tool_use",jobId:s,tool:"Read",file:T.tool_use_result.file.filePath},s)}catch{}});let A=[];$.stderr?.on("data",g=>{A.push(g.toString())}),$.on("close",g=>{if(clearTimeout(P),m.close(),B.length===0&&W.size>0&&console.warn(`[Claude:${s}] No text captured. Event types seen: ${[...W].join(", ")}`),J)q=!0,D=`Timed out after ${Math.round(b/6e4)} minutes`;else if(g!==0&&g!==null){q=!0;let ee=A.join("").trim(),R=B.join("").trim(),ie=B.length===0&&W.size>0?` (no text captured, event types: ${[...W].join(", ")})`:"";D=ee||k||R||`Claude process exited with code ${g}${ie}`}q&&!D&&k&&(D=k);let T=gs(D,K);z({sessionId:w,text:B.join(""),success:!q,error:q?T.message:void 0,errorCode:q?T.code:void 0,recoverableError:q?T.recoverable:void 0,fileEdits:Y.length>0?Y:void 0,editEvents:L.length>0?L:void 0})}),$.on("error",g=>{clearTimeout(P),q=!0,D=g.message,z({sessionId:w,text:B.join(""),success:!1,error:D,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:Y.length>0?Y:void 0,editEvents:L.length>0?L:void 0})})});return{process:$,result:G}}function gs(s,e){let n=s.trim()||"Claude CLI failed",t=`${e??""} ${n}`.toLowerCase();return t.includes("authentication_failed")||t.includes("not logged in")||t.includes("please run /login")||t.includes("api key")?{message:n,code:"claude_auth_required",recoverable:!0}:t.includes("model")&&(t.includes("not found")||t.includes("unknown")||t.includes("unavailable"))?{message:n,code:"claude_model_unavailable",recoverable:!0}:{message:n,code:e||"claude_error",recoverable:!1}}import{spawn as vs,spawnSync as _t}from"child_process";import{readFileSync as ys,statSync as ws}from"fs";import{basename as Ss,extname as bs,isAbsolute as xs,relative as Ot,resolve as Ps}from"path";import{createInterface as ks}from"readline";function Rt(s){let e=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var Tt=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),lt=2e5,Is=1e5,Dt=2e5;function Nt(s){let e=Ss(s).toLowerCase(),n=bs(s).toLowerCase();return Tt.has(n)||Tt.has(e)}function Jt(s,e){let n=xs(e)?e:Ps(s,e),t=Ot(s,n);return t===""||t.startsWith("..")?null:n}function Be(s,e){if(!Nt(e))return;let n=Jt(s,e);if(n)try{let t=ws(n);return t.isFile()?t.size>lt?{exists:!0,truncated:!0}:{exists:!0,content:ys(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Ms(s,e){for(let n of e){let t=s[n];if(typeof t=="string")return t}}function Es(s){let e=s?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function Ct(s){return Ms(s,["patch","diff","unifiedDiff","unified_diff"])}function dt(s,e){return s.length<=e?{text:s}:{text:s.slice(0,e),truncated:!0}}function At(s,e){let n=_t("git",e,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:Dt+65536});return n.status!==0?null:n.stdout??""}function Rs(s){let e=new Set;for(let n of s.split(`
30
- `)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let o=t.split(" -> ");for(let i of o)i&&e.add(i)}return[...e]}function $t(s){let e=At(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=At(s,["diff","--no-ext-diff","HEAD","--"])??"",t=dt(n,Dt);return{status:e,changedFiles:Rs(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Ts(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function Cs(s,e){if(!Nt(e))return;let n=Jt(s,e);if(!n)return;let t=Ot(s,n);if(t===""||t.startsWith(".."))return;let o=_t("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:lt+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",a=dt(i,lt);return{exists:!0,content:a.text,...a.truncated?{truncated:!0}:{}}}function As(s,e,n){return e.map(t=>{let o=n.has(t)?n.get(t):Cs(s,t),i=Be(s,t);return{filePath:t,...o?{before:o}:{},...i?{after:i}:{}}})}function Ue(s,e){let{prompt:n,projectRoot:t,screenshotPath:o,resumeSessionId:i,model:a,onEvent:c,sandboxMode:f="workspace-write",configOverrides:x=[]}=e,b=[];if(i){b.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${f}"`);for(let $ of x)b.push("-c",$);a&&b.push("-m",a),b.push(i),b.push(n),o&&b.push("--image",o)}else{b.push("exec","--skip-git-repo-check","--json","--sandbox",f);for(let $ of x)b.push("-c",$);a&&b.push("-m",a),b.push(n),o&&b.push("--image",o)}let M=vs("codex",b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),O=new Promise($=>{let G,z=[],w=[],B=[],Y=new Map,L=new Map,q=!1,D="",K=ks({input:M.stdout}),k=new Set;K.on("line",P=>{if(P.trim())try{let m=JSON.parse(P),W=m.type??"unknown";if(k.add(W),W==="thread.started"&&m.thread_id&&!G&&(G=m.thread_id),(W==="item.agentMessage.delta"||W==="item/agentMessage/delta")&&m.delta?.text&&(z.push(m.delta.text),c?.({type:"delta",jobId:s,text:m.delta.text},s)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&m.delta?.text&&c?.({type:"thinking",jobId:s,text:m.delta.text},s),(W==="item.started"||W==="item/started")&&m.item){let A=m.item.type;if(A==="command_execution"){let g=m.item.command,T=g?Rt(g):void 0,ee=$t(t),R=new Map;for(let V of ee?.changedFiles??[])R.set(V,Be(t,V));typeof m.item.id=="string"&&L.set(m.item.id,{...g?{rawCommand:g}:{},...T?{command:T}:{},...ee?{beforeWorktree:ee}:{},beforeSnapshots:R});let ie=T?`Bash: ${T.split(`
31
- `)[0].slice(0,80)}`:"Bash";w.push(ie),c?.({type:"tool_use",jobId:s,tool:"Bash",...T?{content:T}:{}},s)}else if(A==="file_change"){let g=m.item.filename||m.item.path;g&&!Y.has(g)&&Y.set(g,Be(t,g)),w.push(g?`Edit ${g.split("/").pop()}`:"Edit"),c?.({type:"tool_use",jobId:s,tool:"Edit",...g?{file:g}:{}},s)}else if(A==="file_read"){let g=m.item.filename||m.item.path;w.push(g?`Read ${g.split("/").pop()}`:"Read"),c?.({type:"tool_use",jobId:s,tool:"Read",...g?{file:g}:{}},s)}else if(A==="web_search")w.push("WebSearch"),c?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if(A==="mcp_tool_call"){let g=m.item.tool_name||m.item.name||"MCP";w.push(g),c?.({type:"tool_use",jobId:s,tool:g},s)}}if((W==="item.completed"||W==="item/completed")&&m.item){if(m.item.type==="agent_message"){let A=m.item.text;typeof A=="string"&&A&&(z.push(A),c?.({type:"delta",jobId:s,text:A},s))}else if(m.item.type==="reasoning"){let A=m.item.text;typeof A=="string"&&A&&c?.({type:"thinking",jobId:s,text:A},s)}else if(m.item.type==="file_change"&&Array.isArray(m.item.changes))for(let A of m.item.changes){let g=A.path||A.filename,T=A.kind==="add"?"Write":"Edit";if(g){w.push(`${T} ${g.split("/").pop()}`),c?.({type:"tool_use",jobId:s,tool:T,file:g},s);let ee=A,R=typeof ee.kind=="string"?ee.kind:void 0,ie=Es(R),V=Y.get(g),ne=Be(t,g);B.push({sequence:B.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:ie,filePath:g,...V?{before:V}:{},...ne?{after:ne}:{},...Ct(ee)?{patch:Ct(ee)}:{},...R?{rawKind:R}:{}}),Y.set(g,ne)}}else if(m.item.type==="command_execution"){let A=typeof m.item.id=="string"?m.item.id:void 0,g=A?L.get(A):void 0,T=typeof m.item.command=="string"?m.item.command:g?.rawCommand,ee=T?Rt(T):g?.command,R=$t(t);if(Ts(g?.beforeWorktree,R)){let ie=[...new Set([...g?.beforeWorktree?.changedFiles??[],...R?.changedFiles??[]])],V=typeof m.item.aggregated_output=="string"?dt(m.item.aggregated_output,Is):void 0,ne=typeof m.item.exit_code=="number"?m.item.exit_code:m.item.exit_code===null?null:void 0,Pe=typeof m.item.status=="string"?m.item.status:void 0;B.push({sequence:B.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...T?{rawCommand:T}:{},...ee?{command:ee}:{},...ne!==void 0?{exitCode:ne}:{},...Pe?{status:Pe}:{},...V?{output:V.text}:{},...V?.truncated?{outputTruncated:!0}:{},...g?.beforeWorktree?{beforeWorktree:g.beforeWorktree}:{},...R?{afterWorktree:R}:{},...ie.length>0?{touchedFiles:As(t,ie,g?.beforeSnapshots??new Map)}:{}})}A&&L.delete(A)}}W==="turn.failed"&&(q=!0,D=m.error?.message||m.message||"Turn failed")}catch{}});let J=[];M.stderr?.on("data",P=>{J.push(P.toString())}),M.on("close",P=>{K.close(),z.length===0&&k.size>0&&console.warn(`[Codex:${s}] No text captured. Event types seen: ${[...k].join(", ")}`),P!==0&&P!==null&&(q=!0,D=J.join("")||`Codex process exited with code ${P}`),$({sessionId:G,text:z.join(""),success:!q,error:q?D:void 0,editEvents:B.length>0?B:void 0,toolsUsed:w.length>0?w:void 0})}),M.on("error",P=>{q=!0,D=P.message,$({sessionId:G,text:z.join(""),success:!1,error:D,editEvents:B.length>0?B:void 0,toolsUsed:w.length>0?w:void 0})})});return{process:M,result:O}}import{spawn as $s}from"child_process";import{createInterface as _s}from"readline";function zt(s,e){let n=s.trim()||"Copilot CLI failed",t=n.toLowerCase();return t.includes("no authentication information")||t.includes("not authenticated")||t.includes("/login")?{code:"copilot_auth_required",recoverable:!0,message:"Copilot is not authenticated. Run `copilot login`, set `COPILOT_GITHUB_TOKEN`, or refresh `gh auth login`."}:t.includes("model")&&(t.includes("not available")||t.includes("not found")||t.includes("disabled")||t.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:n}:t.includes("mcp")&&(t.includes("blocked")||t.includes("allowlist"))?{code:"copilot_mcp_blocked",recoverable:!0,message:"Copilot blocked the Popmelt MCP server. Ask your administrator to add it to the enterprise allowlist."}:t.includes("permission")||t.includes("denied")||t.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:n}:{code:"copilot_error",recoverable:!1,message:n}}function jt(s,e){let{prompt:n,projectRoot:t,resumeSessionId:o,model:i,timeoutMs:a=3e5,onEvent:c,copilotPath:f="copilot"}=e,x=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];o&&x.push(`--resume=${o}`),i&&x.push("--model",i),x.push("-p",n);let b=$s(f,x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),M=new Promise(O=>{let $,G=[],z=[],w=!1,B="",Y=!1,L=setTimeout(()=>{Y=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},a),q=_s({input:b.stdout}),D=new Set,K=[];q.on("line",J=>{if(J.trim())try{let P=JSON.parse(J),m=Ie(P);D.add(m),K.length<5&&Ds(m)&&K.push(J.slice(0,800));let W=ke(P,["sessionId","session_id","id"],["session","conversation","thread"]);W&&!$&&($=W);let A=Os(P,G.length===0);A&&(G.push(A),c?.({type:"delta",jobId:s,text:A},s));let g=Ns(P);g&&c?.({type:"thinking",jobId:s,text:g},s);let T=Js(P);T&&(z.push(T.label),c?.({type:"tool_use",jobId:s,tool:T.tool,...T.file?{file:T.file}:{},...T.content?{content:T.content}:{}},s));let ee=zs(P);ee&&(w=!0,B=ee)}catch{}});let k=[];b.stderr?.on("data",J=>{k.push(J.toString())}),b.on("close",J=>{clearTimeout(L),q.close(),G.length===0&&D.size>0&&(console.warn(`[Copilot:${s}] No text captured. Event types seen: ${[...D].join(", ")}`),K.length>0&&console.warn(`[Copilot:${s}] Sample text-bearing candidates: ${K.join(`
32
- `)}`)),Y?(w=!0,B=`Timed out after ${Math.round(a/6e4)} minutes`):J!==0&&J!==null&&(w=!0,B=k.join("").trim()||B||`Copilot process exited with code ${J}`);let P=w?zt(B,i):null;O({sessionId:$,text:G.join(""),success:!w,error:P?.message,errorCode:P?.code,recoverableError:P?.recoverable,provider:"copilot",toolsUsed:z.length>0?z:void 0})}),b.on("error",J=>{clearTimeout(L);let P=zt(J.message,i);O({sessionId:$,text:G.join(""),success:!1,error:P.message,errorCode:P.code,recoverableError:P.recoverable,provider:"copilot",toolsUsed:z.length>0?z:void 0})})});return{process:b,result:M}}function Ie(s){if(typeof s.type=="string")return s.type;let e=s.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof s.event=="string"?s.event:"unknown"}function Os(s,e=!1){let n=Ie(s).toLowerCase(),t=s.update,o=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&o?.type==="text"&&typeof o.text=="string")return o.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return pe(s.delta)??pe(s.content)??pe(s.message);if(n==="assistant.message"&&e)return pe(s.message)??pe(s.content)??pe(s);if(n==="result"&&e)return pe(s.result)??pe(s.output)??pe(s.message)??pe(s);let i=s.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof s.text=="string"&&ut(s))return s.text;if(typeof s.message=="string"&&ut(s))return s.message;if(typeof s.delta=="string"&&ut(s))return s.delta}function pe(s){if(typeof s=="string")return s;if(!s)return;if(Array.isArray(s)){let n=s.map(pe).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof s!="object")return;let e=s;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=pe(e[n]);if(t)return t}}function Ds(s){let e=s.toLowerCase();return e.includes("assistant.message")||e==="result"}function Ns(s){if(typeof s.thinking=="string")return s.thinking;if(typeof s.reasoning=="string")return s.reasoning;let e=s.update;if(e?.sessionUpdate==="reasoning_chunk"){let n=e.content;if(typeof n?.text=="string")return n.text}}function Js(s){let e=ke(s,["tool","toolName","tool_name","name"]),n=ke(s,["command","cmd"]),t=ke(s,["file","path","filename","filePath"]),o=Ie(s);if(n||o.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
33
- `)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let i=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function zs(s){if(typeof s.error=="string")return s.error;if(s.error&&typeof s.error=="object"){let e=s.error;if(typeof e.message=="string")return e.message}if(typeof s.message=="string"&&Ie(s).toLowerCase().includes("error"))return s.message}function ke(s,e,n=[]){for(let t of e){let o=s[t];if(typeof o=="string")return o}for(let[t,o]of Object.entries(s)){if(!o||typeof o!="object"||n.length>0&&!n.some(a=>t.toLowerCase().includes(a)))continue;let i=ke(o,e);if(i)return i}}function ut(s){let e=Ie(s).toLowerCase();return(typeof s.role=="string"?s.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{execFile as js}from"child_process";import{copyFile as Ft,mkdir as Bt,readdir as Fs,readFile as Bs,writeFile as Us}from"fs/promises";import{join as we}from"path";var Le=class{constructor(e){this.projectRoot=e;let n=we(e,".popmelt");this.decisionsDir=we(n,"decisions"),this.screenshotsDir=we(n,"screenshots")}async persist(e,n,t){try{await Bt(this.decisionsDir,{recursive:!0}),await Bt(this.screenshotsDir,{recursive:!0});try{await Ft(n,we(this.screenshotsDir,`s-${e.id}.webp`))}catch{}for(let o=0;o<t.length;o++)try{let i=e.pastedImagePaths[o];i&&await Ft(t[o],we(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await Us(we(this.decisionsDir,`d-${e.id}.json`),JSON.stringify(e,null,2))}catch(o){console.error("[DecisionStore] Failed to persist decision record:",o)}}async listDecisionIds(){try{return(await Fs(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await Bs(we(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}captureGitDiff(e){return new Promise(n=>{js("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(t,o)=>{if(t){n(null);return}n(o||null)})})}};import{mkdir as Me,readFile as Ut,writeFile as Ee}from"fs/promises";import{join as Re}from"path";var Ls=80,Ws=24,Lt=1e3,We=class{constructor(e){this.evalsDir=Re(e,".popmelt","evals"),this.suitePath=Re(this.evalsDir,"evals.json"),this.runsPath=Re(this.evalsDir,"runs.json"),this.screenshotsDir=Re(this.evalsDir,"screenshots")}async loadSuite(){try{let e=await Ut(this.suitePath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.cases))return n}catch{}return{version:1,updatedAt:0,cases:[]}}async loadRuns(){try{let e=await Ut(this.runsPath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.runs))return n}catch{}return{version:1,updatedAt:0,runs:[]}}async loadSuiteWithRuns(){let[e,n]=await Promise.all([this.loadSuite(),this.loadRuns()]);return{...e,runs:n.runs}}async loadSuiteWithCurrentRuns(e){let n=await this.loadSuiteWithRuns();return e?{...n,runs:n.runs.filter(t=>t.codeFingerprint===e)}:n}async writeSynthesized(e){let n=await this.loadSuite(),t=new Map(n.cases.map(a=>[a.id,a])),o=new Set;for(let a of e){let c=t.get(a.id);c&&(c.title!==a.title||c.prompt!==a.prompt||JSON.stringify(c.assertions)!==JSON.stringify(a.assertions))&&o.add(a.id),t.set(a.id,a)}let i={version:1,updatedAt:Date.now(),cases:[...t.values()]};return await Me(this.evalsDir,{recursive:!0}),await Ee(this.suitePath,JSON.stringify(i,null,2)),o.size>0&&await this.invalidateRunsForEvals(o),i}async updateCase(e,n){let t=await this.loadSuite(),o=n.title!==void 0||n.assertions!==void 0,i=t.cases.map(c=>c.id===e?{...c,...n.status?{status:n.status}:{},...n.title?{title:n.title}:{},...n.assertions?{assertions:n.assertions}:{}}:c),a=i.find(c=>c.id===e)??null;return a?(await Me(this.evalsDir,{recursive:!0}),await Ee(this.suitePath,JSON.stringify({version:1,updatedAt:Date.now(),cases:i},null,2)),o&&await this.invalidateRunsForEvals(new Set([e])),a):null}async invalidateRunsForEvals(e){let t=(await this.loadRuns()).runs.filter(i=>!e.has(i.evalId)),o={version:1,updatedAt:Date.now(),runs:t};return await Me(this.evalsDir,{recursive:!0}),await Ee(this.runsPath,JSON.stringify(o,null,2)),o}async writeRun(e){let n=await this.loadRuns(),t=[e,...n.runs.filter(i=>i.id!==e.id)].slice(0,200),o={version:1,updatedAt:Date.now(),runs:t};return await Me(this.evalsDir,{recursive:!0}),await Ee(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(e,n){return await Me(this.screenshotsDir,{recursive:!0}),await Ee(Re(this.screenshotsDir,`eval-${e}.webp`),n),`evals/screenshots/eval-${e}.webp`}async findCase(e){return(await this.loadSuite()).cases.find(t=>t.id===e)??null}};function Wt(s){let e=s.match(/<evals>\s*([\s\S]*?)\s*<\/evals>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return t?qt(t):null}catch{return null}}function Ht(s){let e=s.match(/<eval_proposals>\s*([\s\S]*?)\s*<\/eval_proposals>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return t?qt(t,"pending"):null}catch{return null}}function Gt(s,e){let n=s.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let t=JSON.parse(n[1]),o=Ys(t.assertionResults,e),i=Ks(o);return{status:i,summary:he(t.summary)||Kt(i),assertionResults:o,tooling:Vs(t.tooling)}}catch{}return{status:"needs_review",summary:He(s.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:e.map(t=>({assertion:t,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function qt(s,e="approved"){let n=[];return s.forEach((t,o)=>{if(!t||typeof t!="object")return;let i=t,a=he(i.title),c=he(i.prompt),f=he(i.rationale),x=be(i.assertions);if(!a||!c||x.length===0)return;let b=qs(i.category),M=Zs(he(i.id))||`eval-${Vt(a).slice(0,32)||o+1}`,O=Qs(i.status)??e;n.push({id:M,title:a,status:O,category:b,prompt:c,assertions:x,rationale:f||"Inferred from Popmelt design history.",sourceDecisionIds:be(i.sourceDecisionIds),sourceThreadIds:be(i.sourceThreadIds)})}),n}function Qt(s){let e=[...s.decisions].sort((t,o)=>o.createdAt-t.createdAt).slice(0,Ls),n=Object.values(s.threads.threads).sort((t,o)=>o.updatedAt-t.updatedAt).slice(0,Ws);return`You are helping a designer turn organic Popmelt annotation history into a project eval suite.
28
+ </html>`}import{spawn as ms}from"child_process";import{createInterface as gs}from"readline";var ys=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),Et=1e5;function vs(s){let e=s.input?.file_path||s.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!ys.has(n))return;let t;if(s.name==="Write"&&typeof s.input?.content=="string"?t=s.input.content:s.name==="Edit"&&typeof s.input?.new_string=="string"&&(t=s.input.new_string),!!t)return t.length>Et?t.slice(0,Et)+`
29
+ \u2026[truncated]`:t}function Fe(s,e){let{prompt:n,projectRoot:t,maxTurns:o=40,maxBudgetUsd:i=1,allowedTools:a=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:l="claude",resumeSessionId:f,model:k,timeoutMs:b=3e5,onEvent:R}=e,O=[];f?O.push("--resume",f,"-p",n):O.push("-p",n),O.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(i)),k&&O.push("--model",k);for(let j of a)O.push("--allowedTools",j);let $=ms(l,O,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),q=new Promise(j=>{let S,F=[],K=[],L=[],X=!1,D="",Z,P,N=!1,I=setTimeout(()=>{N=!0,$.kill("SIGTERM"),setTimeout(()=>{try{$.kill("SIGKILL")}catch{}},5e3)},b),m=gs({input:$.stdout}),H=new Set;m.on("line",v=>{if(v.trim())try{let C=JSON.parse(v);C.session_id&&!S&&(S=C.session_id);let ne=C.type??(C.event?.type?`event.${C.event.type}`:"unknown");if(H.add(ne),C.type==="result"&&C.result&&F.length===0){let T=typeof C.result=="string"?C.result:"";T&&(F.push(T),R?.({type:"delta",jobId:s,text:T},s))}if(C.type==="assistant"&&Array.isArray(C.message?.content)){typeof C.error=="string"&&(Z=C.error);for(let T of C.message.content){if(T.type==="text"&&T.text&&(F.push(T.text),R?.({type:"delta",jobId:s,text:T.text},s)),T.type==="tool_use"&&T.name){let ae=T.input?.file_path||T.input?.path||void 0,ee=vs(T);if(R?.({type:"tool_use",jobId:s,tool:T.name,...ae?{file:ae}:{},...ee?{content:ee}:{}},s),T.name==="Edit"&&T.input?.file_path){let oe={tool:"Edit",file_path:T.input.file_path,old_string:T.input.old_string,new_string:T.input.new_string,replace_all:T.input.replace_all};K.push(oe),L.push({sequence:L.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:oe.file_path,oldString:typeof oe.old_string=="string"?oe.old_string:void 0,newString:typeof oe.new_string=="string"?oe.new_string:void 0,replaceAll:typeof oe.replace_all=="boolean"?oe.replace_all:void 0})}else T.name==="Write"&&T.input?.file_path&&(K.push({tool:"Write",file_path:T.input.file_path,content:T.input.content}),L.push({sequence:L.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:T.input.file_path,content:typeof T.input.content=="string"?T.input.content:void 0}))}T.type==="thinking"&&T.thinking&&R?.({type:"thinking",jobId:s,text:T.thinking},s)}}C.type==="result"&&C.is_error===!0&&(X=!0,typeof C.error=="string"&&(Z=C.error),typeof C.result=="string"&&(P=C.result)),C.type==="user"&&C.tool_use_result?.file?.filePath&&R?.({type:"tool_use",jobId:s,tool:"Read",file:C.tool_use_result.file.filePath},s)}catch{}});let A=[];$.stderr?.on("data",v=>{A.push(v.toString())}),$.on("close",v=>{if(clearTimeout(I),m.close(),F.length===0&&H.size>0&&console.warn(`[Claude:${s}] No text captured. Event types seen: ${[...H].join(", ")}`),N)X=!0,D=`Timed out after ${Math.round(b/6e4)} minutes`;else if(v!==0&&v!==null){X=!0;let ne=A.join("").trim(),T=F.join("").trim(),ae=F.length===0&&H.size>0?` (no text captured, event types: ${[...H].join(", ")})`:"";D=ne||P||T||`Claude process exited with code ${v}${ae}`}X&&!D&&P&&(D=P);let C=ws(D,Z);j({sessionId:S,text:F.join(""),success:!X,error:X?C.message:void 0,errorCode:X?C.code:void 0,recoverableError:X?C.recoverable:void 0,fileEdits:K.length>0?K:void 0,editEvents:L.length>0?L:void 0})}),$.on("error",v=>{clearTimeout(I),X=!0,D=v.message,j({sessionId:S,text:F.join(""),success:!1,error:D,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:K.length>0?K:void 0,editEvents:L.length>0?L:void 0})})});return{process:$,result:q}}function ws(s,e){let n=s.trim()||"Claude CLI failed",t=`${e??""} ${n}`.toLowerCase();return t.includes("authentication_failed")||t.includes("not logged in")||t.includes("please run /login")||t.includes("api key")?{message:n,code:"claude_auth_required",recoverable:!0}:t.includes("model")&&(t.includes("not found")||t.includes("unknown")||t.includes("unavailable"))?{message:n,code:"claude_model_unavailable",recoverable:!0}:{message:n,code:e||"claude_error",recoverable:!1}}import{spawn as Ss,spawnSync as Ot}from"child_process";import{readFileSync as bs,statSync as xs}from"fs";import{basename as Ps,extname as ks,isAbsolute as Is,relative as Dt,resolve as Ms}from"path";import{createInterface as Rs}from"readline";function Tt(s){let e=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var Ct=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),ct=2e5,Es=1e5,Nt=2e5;function Jt(s){let e=Ps(s).toLowerCase(),n=ks(s).toLowerCase();return Ct.has(n)||Ct.has(e)}function jt(s,e){let n=Is(e)?e:Ms(s,e),t=Dt(s,n);return t===""||t.startsWith("..")?null:n}function Ue(s,e){if(!Jt(e))return;let n=jt(s,e);if(n)try{let t=xs(n);return t.isFile()?t.size>ct?{exists:!0,truncated:!0}:{exists:!0,content:bs(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Ts(s,e){for(let n of e){let t=s[n];if(typeof t=="string")return t}}function Cs(s){let e=s?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function At(s){return Ts(s,["patch","diff","unifiedDiff","unified_diff"])}function dt(s,e){return s.length<=e?{text:s}:{text:s.slice(0,e),truncated:!0}}function $t(s,e){let n=Ot("git",e,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:Nt+65536});return n.status!==0?null:n.stdout??""}function As(s){let e=new Set;for(let n of s.split(`
30
+ `)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let o=t.split(" -> ");for(let i of o)i&&e.add(i)}return[...e]}function _t(s){let e=$t(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=$t(s,["diff","--no-ext-diff","HEAD","--"])??"",t=dt(n,Nt);return{status:e,changedFiles:As(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function $s(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function _s(s,e){if(!Jt(e))return;let n=jt(s,e);if(!n)return;let t=Dt(s,n);if(t===""||t.startsWith(".."))return;let o=Ot("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:ct+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",a=dt(i,ct);return{exists:!0,content:a.text,...a.truncated?{truncated:!0}:{}}}function Os(s,e,n){return e.map(t=>{let o=n.has(t)?n.get(t):_s(s,t),i=Ue(s,t);return{filePath:t,...o?{before:o}:{},...i?{after:i}:{}}})}function Le(s,e){let{prompt:n,projectRoot:t,screenshotPath:o,resumeSessionId:i,model:a,onEvent:l,sandboxMode:f="workspace-write",configOverrides:k=[]}=e,b=[];if(i){b.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${f}"`);for(let $ of k)b.push("-c",$);a&&b.push("-m",a),b.push(i),b.push(n),o&&b.push("--image",o)}else{b.push("exec","--skip-git-repo-check","--json","--sandbox",f);for(let $ of k)b.push("-c",$);a&&b.push("-m",a),b.push(n),o&&b.push("--image",o)}let R=Ss("codex",b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),O=new Promise($=>{let q,j=[],S=[],F=[],K=new Map,L=new Map,X=!1,D="",Z=Rs({input:R.stdout}),P=new Set;Z.on("line",I=>{if(I.trim())try{let m=JSON.parse(I),H=m.type??"unknown";if(P.add(H),H==="thread.started"&&m.thread_id&&!q&&(q=m.thread_id),(H==="item.agentMessage.delta"||H==="item/agentMessage/delta")&&m.delta?.text&&(j.push(m.delta.text),l?.({type:"delta",jobId:s,text:m.delta.text},s)),(H==="item.reasoning.delta"||H==="item/reasoning/delta")&&m.delta?.text&&l?.({type:"thinking",jobId:s,text:m.delta.text},s),(H==="item.started"||H==="item/started")&&m.item){let A=m.item.type;if(A==="command_execution"){let v=m.item.command,C=v?Tt(v):void 0,ne=_t(t),T=new Map;for(let ee of ne?.changedFiles??[])T.set(ee,Ue(t,ee));typeof m.item.id=="string"&&L.set(m.item.id,{...v?{rawCommand:v}:{},...C?{command:C}:{},...ne?{beforeWorktree:ne}:{},beforeSnapshots:T});let ae=C?`Bash: ${C.split(`
31
+ `)[0].slice(0,80)}`:"Bash";S.push(ae),l?.({type:"tool_use",jobId:s,tool:"Bash",...C?{content:C}:{}},s)}else if(A==="file_change"){let v=m.item.filename||m.item.path;v&&!K.has(v)&&K.set(v,Ue(t,v)),S.push(v?`Edit ${v.split("/").pop()}`:"Edit"),l?.({type:"tool_use",jobId:s,tool:"Edit",...v?{file:v}:{}},s)}else if(A==="file_read"){let v=m.item.filename||m.item.path;S.push(v?`Read ${v.split("/").pop()}`:"Read"),l?.({type:"tool_use",jobId:s,tool:"Read",...v?{file:v}:{}},s)}else if(A==="web_search")S.push("WebSearch"),l?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if(A==="mcp_tool_call"){let v=m.item.tool_name||m.item.name||"MCP";S.push(v),l?.({type:"tool_use",jobId:s,tool:v},s)}}if((H==="item.completed"||H==="item/completed")&&m.item){if(m.item.type==="agent_message"){let A=m.item.text;typeof A=="string"&&A&&(j.push(A),l?.({type:"delta",jobId:s,text:A},s))}else if(m.item.type==="reasoning"){let A=m.item.text;typeof A=="string"&&A&&l?.({type:"thinking",jobId:s,text:A},s)}else if(m.item.type==="file_change"&&Array.isArray(m.item.changes))for(let A of m.item.changes){let v=A.path||A.filename,C=A.kind==="add"?"Write":"Edit";if(v){S.push(`${C} ${v.split("/").pop()}`),l?.({type:"tool_use",jobId:s,tool:C,file:v},s);let ne=A,T=typeof ne.kind=="string"?ne.kind:void 0,ae=Cs(T),ee=K.get(v),oe=Ue(t,v);F.push({sequence:F.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:ae,filePath:v,...ee?{before:ee}:{},...oe?{after:oe}:{},...At(ne)?{patch:At(ne)}:{},...T?{rawKind:T}:{}}),K.set(v,oe)}}else if(m.item.type==="command_execution"){let A=typeof m.item.id=="string"?m.item.id:void 0,v=A?L.get(A):void 0,C=typeof m.item.command=="string"?m.item.command:v?.rawCommand,ne=C?Tt(C):v?.command,T=_t(t);if($s(v?.beforeWorktree,T)){let ae=[...new Set([...v?.beforeWorktree?.changedFiles??[],...T?.changedFiles??[]])],ee=typeof m.item.aggregated_output=="string"?dt(m.item.aggregated_output,Es):void 0,oe=typeof m.item.exit_code=="number"?m.item.exit_code:m.item.exit_code===null?null:void 0,ke=typeof m.item.status=="string"?m.item.status:void 0;F.push({sequence:F.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...C?{rawCommand:C}:{},...ne?{command:ne}:{},...oe!==void 0?{exitCode:oe}:{},...ke?{status:ke}:{},...ee?{output:ee.text}:{},...ee?.truncated?{outputTruncated:!0}:{},...v?.beforeWorktree?{beforeWorktree:v.beforeWorktree}:{},...T?{afterWorktree:T}:{},...ae.length>0?{touchedFiles:Os(t,ae,v?.beforeSnapshots??new Map)}:{}})}A&&L.delete(A)}}H==="turn.failed"&&(X=!0,D=m.error?.message||m.message||"Turn failed")}catch{}});let N=[];R.stderr?.on("data",I=>{N.push(I.toString())}),R.on("close",I=>{Z.close(),j.length===0&&P.size>0&&console.warn(`[Codex:${s}] No text captured. Event types seen: ${[...P].join(", ")}`),I!==0&&I!==null&&(X=!0,D=N.join("")||`Codex process exited with code ${I}`),$({sessionId:q,text:j.join(""),success:!X,error:X?D:void 0,editEvents:F.length>0?F:void 0,toolsUsed:S.length>0?S:void 0})}),R.on("error",I=>{X=!0,D=I.message,$({sessionId:q,text:j.join(""),success:!1,error:D,editEvents:F.length>0?F:void 0,toolsUsed:S.length>0?S:void 0})})});return{process:R,result:O}}import{spawn as Ds}from"child_process";import{createInterface as Ns}from"readline";function zt(s,e){let n=s.trim()||"Copilot CLI failed",t=n.toLowerCase();return t.includes("no authentication information")||t.includes("not authenticated")||t.includes("/login")?{code:"copilot_auth_required",recoverable:!0,message:"Copilot is not authenticated. Run `copilot login`, set `COPILOT_GITHUB_TOKEN`, or refresh `gh auth login`."}:t.includes("model")&&(t.includes("not available")||t.includes("not found")||t.includes("disabled")||t.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:n}:t.includes("mcp")&&(t.includes("blocked")||t.includes("allowlist"))?{code:"copilot_mcp_blocked",recoverable:!0,message:"Copilot blocked the Popmelt MCP server. Ask your administrator to add it to the enterprise allowlist."}:t.includes("permission")||t.includes("denied")||t.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:n}:{code:"copilot_error",recoverable:!1,message:n}}function Bt(s,e){let{prompt:n,projectRoot:t,resumeSessionId:o,model:i,timeoutMs:a=3e5,onEvent:l,copilotPath:f="copilot"}=e,k=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];o&&k.push(`--resume=${o}`),i&&k.push("--model",i),k.push("-p",n);let b=Ds(f,k,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(O=>{let $,q=[],j=[],S=!1,F="",K=!1,L=setTimeout(()=>{K=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},a),X=Ns({input:b.stdout}),D=new Set,Z=[];X.on("line",N=>{if(N.trim())try{let I=JSON.parse(N),m=Me(I);D.add(m),Z.length<5&&js(m)&&Z.push(N.slice(0,800));let H=Ie(I,["sessionId","session_id","id"],["session","conversation","thread"]);H&&!$&&($=H);let A=Js(I,q.length===0);A&&(q.push(A),l?.({type:"delta",jobId:s,text:A},s));let v=zs(I);v&&l?.({type:"thinking",jobId:s,text:v},s);let C=Bs(I);C&&(j.push(C.label),l?.({type:"tool_use",jobId:s,tool:C.tool,...C.file?{file:C.file}:{},...C.content?{content:C.content}:{}},s));let ne=Fs(I);ne&&(S=!0,F=ne)}catch{}});let P=[];b.stderr?.on("data",N=>{P.push(N.toString())}),b.on("close",N=>{clearTimeout(L),X.close(),q.length===0&&D.size>0&&(console.warn(`[Copilot:${s}] No text captured. Event types seen: ${[...D].join(", ")}`),Z.length>0&&console.warn(`[Copilot:${s}] Sample text-bearing candidates: ${Z.join(`
32
+ `)}`)),K?(S=!0,F=`Timed out after ${Math.round(a/6e4)} minutes`):N!==0&&N!==null&&(S=!0,F=P.join("").trim()||F||`Copilot process exited with code ${N}`);let I=S?zt(F,i):null;O({sessionId:$,text:q.join(""),success:!S,error:I?.message,errorCode:I?.code,recoverableError:I?.recoverable,provider:"copilot",toolsUsed:j.length>0?j:void 0})}),b.on("error",N=>{clearTimeout(L);let I=zt(N.message,i);O({sessionId:$,text:q.join(""),success:!1,error:I.message,errorCode:I.code,recoverableError:I.recoverable,provider:"copilot",toolsUsed:j.length>0?j:void 0})})});return{process:b,result:R}}function Me(s){if(typeof s.type=="string")return s.type;let e=s.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof s.event=="string"?s.event:"unknown"}function Js(s,e=!1){let n=Me(s).toLowerCase(),t=s.update,o=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&o?.type==="text"&&typeof o.text=="string")return o.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return he(s.delta)??he(s.content)??he(s.message);if(n==="assistant.message"&&e)return he(s.message)??he(s.content)??he(s);if(n==="result"&&e)return he(s.result)??he(s.output)??he(s.message)??he(s);let i=s.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof s.text=="string"&&ut(s))return s.text;if(typeof s.message=="string"&&ut(s))return s.message;if(typeof s.delta=="string"&&ut(s))return s.delta}function he(s){if(typeof s=="string")return s;if(!s)return;if(Array.isArray(s)){let n=s.map(he).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof s!="object")return;let e=s;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=he(e[n]);if(t)return t}}function js(s){let e=s.toLowerCase();return e.includes("assistant.message")||e==="result"}function zs(s){if(typeof s.thinking=="string")return s.thinking;if(typeof s.reasoning=="string")return s.reasoning;let e=s.update;if(e?.sessionUpdate==="reasoning_chunk"){let n=e.content;if(typeof n?.text=="string")return n.text}}function Bs(s){let e=Ie(s,["tool","toolName","tool_name","name"]),n=Ie(s,["command","cmd"]),t=Ie(s,["file","path","filename","filePath"]),o=Me(s);if(n||o.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
33
+ `)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let i=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function Fs(s){if(typeof s.error=="string")return s.error;if(s.error&&typeof s.error=="object"){let e=s.error;if(typeof e.message=="string")return e.message}if(typeof s.message=="string"&&Me(s).toLowerCase().includes("error"))return s.message}function Ie(s,e,n=[]){for(let t of e){let o=s[t];if(typeof o=="string")return o}for(let[t,o]of Object.entries(s)){if(!o||typeof o!="object"||n.length>0&&!n.some(a=>t.toLowerCase().includes(a)))continue;let i=Ie(o,e);if(i)return i}}function ut(s){let e=Me(s).toLowerCase();return(typeof s.role=="string"?s.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{execFile as Us}from"child_process";import{copyFile as Ft,mkdir as Ut,readdir as Ls,readFile as Ws,writeFile as Hs}from"fs/promises";import{join as Se}from"path";var We=class{constructor(e){this.projectRoot=e;let n=Se(e,".popmelt");this.decisionsDir=Se(n,"decisions"),this.screenshotsDir=Se(n,"screenshots")}async persist(e,n,t){try{await Ut(this.decisionsDir,{recursive:!0}),await Ut(this.screenshotsDir,{recursive:!0});try{await Ft(n,Se(this.screenshotsDir,`s-${e.id}.webp`))}catch{}for(let o=0;o<t.length;o++)try{let i=e.pastedImagePaths[o];i&&await Ft(t[o],Se(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await Hs(Se(this.decisionsDir,`d-${e.id}.json`),JSON.stringify(e,null,2))}catch(o){console.error("[DecisionStore] Failed to persist decision record:",o)}}async listDecisionIds(){try{return(await Ls(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await Ws(Se(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}captureGitDiff(e){return new Promise(n=>{Us("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(t,o)=>{if(t){n(null);return}n(o||null)})})}};import{mkdir as Re,readFile as Lt,writeFile as Ee}from"fs/promises";import{join as Te}from"path";var Gs=80,qs=24,Wt=1e3,He=class{constructor(e){this.evalsDir=Te(e,".popmelt","evals"),this.suitePath=Te(this.evalsDir,"evals.json"),this.runsPath=Te(this.evalsDir,"runs.json"),this.screenshotsDir=Te(this.evalsDir,"screenshots")}async loadSuite(){try{let e=await Lt(this.suitePath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.cases))return n}catch{}return{version:1,updatedAt:0,cases:[]}}async loadRuns(){try{let e=await Lt(this.runsPath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.runs))return n}catch{}return{version:1,updatedAt:0,runs:[]}}async loadSuiteWithRuns(){let[e,n]=await Promise.all([this.loadSuite(),this.loadRuns()]);return{...e,runs:n.runs}}async loadSuiteWithCurrentRuns(e){let n=await this.loadSuiteWithRuns();return e?{...n,runs:n.runs.filter(t=>t.codeFingerprint===e)}:n}async writeSynthesized(e){let n=await this.loadSuite(),t=new Map(n.cases.map(a=>[a.id,a])),o=new Set;for(let a of e){let l=t.get(a.id);l&&(l.title!==a.title||l.prompt!==a.prompt||JSON.stringify(l.assertions)!==JSON.stringify(a.assertions))&&o.add(a.id),t.set(a.id,a)}let i={version:1,updatedAt:Date.now(),cases:[...t.values()]};return await Re(this.evalsDir,{recursive:!0}),await Ee(this.suitePath,JSON.stringify(i,null,2)),o.size>0&&await this.invalidateRunsForEvals(o),i}async updateCase(e,n){let t=await this.loadSuite(),o=n.title!==void 0||n.assertions!==void 0,i=t.cases.map(l=>l.id===e?{...l,...n.status?{status:n.status}:{},...n.title?{title:n.title}:{},...n.assertions?{assertions:n.assertions}:{}}:l),a=i.find(l=>l.id===e)??null;return a?(await Re(this.evalsDir,{recursive:!0}),await Ee(this.suitePath,JSON.stringify({version:1,updatedAt:Date.now(),cases:i},null,2)),o&&await this.invalidateRunsForEvals(new Set([e])),a):null}async invalidateRunsForEvals(e){let t=(await this.loadRuns()).runs.filter(i=>!e.has(i.evalId)),o={version:1,updatedAt:Date.now(),runs:t};return await Re(this.evalsDir,{recursive:!0}),await Ee(this.runsPath,JSON.stringify(o,null,2)),o}async writeRun(e){let n=await this.loadRuns(),t=[e,...n.runs.filter(i=>i.id!==e.id)].slice(0,200),o={version:1,updatedAt:Date.now(),runs:t};return await Re(this.evalsDir,{recursive:!0}),await Ee(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(e,n){return await Re(this.screenshotsDir,{recursive:!0}),await Ee(Te(this.screenshotsDir,`eval-${e}.webp`),n),`evals/screenshots/eval-${e}.webp`}async findCase(e){return(await this.loadSuite()).cases.find(t=>t.id===e)??null}};function Ht(s){let e=s.match(/<evals>\s*([\s\S]*?)\s*<\/evals>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return t?Qt(t):null}catch{return null}}function Gt(s){let e=s.match(/<eval_proposals>\s*([\s\S]*?)\s*<\/eval_proposals>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return t?Qt(t,"pending"):null}catch{return null}}function qt(s,e){let n=s.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let t=JSON.parse(n[1]),o=Zs(t.assertionResults,e),i=eo(o);return{status:i,summary:fe(t.summary)||Vt(i),assertionResults:o,tooling:to(t.tooling)}}catch{}return{status:"needs_review",summary:Ge(s.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:e.map(t=>({assertion:t,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function Qt(s,e="approved"){let n=[];return s.forEach((t,o)=>{if(!t||typeof t!="object")return;let i=t,a=fe(i.title),l=fe(i.prompt),f=fe(i.rationale),k=xe(i.assertions);if(!a||!l||k.length===0)return;let b=Ys(i.category),R=no(fe(i.id))||`eval-${Zt(a).slice(0,32)||o+1}`,O=Ks(i.status)??e;n.push({id:R,title:a,status:O,category:b,prompt:l,assertions:k,rationale:f||"Inferred from Popmelt design history.",sourceDecisionIds:xe(i.sourceDecisionIds),sourceThreadIds:xe(i.sourceThreadIds)})}),n}function Xt(s){let e=[...s.decisions].sort((t,o)=>o.createdAt-t.createdAt).slice(0,Gs),n=Object.values(s.threads.threads).sort((t,o)=>o.updatedAt-t.updatedAt).slice(0,qs);return`You are helping a designer turn organic Popmelt annotation history into a project eval suite.
34
34
 
35
35
  The designer does NOT work eval-first. They use annotations and conversation threads to zhuzh the UI over time. Your job is to infer useful eval proposals from that trail. The developer will reject, refine, or approve proposals in this thread. Do not write files or run commands.
36
36
 
@@ -45,12 +45,12 @@ ${JSON.stringify(s.existingSuite,null,2)}
45
45
  \`\`\`
46
46
 
47
47
  ## Recent Decisions
48
- ${e.map(Hs).join(`
48
+ ${e.map(Qs).join(`
49
49
 
50
50
  `)||"No decisions found."}
51
51
 
52
52
  ## Recent Threads
53
- ${n.map(Gs).join(`
53
+ ${n.map(Xs).join(`
54
54
 
55
55
  `)||"No threads found."}
56
56
 
@@ -86,7 +86,7 @@ Allowed categories: component, layout, copy, interaction, visual, workflow.
86
86
  Return only the <evals> block after approval.
87
87
 
88
88
  ## First Response Structured Block
89
- At the end of your first proposal response, output a JSON array inside <eval_proposals> tags using the same schema, but with "status": "pending".`}function Xt(s){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
89
+ At the end of your first proposal response, output a JSON array inside <eval_proposals> tags using the same schema, but with "status": "pending".`}function Yt(s){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
90
90
 
91
91
  ## Eval
92
92
  \`\`\`json
@@ -141,7 +141,7 @@ The block must be valid JSON with this shape:
141
141
  \`\`\`
142
142
 
143
143
  Allowed statuses: pass, fail, needs_review.
144
- Allowed chromeDevtools values: available, unavailable, unknown.`}function Yt(s){return`You are turning an approved Popmelt taste-model update into draft evals.
144
+ Allowed chromeDevtools values: available, unavailable, unknown.`}function Kt(s){return`You are turning an approved Popmelt taste-model update into draft evals.
145
145
 
146
146
  The model is the source of truth. Evals are executable projections of model properties and values. Your job is to translate the approved model proposal into concrete, falsifiable eval proposals that a designer can review in the Eval panel.
147
147
 
@@ -190,30 +190,30 @@ Allowed categories: component, layout, copy, interaction, visual, workflow.
190
190
 
191
191
  <eval_proposals>
192
192
  []
193
- </eval_proposals>`}function Hs(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(c=>c.instruction).filter(Boolean).join(`
194
- `),i=n.map(c=>{let f=c.finalScope??c.inferredScope??c.declaredScope;return`- ${c.status}: ${c.summary}${f?` [${f.breadth}/${f.target}]`:""}`}).join(`
195
- `),a=[...new Set([...n.flatMap(c=>c.filesModified??[]),...t.map(c=>c.filePath).filter(c=>!!c)])].slice(0,12);return`### Decision ${s.id}
193
+ </eval_proposals>`}function Qs(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(l=>l.instruction).filter(Boolean).join(`
194
+ `),i=n.map(l=>{let f=l.finalScope??l.inferredScope??l.declaredScope;return`- ${l.status}: ${l.summary}${f?` [${f.breadth}/${f.target}]`:""}`}).join(`
195
+ `),a=[...new Set([...n.flatMap(l=>l.filesModified??[]),...t.map(l=>l.filePath).filter(l=>!!l)])].slice(0,12);return`### Decision ${s.id}
196
196
  Thread: ${s.threadId??"none"}
197
197
  Created: ${new Date(s.createdAt).toISOString()}
198
198
  URL: ${s.url||"unknown"}
199
199
  Instructions:
200
- ${He(o||"(none)",Lt)}
200
+ ${Ge(o||"(none)",Wt)}
201
201
  Resolutions:
202
- ${He(i||"(none)",Lt)}
203
- Files: ${a.length>0?a.join(", "):"none"}`}function Gs(s){let n=s.messages.slice(0,2).concat(s.messages.length>4?s.messages.slice(-2):s.messages.slice(2)).map(t=>{let o=t.feedbackSummary??t.replyToQuestion??t.question??t.responseText??"",i=t.resolutions?.map(a=>`${a.status}: ${a.summary}`).join("; ")??"";return`- ${t.role}: ${He(o||i||"(no text)",500)}`}).join(`
202
+ ${Ge(i||"(none)",Wt)}
203
+ Files: ${a.length>0?a.join(", "):"none"}`}function Xs(s){let n=s.messages.slice(0,2).concat(s.messages.length>4?s.messages.slice(-2):s.messages.slice(2)).map(t=>{let o=t.feedbackSummary??t.replyToQuestion??t.question??t.responseText??"",i=t.resolutions?.map(a=>`${a.status}: ${a.summary}`).join("; ")??"";return`- ${t.role}: ${Ge(o||i||"(no text)",500)}`}).join(`
204
204
  `);return`### Thread ${s.id}
205
205
  Messages: ${s.messages.length}
206
206
  Updated: ${new Date(s.updatedAt).toISOString()}
207
- ${n}`}function he(s){return typeof s=="string"?s.trim():""}function be(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function qs(s){let e=he(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function Qs(s){let e=he(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function Xs(s){let e=he(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ys(s,e){let t=(Array.isArray(s)?s:[]).map(o=>{if(!o||typeof o!="object")return null;let i=o,a=he(i.assertion);return a?{assertion:a,status:Xs(i.status)??"needs_review",summary:he(i.summary)||Kt("needs_review"),evidence:be(i.evidence)}:null}).filter(o=>o!==null);return t.length>0?t:e.map(o=>({assertion:o,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function Ks(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Vs(s){if(!s||typeof s!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=s,n=he(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:be(e.evidenceTypes).length>0?be(e.evidenceTypes):["screenshot"]}}function Kt(s){return s==="pass"?"The current page appears to satisfy this eval.":s==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function Zs(s){return Vt(s).slice(0,48)}function Vt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function He(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as Zt}from"crypto";import{mkdir as pt,readFile as Ge,writeFile as ve}from"fs/promises";import{dirname as ht,join as Te}from"path";var te="[Materializer]",en={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},eo={version:1,runs:[]},to={version:1,updatedAt:0,proposals:[]},no=12;function so(s){return Array.isArray(s)?s.map((e,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function Ce(s){let e=[];for(let n of s){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${te} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${te} Rule count ${e.length} exceeds cap of 30`),e}function oo(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function ro(s,e){let n=new Set(e),t=new Set,o=Array.isArray(s.rules)?s.rules:[];for(let c of o){if(!c||typeof c!="object")continue;let f=c.sources;if(Array.isArray(f))for(let x of f)typeof x=="string"&&n.has(x)&&t.add(x)}let i=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?s.tokens:{},a=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?s.components:{};return{ruleCount:o.length,tokenSectionCount:Object.keys(i).length,componentCount:Object.keys(a).length,coveredDecisionIds:[...t],uncoveredDecisionIds:e.filter(c=>!t.has(c))}}var qe=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=Te(e,".popmelt");this.indexPath=Te(o,"materialized.json"),this.runsPath=Te(o,"materialization-runs.json"),this.proposalsPath=Te(o,"model-proposals.json"),this.modelPath=Te(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Ge(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=so(n.rules)),n}catch{return null}}async addComponent(e){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let t=n.components;return t[e]?{added:!1,alreadyExists:!0}:(t[e]={description:""},await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${te} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]});let o=e.split("."),i=t;for(let f=0;f<o.length-1;f++){let x=o[f];(!i[x]||typeof i[x]!="object")&&(i[x]={}),i=i[x]}let a=o[o.length-1],c;try{c=JSON.parse(n)}catch{c=null}if(c&&typeof c=="object"&&c!==null&&"value"in c)i[a]=c;else{let f=i[a];f&&typeof f=="object"&&f!==null&&"value"in f?f.value=n:i[a]=n}return await ve(this.modelPath,JSON.stringify(t,null,2)),console.log(`${te} Updated token "${e}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=e.split("."),o=n;for(let a=0;a<t.length-1;a++){let c=t[a];if(!o[c]||typeof o[c]!="object")return{removed:!1};o=o[c]}let i=t[t.length-1];return i in o?(delete o[i],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${te} Removed token "${e}" from model`),{removed:!0}):{removed:!1}}async removeComponent(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=n.components;return!t||!t[e]?{removed:!1}:(delete t[e],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${te} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){return(await this.selectUnmaterializedPatternDecisions()).decisions}async selectUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=(await this.decisionStore.listDecisionIds()).filter(c=>{let f=e.decisions[c];return f?f.status==="applied"||f.status==="merged"||f.status==="rejected"||f.status==="running"||f.status==="queued"||f.status==="proposed"?!1:f.attemptCount<3:!0});if(t.length===0)return{decisions:[],totalCandidateDecisionCount:0};let i=(await this.decisionStore.loadDecisions(t)).filter(c=>c.resolutions.some(f=>(f.finalScope??f.inferredScope)?.breadth==="pattern")),a=i.sort((c,f)=>f.createdAt-c.createdAt).slice(0,no);return i.length>a.length&&console.log(`${te} Selected ${a.length}/${i.length} pattern decision(s); remaining decisions stay pending for later runs.`),{decisions:a,totalCandidateDecisionCount:i.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnmaterializedPatternDecisions(),o=t.decisions;if(o.length===0)return{processedIds:[],success:!0};let i=o.map(z=>z.id);console.log(`${te} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let a=await this.loadModel(),c=co(o,a),f=oo(o,t.totalCandidateDecisionCount,c);n=Zt().slice(0,8);let x={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,decisionIds:i,startedAt:Date.now(),promptStats:f};await this.persistRun(x),await this.updateDecisionStates(i,"running",n);let b=!0,M,O,$;try{let z=`mat-${Date.now()}`,{provider:w,result:B}=this.spawnModelAgent(z,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});x={...x,provider:w},await this.persistRun(x);let Y=await B;if(!Y.success)b=!1,M=Y.error,console.error(`${te} ${w} spawn error:`,M);else{let L=Qe(Y.text);if(L){Array.isArray(L.rules)&&(L.rules=Ce(L.rules)),O=ro(L,i);let q=await this.createModelProposal({decisionIds:i,proposedModel:L,runId:n,threadId:e.threadId,provider:w,model:e.model??this.options.model});$=q.id,console.log(`${te} Created model proposal ${q.id} for ${i.length} decision(s)`)}else b=!1,M="No <model> block found in response",console.error(`${te} ${M}`)}}catch(z){b=!1,M=z instanceof Error?z.message:String(z),console.error(`${te} Error:`,M)}let G=await this.loadIndex();return G.lastRunAt=Date.now(),G.lastRunDecisionIds=i,G.lastRunError=M??null,await this.persistIndex(G),await this.updateDecisionStates(i,b?"proposed":"failed",n,M),await this.persistRun({...x,status:b?"proposed":"failed",completedAt:Date.now(),error:M,outputStats:O,proposalId:$}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:b,error:M}),{processedIds:i,success:b,error:M,runId:n,proposalId:$}}finally{this.running=!1}}async consolidate(e={}){if(this.running)return{success:!1,error:"Already running"};this.running=!0;try{let n=await this.loadModel();if(!n)return{success:!1,error:"No model exists"};let t=lo(n),{provider:o,result:i}=this.spawnModelAgent(`consolidate-${Date.now()}`,t,e,{maxTurns:this.options.maxTurns??3,maxBudgetUsd:this.options.maxBudgetUsd??.3,allowedTools:[]}),a=await i;if(!a.success)return console.error(`${te} ${o} consolidation spawn error:`,a.error),{success:!1,error:a.error};let c=Qe(a.text);return c?(Array.isArray(c.rules)&&(c.rules=Ce(c.rules)),!c.tokens&&n.tokens&&(c.tokens=n.tokens),!c.components&&n.components&&(c.components=n.components),await ve(this.modelPath,JSON.stringify(c,null,2)),console.log(`${te} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${te} No <model> block in consolidation response`),{success:!1,error:"No <model> block found"})}catch(n){let t=n instanceof Error?n.message:String(n);return console.error(`${te} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ce(e.rules)),await ve(this.modelPath,JSON.stringify(e,null,2)),console.log(`${te} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await Ge(this.indexPath,"utf-8"),n=JSON.parse(e);if(n.version===2&&n.decisions)return this.cachedIndex=n,this.cachedIndex;if(n.version===1&&Array.isArray(n.materializedIds)){let t=Date.now(),o=Object.fromEntries(n.materializedIds.map(i=>[i,{status:"applied",runIds:[],attemptCount:1,updatedAt:t}]));return this.cachedIndex={version:2,decisions:o,lastRunAt:n.lastRunAt??null,lastRunDecisionIds:n.lastRunDecisionIds??[],lastRunError:n.lastRunError??null,materializedIds:n.materializedIds},this.cachedIndex}}catch{return this.cachedIndex={...en,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...en,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}async persistIndex(e){e.materializedIds=Object.entries(e.decisions).filter(([,n])=>n.status==="applied"||n.status==="merged").map(([n])=>n),this.cachedIndex=e;try{await pt(ht(this.indexPath),{recursive:!0}),await ve(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${te} Failed to write index:`,n)}}async loadRuns(){try{let e=await Ge(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...eo,runs:[]}}async loadModelProposals(){try{let e=await Ge(this.proposalsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.proposals))return n}catch{}return{...to,proposals:[]}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,o)=>o.updatedAt-t.updatedAt)[0]??null}async applyModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;if(n.status==="dismissed")return n;await this.writeModel(n.proposedModel);let t=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0});return await this.updateDecisionStates(n.decisionIds,"applied",n.runId??e),t}async dismissModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;let t=await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()});return await this.updateDecisionStates(n.decisionIds,"rejected",n.runId??e),t}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let o=new Set(t.generatedEvalIds??[]);for(let i of n)o.add(i);return this.updateModelProposal(e,{generatedEvalIds:[...o]})}async createModelProposal(e){let n={id:Zt().slice(0,8),status:"pending",title:io(e.proposedModel),summary:ao(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,provider:e.provider,model:e.model,proposedModel:e.proposedModel,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(o=>o.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),o=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(o={...i,...n,updatedAt:Date.now()},o)),o?(t.updatedAt=Date.now(),await this.persistModelProposals(t),o):null}async persistModelProposals(e){try{await pt(ht(this.proposalsPath),{recursive:!0}),await ve(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${te} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(o=>o.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await pt(ht(this.runsPath),{recursive:!0}),await ve(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${te} Failed to write materialization run:`,n)}}async updateDecisionStates(e,n,t,o){let i=await this.loadIndex(),a=Date.now();for(let c of e){let f=i.decisions[c],x=f?.runIds.includes(t)?f.runIds:[...f?.runIds??[],t];i.decisions[c]={status:n,runIds:x,error:o,attemptCount:n==="running"?f?.attemptCount??0:(f?.attemptCount??0)+1,updatedAt:a}}await this.persistIndex(i)}spawnModelAgent(e,n,t,o){let i=t.provider??this.options.provider??"claude",a=this.options.onEvent?(c,f)=>this.options.onEvent?.(c):void 0;return i==="codex"?{provider:"codex",...Ue(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:a})}:(i==="copilot"&&console.warn(`${te} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...Fe(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?t.model??this.options.model:void 0,timeoutMs:this.options.timeoutMs,onEvent:a})})}};function io(s){let n=(Array.isArray(s.rules)?s.rules:[]).find(o=>o&&typeof o=="object"&&typeof o.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function ao(s,e){let n=Array.isArray(s.rules)?s.rules.length:0,t=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?Object.keys(s.tokens).length:0,o=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${o} component entr${o===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Qe(s){let e=s.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}function co(s,e){let n=s.map(i=>{let c=i.resolutions.filter(b=>(b.finalScope??b.inferredScope)?.breadth==="pattern").map(b=>{let O=(b.finalScope??b.inferredScope)?.target??"unknown",$=b.filesModified?.join(", ")??"none";return`- **${b.summary}** [scope: pattern/${O}]
207
+ ${n}`}function fe(s){return typeof s=="string"?s.trim():""}function xe(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Ys(s){let e=fe(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function Ks(s){let e=fe(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function Vs(s){let e=fe(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Zs(s,e){let t=(Array.isArray(s)?s:[]).map(o=>{if(!o||typeof o!="object")return null;let i=o,a=fe(i.assertion);return a?{assertion:a,status:Vs(i.status)??"needs_review",summary:fe(i.summary)||Vt("needs_review"),evidence:xe(i.evidence)}:null}).filter(o=>o!==null);return t.length>0?t:e.map(o=>({assertion:o,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function eo(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function to(s){if(!s||typeof s!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=s,n=fe(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:xe(e.evidenceTypes).length>0?xe(e.evidenceTypes):["screenshot"]}}function Vt(s){return s==="pass"?"The current page appears to satisfy this eval.":s==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function no(s){return Zt(s).slice(0,48)}function Zt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ge(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as en}from"crypto";import{mkdir as pt,readFile as qe,writeFile as ve}from"fs/promises";import{dirname as ht,join as Ce}from"path";var se="[Materializer]",tn={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},so={version:1,runs:[]},oo={version:1,updatedAt:0,proposals:[]},ro=12;function io(s){return Array.isArray(s)?s.map((e,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function Ae(s){let e=[];for(let n of s){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${se} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${se} Rule count ${e.length} exceeds cap of 30`),e}function ao(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function lo(s,e){let n=new Set(e),t=new Set,o=Array.isArray(s.rules)?s.rules:[];for(let l of o){if(!l||typeof l!="object")continue;let f=l.sources;if(Array.isArray(f))for(let k of f)typeof k=="string"&&n.has(k)&&t.add(k)}let i=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?s.tokens:{},a=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?s.components:{};return{ruleCount:o.length,tokenSectionCount:Object.keys(i).length,componentCount:Object.keys(a).length,coveredDecisionIds:[...t],uncoveredDecisionIds:e.filter(l=>!t.has(l))}}function co(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function uo(s,e,n){let t=s[e];if(t&&typeof t=="object")return t;let o=typeof n=="number"?[]:{};return s[String(e)]=o,o}function po(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=uo(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=co(n)}function ho(s,e){let n=s;for(let o=0;o<e.length-1;o++){let i=n[String(e[o])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}var Qe=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=Ce(e,".popmelt");this.indexPath=Ce(o,"materialized.json"),this.runsPath=Ce(o,"materialization-runs.json"),this.proposalsPath=Ce(o,"model-proposals.json"),this.modelPath=Ce(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await qe(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=io(n.rules)),n}catch{return null}}async addComponent(e){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let t=n.components;return t[e]?{added:!1,alreadyExists:!0}:(t[e]={description:""},await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${se} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]});let o=e.split("."),i=t;for(let f=0;f<o.length-1;f++){let k=o[f];(!i[k]||typeof i[k]!="object")&&(i[k]={}),i=i[k]}let a=o[o.length-1],l;try{l=JSON.parse(n)}catch{l=null}if(l&&typeof l=="object"&&l!==null&&"value"in l)i[a]=l;else{let f=i[a];f&&typeof f=="object"&&f!==null&&"value"in f?f.value=n:i[a]=n}return await ve(this.modelPath,JSON.stringify(t,null,2)),console.log(`${se} Updated token "${e}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=e.split("."),o=n;for(let a=0;a<t.length-1;a++){let l=t[a];if(!o[l]||typeof o[l]!="object")return{removed:!1};o=o[l]}let i=t[t.length-1];return i in o?(delete o[i],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${se} Removed token "${e}" from model`),{removed:!0}):{removed:!1}}async removeComponent(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=n.components;return!t||!t[e]?{removed:!1}:(delete t[e],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${se} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){return(await this.selectUnmaterializedPatternDecisions()).decisions}async selectUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=(await this.decisionStore.listDecisionIds()).filter(l=>{let f=e.decisions[l];return f?f.status==="applied"||f.status==="merged"||f.status==="rejected"||f.status==="running"||f.status==="queued"||f.status==="proposed"?!1:f.attemptCount<3:!0});if(t.length===0)return{decisions:[],totalCandidateDecisionCount:0};let i=(await this.decisionStore.loadDecisions(t)).filter(l=>l.resolutions.some(f=>(f.finalScope??f.inferredScope)?.breadth==="pattern")),a=i.sort((l,f)=>f.createdAt-l.createdAt).slice(0,ro);return i.length>a.length&&console.log(`${se} Selected ${a.length}/${i.length} pattern decision(s); remaining decisions stay pending for later runs.`),{decisions:a,totalCandidateDecisionCount:i.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnmaterializedPatternDecisions(),o=t.decisions;if(o.length===0)return{processedIds:[],success:!0};let i=o.map(j=>j.id);console.log(`${se} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let a=await this.loadModel(),l=go(o,a),f=ao(o,t.totalCandidateDecisionCount,l);n=en().slice(0,8);let k={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,decisionIds:i,startedAt:Date.now(),promptStats:f};await this.persistRun(k),await this.updateDecisionStates(i,"running",n);let b=!0,R,O,$;try{let j=`mat-${Date.now()}`,{provider:S,result:F}=this.spawnModelAgent(j,l,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});k={...k,provider:S},await this.persistRun(k);let K=await F;if(!K.success)b=!1,R=K.error,console.error(`${se} ${S} spawn error:`,R);else{let L=Xe(K.text);if(L){Array.isArray(L.rules)&&(L.rules=Ae(L.rules)),O=lo(L,i);let X=await this.createModelProposal({decisionIds:i,proposedModel:L,runId:n,threadId:e.threadId,provider:S,model:e.model??this.options.model});$=X.id,console.log(`${se} Created model proposal ${X.id} for ${i.length} decision(s)`)}else b=!1,R="No <model> block found in response",console.error(`${se} ${R}`)}}catch(j){b=!1,R=j instanceof Error?j.message:String(j),console.error(`${se} Error:`,R)}let q=await this.loadIndex();return q.lastRunAt=Date.now(),q.lastRunDecisionIds=i,q.lastRunError=R??null,await this.persistIndex(q),await this.updateDecisionStates(i,b?"proposed":"failed",n,R),await this.persistRun({...k,status:b?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:O,proposalId:$}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:b,error:R}),{processedIds:i,success:b,error:R,runId:n,proposalId:$}}finally{this.running=!1}}async consolidate(e={}){if(this.running)return{success:!1,error:"Already running"};this.running=!0;try{let n=await this.loadModel();if(!n)return{success:!1,error:"No model exists"};let t=yo(n),{provider:o,result:i}=this.spawnModelAgent(`consolidate-${Date.now()}`,t,e,{maxTurns:this.options.maxTurns??3,maxBudgetUsd:this.options.maxBudgetUsd??.3,allowedTools:[]}),a=await i;if(!a.success)return console.error(`${se} ${o} consolidation spawn error:`,a.error),{success:!1,error:a.error};let l=Xe(a.text);return l?(Array.isArray(l.rules)&&(l.rules=Ae(l.rules)),!l.tokens&&n.tokens&&(l.tokens=n.tokens),!l.components&&n.components&&(l.components=n.components),await ve(this.modelPath,JSON.stringify(l,null,2)),console.log(`${se} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${se} No <model> block in consolidation response`),{success:!1,error:"No <model> block found"})}catch(n){let t=n instanceof Error?n.message:String(n);return console.error(`${se} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ae(e.rules)),await ve(this.modelPath,JSON.stringify(e,null,2)),console.log(`${se} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await qe(this.indexPath,"utf-8"),n=JSON.parse(e);if(n.version===2&&n.decisions)return this.cachedIndex=n,this.cachedIndex;if(n.version===1&&Array.isArray(n.materializedIds)){let t=Date.now(),o=Object.fromEntries(n.materializedIds.map(i=>[i,{status:"applied",runIds:[],attemptCount:1,updatedAt:t}]));return this.cachedIndex={version:2,decisions:o,lastRunAt:n.lastRunAt??null,lastRunDecisionIds:n.lastRunDecisionIds??[],lastRunError:n.lastRunError??null,materializedIds:n.materializedIds},this.cachedIndex}}catch{return this.cachedIndex={...tn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...tn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}async persistIndex(e){e.materializedIds=Object.entries(e.decisions).filter(([,n])=>n.status==="applied"||n.status==="merged").map(([n])=>n),this.cachedIndex=e;try{await pt(ht(this.indexPath),{recursive:!0}),await ve(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${se} Failed to write index:`,n)}}async loadRuns(){try{let e=await qe(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...so,runs:[]}}async loadModelProposals(){try{let e=await qe(this.proposalsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.proposals))return n}catch{}return{...oo,proposals:[]}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,o)=>o.updatedAt-t.updatedAt)[0]??null}async applyModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;if(n.status==="dismissed")return n;await this.writeModel(n.proposedModel);let t=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0});return await this.updateDecisionStates(n.decisionIds,"applied",n.runId??e),t}async applySelectedModelProposal(e,n){let t=await this.findModelProposal(e);if(!t)return null;if(t.status==="dismissed")return t;let o=await this.loadModel()??{};for(let a of n)!Array.isArray(a.path)||a.path.length===0||(a.remove?ho(o,a.path):po(o,a.path,a.value));await this.writeModel(o);let i=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0});return await this.updateDecisionStates(t.decisionIds,"applied",t.runId??e),i}async dismissModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;let t=await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()});return await this.updateDecisionStates(n.decisionIds,"rejected",n.runId??e),t}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let o=new Set(t.generatedEvalIds??[]);for(let i of n)o.add(i);return this.updateModelProposal(e,{generatedEvalIds:[...o]})}async createModelProposal(e){let n={id:en().slice(0,8),status:"pending",title:fo(e.proposedModel),summary:mo(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,provider:e.provider,model:e.model,proposedModel:e.proposedModel,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(o=>o.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),o=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(o={...i,...n,updatedAt:Date.now()},o)),o?(t.updatedAt=Date.now(),await this.persistModelProposals(t),o):null}async persistModelProposals(e){try{await pt(ht(this.proposalsPath),{recursive:!0}),await ve(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${se} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(o=>o.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await pt(ht(this.runsPath),{recursive:!0}),await ve(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${se} Failed to write materialization run:`,n)}}async updateDecisionStates(e,n,t,o){let i=await this.loadIndex(),a=Date.now();for(let l of e){let f=i.decisions[l],k=f?.runIds.includes(t)?f.runIds:[...f?.runIds??[],t];i.decisions[l]={status:n,runIds:k,error:o,attemptCount:n==="running"?f?.attemptCount??0:(f?.attemptCount??0)+1,updatedAt:a}}await this.persistIndex(i)}spawnModelAgent(e,n,t,o){let i=t.provider??this.options.provider??"claude",a=this.options.onEvent?(l,f)=>this.options.onEvent?.(l):void 0;return i==="codex"?{provider:"codex",...Le(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:a})}:(i==="copilot"&&console.warn(`${se} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...Fe(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?t.model??this.options.model:void 0,timeoutMs:this.options.timeoutMs,onEvent:a})})}};function fo(s){let n=(Array.isArray(s.rules)?s.rules:[]).find(o=>o&&typeof o=="object"&&typeof o.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function mo(s,e){let n=Array.isArray(s.rules)?s.rules.length:0,t=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?Object.keys(s.tokens).length:0,o=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${o} component entr${o===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Xe(s){let e=s.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}function go(s,e){let n=s.map(i=>{let l=i.resolutions.filter(b=>(b.finalScope??b.inferredScope)?.breadth==="pattern").map(b=>{let O=(b.finalScope??b.inferredScope)?.target??"unknown",$=b.filesModified?.join(", ")??"none";return`- **${b.summary}** [scope: pattern/${O}]
208
208
  Files modified: ${$}`}).join(`
209
209
  `),f=i.annotations.map(b=>b.instruction).filter(Boolean).join(`
210
- `),x=i.gitDiff?`
210
+ `),k=i.gitDiff?`
211
211
  \`\`\`diff
212
212
  ${i.gitDiff.slice(0,2e3)}
213
213
  \`\`\``:"";return`### Decision ${i.id} (${new Date(i.createdAt).toISOString()})
214
214
  Page: ${i.url}
215
- ${c}
216
- ${x}
215
+ ${l}
216
+ ${k}
217
217
  ${f?`
218
218
  Original instructions:
219
219
  ${f}`:""}`}).join(`
@@ -290,7 +290,7 @@ Example:
290
290
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
291
291
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
292
292
  - bindings: Tailwind class names (without responsive prefixes) that use this token
293
- Include property and bindings when the decision context has class-level evidence.`}function lo(s){return`You are consolidating a design model's rules. The model has accumulated too many rules and needs cleanup.
293
+ Include property and bindings when the decision context has class-level evidence.`}function yo(s){return`You are consolidating a design model's rules. The model has accumulated too many rules and needs cleanup.
294
294
 
295
295
  ## Current Model
296
296
  \`\`\`json
@@ -329,7 +329,7 @@ Output the complete model inside <model> tags. Preserve tokens and components as
329
329
 
330
330
  <model>
331
331
  { "tokens": { ... }, "components": { ... }, "rules": [ ... ] }
332
- </model>`}function tn(s){return`You are a design system curator reviewing a project's design model. Your job is to propose improvements to the rules \u2014 merging duplicates, filling gaps, removing noise.
332
+ </model>`}function nn(s){return`You are a design system curator reviewing a project's design model. Your job is to propose improvements to the rules \u2014 merging duplicates, filling gaps, removing noise.
333
333
 
334
334
  ## Current Model
335
335
  \`\`\`json
@@ -362,56 +362,57 @@ These are my proposed rule changes. Would you like to approve all of them, adjus
362
362
  </question>
363
363
 
364
364
  ## After approval
365
- When the developer approves (says "yes", "looks good", "go ahead", etc.), output the complete updated model inside <model> tags \u2014 the full JSON with tokens, components, and the revised rules array. Do NOT output partial models. Preserve tokens and components as-is unless the developer asks to change them.`}var Xe=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let o of this.listeners)o(e,n,t)}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"materialize_model",global:!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJob=null,this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as uo}from"child_process";import{readFile as mt}from"fs/promises";import{homedir as Ke}from"os";import{join as ue}from"path";var gt=/popmelt/i,po=/chrome|devtools/i;function Se(){return{found:!1,name:null,scope:null,disabled:!1}}function xe(s,e,n=!1){return{found:!0,name:s,scope:e,disabled:n}}function Ae(s){for(let e of Object.keys(s))if(gt.test(e))return e;return null}async function Ye(s){try{let e=await mt(s,"utf-8");return JSON.parse(e)}catch{return null}}async function vt(s){let e=Ke(),n=await Ye(ue(e,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=Ae(o.mcpServers);if(i)return xe(i,"user")}if(o.projects&&typeof o.projects=="object"){let a=o.projects[s];if(a&&typeof a=="object"){let c=a;if(c.mcpServers&&typeof c.mcpServers=="object"){let f=Ae(c.mcpServers);if(f){let x=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(b=>gt.test(b));return xe(f,"project",x)}}}}}let t=await Ye(ue(s,".mcp.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=Ae(o.mcpServers);if(a){let c=await nn(s,a);return xe(a,"mcp.json",c)}}let i=Ae(o);if(i&&i!=="mcpServers"){let a=await nn(s,i);return xe(i,"mcp.json",a)}}return Se()}async function nn(s,e){let n=ue(s,".claude","settings.local.json"),t=await Ye(n);if(t&&typeof t=="object"){let o=t;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var ho=/^\[mcp_servers\.([^\]]+)\]/;function fo(s){return s.replace(/^"(.+)"$/,"$1")}function mo(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function on(s){let e=s.split(`
366
- `),n=[],t=null;for(let o of e){let i=o.match(ho);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
365
+ When the developer approves (says "yes", "looks good", "go ahead", etc.), output the complete updated model inside <model> tags \u2014 the full JSON with tokens, components, and the revised rules array. Do NOT output partial models. Preserve tokens and components as-is unless the developer asks to change them.`}var Ye=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let o of this.listeners)o(e,n,t)}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"materialize_model",global:!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJob=null,this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as vo}from"child_process";import{readFile as mt}from"fs/promises";import{homedir as Ve}from"os";import{join as de}from"path";var gt=/popmelt/i,wo=/chrome|devtools/i;function be(){return{found:!1,name:null,scope:null,disabled:!1}}function Pe(s,e,n=!1){return{found:!0,name:s,scope:e,disabled:n}}function $e(s){for(let e of Object.keys(s))if(gt.test(e))return e;return null}async function Ke(s){try{let e=await mt(s,"utf-8");return JSON.parse(e)}catch{return null}}async function yt(s){let e=Ve(),n=await Ke(de(e,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=$e(o.mcpServers);if(i)return Pe(i,"user")}if(o.projects&&typeof o.projects=="object"){let a=o.projects[s];if(a&&typeof a=="object"){let l=a;if(l.mcpServers&&typeof l.mcpServers=="object"){let f=$e(l.mcpServers);if(f){let k=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(b=>gt.test(b));return Pe(f,"project",k)}}}}}let t=await Ke(de(s,".mcp.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=$e(o.mcpServers);if(a){let l=await sn(s,a);return Pe(a,"mcp.json",l)}}let i=$e(o);if(i&&i!=="mcpServers"){let a=await sn(s,i);return Pe(i,"mcp.json",a)}}return be()}async function sn(s,e){let n=de(s,".claude","settings.local.json"),t=await Ke(n);if(t&&typeof t=="object"){let o=t;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var So=/^\[mcp_servers\.([^\]]+)\]/;function bo(s){return s.replace(/^"(.+)"$/,"$1")}function xo(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function rn(s){let e=s.split(`
366
+ `),n=[],t=null;for(let o of e){let i=o.match(So);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
367
367
  `)}),t={name:i[1],bodyLines:[]}):o.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
368
368
  `)}),t=null):t&&t.bodyLines.push(o)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
369
- `)}),n}function rn(s){return/enabled\s*=\s*false/i.test(s)}async function yt(s){let e=process.env.CODEX_HOME||ue(Ke(),".codex"),n=await sn(ue(e,"config.toml"),"user");if(n.found)return n;let t=await sn(ue(s,".codex","config.toml"),"project");return t.found?t:Se()}async function go(s,e){let n=process.env.CODEX_HOME||ue(Ke(),".codex"),t=new Set;for(let o of[ue(n,"config.toml"),ue(s,".codex","config.toml")])try{let i=await mt(o,"utf-8");for(let a of on(i)){if(mo(a.name)||rn(a.body))continue;let c=fo(a.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function an(s){return go(s,po)}async function wt(s,e="copilot"){let n=await vo(e);if(n.found)return n;let t=process.env.COPILOT_HOME||ue(Ke(),".copilot"),o=await ft(ue(t,"mcp-config.json"),"user");if(o.found)return o;let i=await ft(ue(s,".mcp.json"),"mcp.json");if(i.found)return i;let a=await ft(ue(s,".github","mcp.json"),"mcp.json");return a.found?a:Se()}async function vo(s){try{let e=await new Promise((n,t)=>{uo(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return cn(JSON.parse(e),"user")}catch{return Se()}}async function ft(s,e){let n=await Ye(s);return cn(n,e)}function cn(s,e){if(!s||typeof s!="object")return Se();let n=s,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=Ae(t);return o?xe(o,e):Se()}async function sn(s,e){try{let n=await mt(s,"utf-8"),t=on(n);for(let o of t)if(gt.test(o.name)){let i=rn(o.body);return xe(o.name,e,i)}}catch{}return Se()}import{execFile as ln}from"child_process";import{mkdir as yo,readFile as dn,writeFile as un}from"fs/promises";import{homedir as pn}from"os";import{dirname as wo,join as St}from"path";var bt="https://mcp.popmelt.com/mcp";async function hn(s=bt){let e=St(pn(),".claude.json"),n;try{let o=await dn(e,"utf-8");n=JSON.parse(o)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let o of Object.keys(t))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:s},await un(e,JSON.stringify(n,null,2)+`
370
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function fn(s=bt){let e=process.env.CODEX_HOME||St(pn(),".codex"),n=St(e,"config.toml"),t;try{t=await dn(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await yo(wo(n),{recursive:!0});let o=`
369
+ `)}),n}function an(s){return/enabled\s*=\s*false/i.test(s)}async function vt(s){let e=process.env.CODEX_HOME||de(Ve(),".codex"),n=await on(de(e,"config.toml"),"user");if(n.found)return n;let t=await on(de(s,".codex","config.toml"),"project");return t.found?t:be()}async function Po(s,e){let n=process.env.CODEX_HOME||de(Ve(),".codex"),t=new Set;for(let o of[de(n,"config.toml"),de(s,".codex","config.toml")])try{let i=await mt(o,"utf-8");for(let a of rn(i)){if(xo(a.name)||an(a.body))continue;let l=bo(a.name);e.test(l)&&t.add(l)}}catch{}return[...t]}async function ln(s){return Po(s,wo)}async function wt(s,e="copilot"){let n=await ko(e);if(n.found)return n;let t=process.env.COPILOT_HOME||de(Ve(),".copilot"),o=await ft(de(t,"mcp-config.json"),"user");if(o.found)return o;let i=await ft(de(s,".mcp.json"),"mcp.json");if(i.found)return i;let a=await ft(de(s,".github","mcp.json"),"mcp.json");return a.found?a:be()}async function ko(s){try{let e=await new Promise((n,t)=>{vo(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return cn(JSON.parse(e),"user")}catch{return be()}}async function ft(s,e){let n=await Ke(s);return cn(n,e)}function cn(s,e){if(!s||typeof s!="object")return be();let n=s,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=$e(t);return o?Pe(o,e):be()}async function on(s,e){try{let n=await mt(s,"utf-8"),t=rn(n);for(let o of t)if(gt.test(o.name)){let i=an(o.body);return Pe(o.name,e,i)}}catch{}return be()}import{execFile as dn}from"child_process";import{mkdir as Io,readFile as un,writeFile as pn}from"fs/promises";import{homedir as hn}from"os";import{dirname as Mo,join as St}from"path";var bt="https://mcp.popmelt.com/mcp";async function fn(s=bt){let e=St(hn(),".claude.json"),n;try{let o=await un(e,"utf-8");n=JSON.parse(o)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let o of Object.keys(t))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:s},await pn(e,JSON.stringify(n,null,2)+`
370
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function mn(s=bt){let e=process.env.CODEX_HOME||St(hn(),".codex"),n=St(e,"config.toml"),t;try{t=await un(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Io(Mo(n),{recursive:!0});let o=`
371
371
  [mcp_servers.popmelt]
372
372
  url = "${s}"
373
- `;return await un(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function mn(s=bt,e="copilot"){let n=await So(e);if(bo(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{ln(e,["mcp","add","--transport","http","--json","popmelt",s],{encoding:"utf-8",timeout:1e4},i=>{if(i){o(i);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function So(s){try{let e=await new Promise((n,t)=>{ln(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return JSON.parse(e)}catch{return null}}function bo(s){if(!s||typeof s!="object")return!1;let e=s,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}async function Ve(s){let n=(s.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],o=await xo(s),i=Buffer.from(`--${t}`),a=Buffer.from(`--${t}--`),c,f,x,b,M,O,$,G,z,w,B,Y,L=[],q=[],D=0,K=[];for(;D<o.length;){let k=o.indexOf(i,D);if(k===-1)break;let J=k+i.length;if(o.slice(k,k+a.length).equals(a))break;let P=J;o[P]===13&&o[P+1]===10&&(P+=2);let m=o.indexOf(`\r
373
+ `;return await pn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function gn(s=bt,e="copilot"){let n=await Ro(e);if(Eo(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{dn(e,["mcp","add","--transport","http","--json","popmelt",s],{encoding:"utf-8",timeout:1e4},i=>{if(i){o(i);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function Ro(s){try{let e=await new Promise((n,t)=>{dn(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return JSON.parse(e)}catch{return null}}function Eo(s){if(!s||typeof s!="object")return!1;let e=s,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}async function Ze(s){let n=(s.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],o=await To(s),i=Buffer.from(`--${t}`),a=Buffer.from(`--${t}--`),l,f,k,b,R,O,$,q,j,S,F,K,L=[],X=[],D=0,Z=[];for(;D<o.length;){let P=o.indexOf(i,D);if(P===-1)break;let N=P+i.length;if(o.slice(P,P+a.length).equals(a))break;let I=N;o[I]===13&&o[I+1]===10&&(I+=2);let m=o.indexOf(`\r
374
374
  \r
375
- `,P);if(m===-1)break;let W=o.slice(P,m).toString("utf-8"),A=m+4,g=o.indexOf(i,A),T=g!==-1?g-2:o.length;K.push({headers:W,body:o.slice(A,T)}),D=g!==-1?g:o.length}for(let k of K){let J=k.headers.match(/name="([^"]+)"/);if(!J)continue;let P=J[1];if(P==="screenshot")c=k.body;else if(P==="feedback")f=k.body.toString("utf-8");else if(P==="color")x=k.body.toString("utf-8");else if(P==="provider")b=k.body.toString("utf-8");else if(P==="model")M=k.body.toString("utf-8");else if(P==="goal")O=k.body.toString("utf-8");else if(P==="pageUrl")$=k.body.toString("utf-8");else if(P==="viewport")G=k.body.toString("utf-8");else if(P==="planId")z=k.body.toString("utf-8");else if(P==="manifest")w=k.body.toString("utf-8");else if(P==="tasks")B=k.body.toString("utf-8");else if(P==="sourceId")Y=k.body.toString("utf-8");else if(P.startsWith("screenshot-")){let m=P.slice(11);try{let W=decodeURIComponent(m);q.push({pathname:W,data:k.body})}catch{}}else if(P.startsWith("image-")){let m=P.split("-"),W=parseInt(m[m.length-1],10),A=m.slice(1,-1).join("-");A&&!isNaN(W)&&L.push({annotationId:A,index:W,data:k.body})}}if(!c)throw new Error("Missing screenshot field");return f||(f=""),{screenshot:c,feedback:f,color:x,provider:b,model:M,goal:O,pageUrl:$,viewport:G,planId:z,manifest:w,tasks:B,sourceId:Y,pastedImages:L,pageScreenshots:q}}function xo(s){return new Promise((e,n)=>{let t=[];s.on("data",o=>t.push(o)),s.on("end",()=>e(Buffer.concat(t))),s.on("error",n)})}function $e(s,e){let n=[];if(s.annotations.length>0){n.push("## Annotations");for(let t of s.annotations){let o=t.elements.map(c=>{let f=[c.selector];return c.reactComponent&&f.push(`(${c.reactComponent})`),f.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${o||"none"}`);let a=e?.[t.id];if(a&&a.length>0)for(let c of a)n.push(` Attached image: use the Read tool to view ${c}`)}}if(s.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of s.styleModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${o}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if(s.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of s.spacingTokenChanges){n.push(`
375
+ `,I);if(m===-1)break;let H=o.slice(I,m).toString("utf-8"),A=m+4,v=o.indexOf(i,A),C=v!==-1?v-2:o.length;Z.push({headers:H,body:o.slice(A,C)}),D=v!==-1?v:o.length}for(let P of Z){let N=P.headers.match(/name="([^"]+)"/);if(!N)continue;let I=N[1];if(I==="screenshot")l=P.body;else if(I==="feedback")f=P.body.toString("utf-8");else if(I==="color")k=P.body.toString("utf-8");else if(I==="provider")b=P.body.toString("utf-8");else if(I==="model")R=P.body.toString("utf-8");else if(I==="goal")O=P.body.toString("utf-8");else if(I==="pageUrl")$=P.body.toString("utf-8");else if(I==="viewport")q=P.body.toString("utf-8");else if(I==="planId")j=P.body.toString("utf-8");else if(I==="manifest")S=P.body.toString("utf-8");else if(I==="tasks")F=P.body.toString("utf-8");else if(I==="sourceId")K=P.body.toString("utf-8");else if(I.startsWith("screenshot-")){let m=I.slice(11);try{let H=decodeURIComponent(m);X.push({pathname:H,data:P.body})}catch{}}else if(I.startsWith("image-")){let m=I.split("-"),H=parseInt(m[m.length-1],10),A=m.slice(1,-1).join("-");A&&!isNaN(H)&&L.push({annotationId:A,index:H,data:P.body})}}if(!l)throw new Error("Missing screenshot field");return f||(f=""),{screenshot:l,feedback:f,color:k,provider:b,model:R,goal:O,pageUrl:$,viewport:q,planId:j,manifest:S,tasks:F,sourceId:K,pastedImages:L,pageScreenshots:X}}function To(s){return new Promise((e,n)=>{let t=[];s.on("data",o=>t.push(o)),s.on("end",()=>e(Buffer.concat(t))),s.on("error",n)})}function _e(s,e){let n=[];if(s.annotations.length>0){n.push("## Annotations");for(let t of s.annotations){let o=t.elements.map(l=>{let f=[l.selector];return l.reactComponent&&f.push(`(${l.reactComponent})`),f.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${o||"none"}`);let a=e?.[t.id];if(a&&a.length>0)for(let l of a)n.push(` Attached image: use the Read tool to view ${l}`)}}if(s.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of s.styleModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${o}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if(s.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of s.spacingTokenChanges){n.push(`
376
376
  ### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let o of t.affectedElements){let i=o.reactComponent?` (${o.reactComponent})`:"";o.matchedClass&&o.suggestedClass?n.push(`- ${o.selector}${i}: \`${o.matchedClass}\` \u2192 \`${o.suggestedClass}\``):n.push(`- ${o.selector}${i}: ${o.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${o.className}"`)}}}if(s.inspectedElement){let t=s.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let o=[t.selector];t.reactComponent&&o.push(`(${t.reactComponent})`),t.context&&o.push(`in ${t.context}`),t.textContent&&o.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${o.join(" ")}`)}return n.join(`
377
- `)}function gn(s,e,n){let t=[],i=new Set(e.annotations.map(a=>a.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!i&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let a=0;for(let c of n.threadHistory)if(c.role==="human")a++,c.replyToQuestion?(t.push(`### Round ${a} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${a} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${a} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${a} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let f of c.resolutions){let x=f.finalScope??f.inferredScope,b=x?` [${x.breadth} ${x.target}]`:"";t.push(`- ${f.annotationId}: ${f.status}${b} \u2014 ${f.summary}`),f.filesModified&&f.filesModified.length>0&&t.push(` Files: ${f.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&t.push(`Tools used: ${c.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let a=n.designModel.rules;if(Array.isArray(a)&&a.length>0)if(t.push(""),t.push("Rules:"),a.length>0&&typeof a[0]=="object"&&a[0]!==null&&"scope"in a[0]){let b=new Map;for(let M of a)if(typeof M=="object"&&M!==null&&"text"in M){let O=M,$=O.scope||"general";b.has($)||b.set($,[]),b.get($).push(O.text)}for(let[M,O]of b){t.push(`**${M.charAt(0).toUpperCase()+M.slice(1)}**`);for(let $ of O)t.push(`- ${$}`)}}else for(let b of a)typeof b=="string"&&t.push(`- ${b}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let f=n.designModel.components;f&&typeof f=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(f,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code.")),i){let a=n?.screenshotPaths??{},c=new Map;for(let f of e.annotations){let x=f.pathname||new URL(e.url).pathname;c.has(x)||c.set(x,[]),c.get(x).push(f)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[f,x]of c){t.push(""),t.push(`## Page: ${f}`);let b=a[f];b&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${b}`):!b&&n?.provider!=="codex"&&(Object.keys(a).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${s}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let M={...e,annotations:x,styleModifications:e.styleModifications},O=$e(M,n?.imagePaths);O&&(t.push(""),t.push(O))}}else{let a=$e(e,n?.imagePaths);a&&(t.push(""),t.push(a))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
378
- `)}function vn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function yn(s,e,n,t){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=e.find(a=>a.role==="human"&&a.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),e.length>0){o.push(""),o.push("## Conversation History");let a=0;for(let c of e)c.role==="human"?(a++,c.replyToQuestion?(o.push(`### Round ${a} (human) \u2014 reply`),o.push(`"${c.replyToQuestion}"`)):(o.push(`### Round ${a} (human)`),c.feedbackSummary&&o.push(`Annotations: ${c.feedbackSummary}`))):c.question?(o.push(`### Round ${a} (assistant) \u2014 question`),o.push(`"${c.question}"`)):(o.push(`### Round ${a} (assistant)`),c.responseText&&o.push(`Response: ${c.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let a of t)o.push(`Attached image: use the Read tool to view the image at: ${a}`)}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(`
379
- `)}function Po(s){if(typeof s!="object"||s===null)return!1;let e=s;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function ko(s){if(typeof s!="object"||s===null||typeof s.annotationId!="string"||s.status!=="resolved"&&s.status!=="needs_review"||typeof s.summary!="string")return!1;let e=s;for(let n of["declaredScope","inferredScope","finalScope"])if(e[n]!==void 0&&e[n]!==null&&!Po(e[n]))return!1;return!0}function wn(s){let e=s.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!e||!e[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(ko):[]}catch{return[]}}function Sn(s){let e=s.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let o=t;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}import{execFile as Io}from"child_process";import{readdir as Mo,readFile as Eo,stat as Ro}from"fs/promises";import{homedir as _e}from"os";import{join as me}from"path";var et=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static"},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static"}],Oe=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],De={id:"",label:"Default",source:"cli"},To=/^\s*-\s+"([^"]+)"/;function Co(s){let e=[],n=!1;for(let t of s.split(`
380
- `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let o=t.match(To);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:xt(i),source:"cli"})}return tt([De,...e])}function Ao(s){let e=JSON.parse(s);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,o)=>{let i=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,a=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-a}).flatMap(t=>{let o=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!o)return[];let i=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():xt(o);return[{id:o,label:i,source:"cli"}]})}function $o(s){let e=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return tt(e.map(n=>({id:n,label:xt(n),source:"cli"})))}function xt(s){if(!s)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=s.replace(/-\d{8,}$/,"");if(e[s])return e[s];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let i=t[1]==="sonnet"?"Sonn":No(t[1]),a=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${i}${a}${t[4]?" Fast":""}`}let o=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let i=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${i}`:o[3]==="codex"?`Codex ${i}`:o[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function bn(s="copilot"){let e=await Ze(s,["help","config"]),n=Co(e);return n.length>1?n:[De]}async function xn(s="codex"){let e=await Ze(s,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||me(_e(),".codex");return kn(me(t,"models_cache.json"))}),n=Ao(e);return n.length>0?tt([...n,...Oe]):Oe}async function Pn(s="claude"){let e=me(_e(),".claude"),n=[me(_e(),".claude","stats-cache.json"),me(_e(),".claude","settings.json"),me(_e(),".claude.json"),me(e,"cache","changelog.md")],[t,o,i]=await Promise.all([Ze(s,["--help"]).catch(()=>""),Ze(s,["--version"]).catch(()=>""),_o(e).catch(()=>[])]),a=Do([...n,...i]),c=await Promise.all(a.map(x=>kn(x).catch(()=>""))),f=$o([t,o,...c].join(`
381
- `));return tt([...et,...f])}function Ze(s,e,n=5e3){return new Promise((t,o)=>{Io(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function kn(s){return Eo(s,"utf-8")}async function _o(s){let e=[me(s,"projects"),me(s,"telemetry")],n=[];for(let t of e)await In(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function In(s,e,n){if(n<0)return;let t;try{t=await Mo(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=me(s,o.name);if(o.isDirectory()){await In(i,e,n-1);return}if(!(!o.isFile()||!Oo(o.name)))try{let a=await Ro(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function Oo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function tt(s){let e=new Set,n=[];for(let t of s)e.has(t.id)||(e.add(t.id),n.push(t));return n}function Do(s){return[...new Set(s)]}function No(s){return s.charAt(0).toUpperCase()+s.slice(1)}var nt=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let o=this.bufferEvent(n,e);for(let i of this.listeners)i(o,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let o={...n,seq:t.nextSeq++};return t.events.push(o),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),o}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!t)return null;let a=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:a,currentSeq:t.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(e,n,t){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(o=>{let i=!1,a=()=>{i||(i=!0,o())};t.on("exit",a),t.on("error",a),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(a,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="materialize_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{mkdir as Jo,readFile as zo,writeFile as jo}from"fs/promises";import{dirname as Fo,join as Bo}from"path";var Uo={version:1,threads:{}},st=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=Bo(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await zo(this.filePath,"utf-8"),n=JSON.parse(e);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...Uo,threads:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>t.has(a)))return o;return null}async createThread(e,n){let t=await this.load(),o={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=o,await this.persist(),o}async appendMessage(e,n){let o=(await this.load()).threads[e];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((o,i)=>i.updatedAt-o.updatedAt),t.slice(0,e).map(o=>{let a=o.messages.find(c=>c.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await Jo(Fo(this.filePath),{recursive:!0}),await jo(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function Mn(s){return Wo(s).slice(0,12)}var Lo=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Wo(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):Ho(s),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let O=7;O>=0;O--)e.push(n/Math.pow(2,O*8)&255);let t=1779033703,o=3144134277,i=1013904242,a=2773480762,c=1359893119,f=2600822924,x=528734635,b=1541459225,M=new Array(64);for(let O=0;O<e.length;O+=64){for(let D=0;D<16;D++){let K=O+D*4;M[D]=(e[K]<<24|e[K+1]<<16|e[K+2]<<8|e[K+3])>>>0}for(let D=16;D<64;D++){let K=ge(M[D-15],7)^ge(M[D-15],18)^M[D-15]>>>3,k=ge(M[D-2],17)^ge(M[D-2],19)^M[D-2]>>>10;M[D]=M[D-16]+K+M[D-7]+k>>>0}let $=t,G=o,z=i,w=a,B=c,Y=f,L=x,q=b;for(let D=0;D<64;D++){let K=ge(B,6)^ge(B,11)^ge(B,25),k=B&Y^~B&L,J=q+K+k+Lo[D]+M[D]>>>0,P=ge($,2)^ge($,13)^ge($,22),m=$&G^$&z^G&z,W=P+m>>>0;q=L,L=Y,Y=B,B=w+J>>>0,w=z,z=G,G=$,$=J+W>>>0}t=t+$>>>0,o=o+G>>>0,i=i+z>>>0,a=a+w>>>0,c=c+B>>>0,f=f+Y>>>0,x=x+L>>>0,b=b+q>>>0}return[t,o,i,a,c,f,x,b].map(O=>O.toString(16).padStart(8,"0")).join("")}function ge(s,e){return s>>>e|s<<32-e}function Ho(s){let e=[];for(let n=0;n<s.length;n++){let t=s.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var En="0.7.7";var nr=1111,sr=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],or=1800*1e3,rr=3600*1e3;function $n(s){if(!s)return!1;try{let e=new URL(s);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function ir(s){let e=[];for(let n of s)if(n.type==="delta"){let t=n.text;if(!t)continue;let o=e[e.length-1];o&&o.kind==="text"?o.text+=t:e.push({kind:"text",text:t})}else if(n.type==="tool_use"){let t=n.tool||"",o=n.file??void 0,i=n.content??void 0,a=o?o.split("/").pop()??o:void 0,c;switch(t){case"Read":c=a?`Reading ${a}`:"Reading file";break;case"Edit":c=a?`Editing ${a}`:"Editing file";break;case"Write":c=a?`Writing ${a}`:"Writing file";break;case"Bash":c=i?i.split(`
382
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":c="Searching files";break;case"Grep":c="Searching code";break;case"WebFetch":c="Fetching page";break;case"WebSearch":c="Searching web";break;default:c=t?`Using ${t}`:"tool";break}let f=o??i??void 0,x=e[e.length-1];x&&x.kind==="tool_group"&&x.tool===t?x.items.push({label:c,detail:f}):e.push({kind:"tool_group",tool:t,items:[{label:c,detail:f}]})}return e}function ar(s,e){if(s.processedIds.length===0&&s.success)return"No unmaterialized pattern decisions were ready for model materialization.";let n=[];return s.success?n.push("Model suggestion"):n.push("Model materialization failed."),s.proposalId&&(n.push(""),n.push(`Proposal: ${s.proposalId}`),n.push("Review this model suggestion before applying it to the local taste model.")),e&&(n.push(""),n.push(`Run: ${e.id}`),n.push(`Decisions: ${e.decisionIds.length}`),e.promptStats&&n.push(`Prompt: ${e.promptStats.estimatedTokens.toLocaleString()} estimated tokens from ${e.promptStats.decisionCount}/${e.promptStats.totalCandidateDecisionCount} candidate decisions`),e.outputStats&&n.push(`Model output: ${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components`)),s.error&&(n.push(""),n.push(`Error: ${s.error}`),n.push("The selected decisions were not marked applied and remain visible in materialization history.")),n.join(`
383
- `)}function cr(s,e){let n=s.headers.origin;$n(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function y(s,e,n){s.writeHead(e,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}function lr(s,e){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function dr(s,e){if(!s)return e;let n=s.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,o,i]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(o,16)};${parseInt(i,16)}m${e}\x1B[0m`}function rt(s,e){try{s.res.write(`event: ${e.type}
377
+ `)}function yn(s,e,n){let t=[],i=new Set(e.annotations.map(a=>a.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!i&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let a=0;for(let l of n.threadHistory)if(l.role==="human")a++,l.replyToQuestion?(t.push(`### Round ${a} (human) \u2014 reply`),t.push(`"${l.replyToQuestion}"`)):(t.push(`### Round ${a} (human)`),l.feedbackSummary&&t.push(`Annotations: ${l.feedbackSummary}`),l.annotationIds&&l.annotationIds.length>0&&t.push(`Annotation IDs: ${l.annotationIds.join(", ")}`));else if(l.question)t.push(`### Round ${a} (assistant) \u2014 question`),t.push(`"${l.question}"`);else{if(t.push(`### Round ${a} (assistant)`),l.responseText&&t.push(`Response: ${l.responseText}`),l.resolutions&&l.resolutions.length>0)for(let f of l.resolutions){let k=f.finalScope??f.inferredScope,b=k?` [${k.breadth} ${k.target}]`:"";t.push(`- ${f.annotationId}: ${f.status}${b} \u2014 ${f.summary}`),f.filesModified&&f.filesModified.length>0&&t.push(` Files: ${f.filesModified.join(", ")}`)}l.toolsUsed&&l.toolsUsed.length>0&&t.push(`Tools used: ${l.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let a=n.designModel.rules;if(Array.isArray(a)&&a.length>0)if(t.push(""),t.push("Rules:"),a.length>0&&typeof a[0]=="object"&&a[0]!==null&&"scope"in a[0]){let b=new Map;for(let R of a)if(typeof R=="object"&&R!==null&&"text"in R){let O=R,$=O.scope||"general";b.has($)||b.set($,[]),b.get($).push(O.text)}for(let[R,O]of b){t.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let $ of O)t.push(`- ${$}`)}}else for(let b of a)typeof b=="string"&&t.push(`- ${b}`);let l=n.designModel.tokens;l&&typeof l=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(l,null,2)),t.push("```"));let f=n.designModel.components;f&&typeof f=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(f,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code.")),i){let a=n?.screenshotPaths??{},l=new Map;for(let f of e.annotations){let k=f.pathname||new URL(e.url).pathname;l.has(k)||l.set(k,[]),l.get(k).push(f)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[f,k]of l){t.push(""),t.push(`## Page: ${f}`);let b=a[f];b&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${b}`):!b&&n?.provider!=="codex"&&(Object.keys(a).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${s}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let R={...e,annotations:k,styleModifications:e.styleModifications},O=_e(R,n?.imagePaths);O&&(t.push(""),t.push(O))}}else{let a=_e(e,n?.imagePaths);a&&(t.push(""),t.push(a))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
378
+ `)}function vn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function xt(s,e,n,t){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=e.find(a=>a.role==="human"&&a.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),e.length>0){o.push(""),o.push("## Conversation History");let a=0;for(let l of e)l.role==="human"?(a++,l.replyToQuestion?(o.push(`### Round ${a} (human) \u2014 reply`),o.push(`"${l.replyToQuestion}"`)):(o.push(`### Round ${a} (human)`),l.feedbackSummary&&o.push(`Annotations: ${l.feedbackSummary}`))):l.question?(o.push(`### Round ${a} (assistant) \u2014 question`),o.push(`"${l.question}"`)):(o.push(`### Round ${a} (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."),t&&t.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let a of t)o.push(`Attached image: use the Read tool to view the image at: ${a}`)}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(`
379
+ `)}function Co(s){if(typeof s!="object"||s===null)return!1;let e=s;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function Ao(s){if(typeof s!="object"||s===null||typeof s.annotationId!="string"||s.status!=="resolved"&&s.status!=="needs_review"||typeof s.summary!="string")return!1;let e=s;for(let n of["declaredScope","inferredScope","finalScope"])if(e[n]!==void 0&&e[n]!==null&&!Co(e[n]))return!1;return!0}function wn(s){let e=s.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!e||!e[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(Ao):[]}catch{return[]}}function Sn(s){let e=s.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let o=t;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}import{execFile as $o}from"child_process";import{readdir as _o,readFile as Oo,stat as Do}from"fs/promises";import{homedir as Oe}from"os";import{join as ge}from"path";var tt=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static"},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static"}],De=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],Ne={id:"",label:"Default",source:"cli"},No=/^\s*-\s+"([^"]+)"/;function Jo(s){let e=[],n=!1;for(let t of s.split(`
380
+ `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let o=t.match(No);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:Pt(i),source:"cli"})}return nt([Ne,...e])}function jo(s){let e=JSON.parse(s);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,o)=>{let i=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,a=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-a}).flatMap(t=>{let o=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!o)return[];let i=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():Pt(o);return[{id:o,label:i,source:"cli"}]})}function zo(s){let e=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return nt(e.map(n=>({id:n,label:Pt(n),source:"cli"})))}function Pt(s){if(!s)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=s.replace(/-\d{8,}$/,"");if(e[s])return e[s];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let i=t[1]==="sonnet"?"Sonn":Lo(t[1]),a=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${i}${a}${t[4]?" Fast":""}`}let o=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let i=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${i}`:o[3]==="codex"?`Codex ${i}`:o[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function bn(s="copilot"){let e=await et(s,["help","config"]),n=Jo(e);return n.length>1?n:[Ne]}async function xn(s="codex"){let e=await et(s,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||ge(Oe(),".codex");return kn(ge(t,"models_cache.json"))}),n=jo(e);return n.length>0?nt([...n,...De]):De}async function Pn(s="claude"){let e=ge(Oe(),".claude"),n=[ge(Oe(),".claude","stats-cache.json"),ge(Oe(),".claude","settings.json"),ge(Oe(),".claude.json"),ge(e,"cache","changelog.md")],[t,o,i]=await Promise.all([et(s,["--help"]).catch(()=>""),et(s,["--version"]).catch(()=>""),Bo(e).catch(()=>[])]),a=Uo([...n,...i]),l=await Promise.all(a.map(k=>kn(k).catch(()=>""))),f=zo([t,o,...l].join(`
381
+ `));return nt([...tt,...f])}function et(s,e,n=5e3){return new Promise((t,o)=>{$o(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function kn(s){return Oo(s,"utf-8")}async function Bo(s){let e=[ge(s,"projects"),ge(s,"telemetry")],n=[];for(let t of e)await In(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function In(s,e,n){if(n<0)return;let t;try{t=await _o(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=ge(s,o.name);if(o.isDirectory()){await In(i,e,n-1);return}if(!(!o.isFile()||!Fo(o.name)))try{let a=await Do(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function Fo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function nt(s){let e=new Set,n=[];for(let t of s)e.has(t.id)||(e.add(t.id),n.push(t));return n}function Uo(s){return[...new Set(s)]}function Lo(s){return s.charAt(0).toUpperCase()+s.slice(1)}var st=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let t=n>=0?n+1:0,o=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),o}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let o=this.bufferEvent(n,e);for(let i of this.listeners)i(o,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let o={...n,seq:t.nextSeq++};return t.events.push(o),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),o}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!t)return null;let a=n<0?t.events:t.events.filter(l=>l.seq>n);return{jobId:e,events:a,currentSeq:t.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(e,n,t){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(o=>{let i=!1,a=()=>{i||(i=!0,o())};t.on("exit",a),t.on("error",a),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(a,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="materialize_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{mkdir as Wo,readFile as Ho,writeFile as Go}from"fs/promises";import{dirname as qo,join as Qo}from"path";var Xo={version:1,threads:{}},ot=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=Qo(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await Ho(this.filePath,"utf-8"),n=JSON.parse(e);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...Xo,threads:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>t.has(a)))return o;return null}async createThread(e,n){let t=await this.load(),o={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=o,await this.persist(),o}async appendMessage(e,n){let o=(await this.load()).threads[e];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async appendMessageBeforeQueuedReplies(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=o.messages.findIndex(a=>a.role==="human"&&!!a.replyToQuestion&&a.queued);i>=0?o.messages.splice(i,0,n):o.messages.push(n),o.updatedAt=Date.now(),await this.persist()}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return;let a=i.messages.filter(l=>l.jobId===n);if(a.length!==0){for(let l of a)Object.assign(l,t);i.updatedAt=Date.now(),await this.persist()}}async addElementIdentifiers(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((o,i)=>i.updatedAt-o.updatedAt),t.slice(0,e).map(o=>{let a=o.messages.find(l=>l.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await Wo(qo(this.filePath),{recursive:!0}),await Go(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function Mn(s){return Ko(s).slice(0,12)}var Yo=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Ko(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):Vo(s),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let O=7;O>=0;O--)e.push(n/Math.pow(2,O*8)&255);let t=1779033703,o=3144134277,i=1013904242,a=2773480762,l=1359893119,f=2600822924,k=528734635,b=1541459225,R=new Array(64);for(let O=0;O<e.length;O+=64){for(let D=0;D<16;D++){let Z=O+D*4;R[D]=(e[Z]<<24|e[Z+1]<<16|e[Z+2]<<8|e[Z+3])>>>0}for(let D=16;D<64;D++){let Z=ye(R[D-15],7)^ye(R[D-15],18)^R[D-15]>>>3,P=ye(R[D-2],17)^ye(R[D-2],19)^R[D-2]>>>10;R[D]=R[D-16]+Z+R[D-7]+P>>>0}let $=t,q=o,j=i,S=a,F=l,K=f,L=k,X=b;for(let D=0;D<64;D++){let Z=ye(F,6)^ye(F,11)^ye(F,25),P=F&K^~F&L,N=X+Z+P+Yo[D]+R[D]>>>0,I=ye($,2)^ye($,13)^ye($,22),m=$&q^$&j^q&j,H=I+m>>>0;X=L,L=K,K=F,F=S+N>>>0,S=j,j=q,q=$,$=N+H>>>0}t=t+$>>>0,o=o+q>>>0,i=i+j>>>0,a=a+S>>>0,l=l+F>>>0,f=f+K>>>0,k=k+L>>>0,b=b+X>>>0}return[t,o,i,a,l,f,k,b].map(O=>O.toString(16).padStart(8,"0")).join("")}function ye(s,e){return s>>>e|s<<32-e}function Vo(s){let e=[];for(let n=0;n<s.length;n++){let t=s.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var Rn={name:"@popmelt.com/core",version:"0.8.0",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .",prepublishOnly:"pnpm run build",typecheck:"tsc --noEmit"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=0.400.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{},devDependencies:{"@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0","lucide-react":"^0.487.0",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3"}};var En=Rn.version;var dr=1111,ur=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],pr=1800*1e3,hr=3600*1e3;function An(s){return s.length<=1?s[0]??"":["The developer sent these queued steering messages while you were working:","",...s.map((e,n)=>`${n+1}. ${e}`)].join(`
382
+ `)}function On(s){if(!s)return!1;try{let e=new URL(s);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function fr(s){let e=[];for(let n of s)if(n.type==="delta"){let t=n.text;if(!t)continue;let o=e[e.length-1];o&&o.kind==="text"?o.text+=t:e.push({kind:"text",text:t})}else if(n.type==="tool_use"){let t=n.tool||"",o=n.file??void 0,i=n.content??void 0,a=o?o.split("/").pop()??o:void 0,l;switch(t){case"Read":l=a?`Reading ${a}`:"Reading file";break;case"Edit":l=a?`Editing ${a}`:"Editing file";break;case"Write":l=a?`Writing ${a}`:"Writing file";break;case"Bash":l=i?i.split(`
383
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=t?`Using ${t}`:"tool";break}let f=o??i??void 0,k=e[e.length-1];k&&k.kind==="tool_group"&&k.tool===t?k.items.push({label:l,detail:f}):e.push({kind:"tool_group",tool:t,items:[{label:l,detail:f}]})}return e}function mr(s,e){if(s.processedIds.length===0&&s.success)return"No unmaterialized pattern decisions were ready for model materialization.";let n=[];return s.success?n.push("Model suggestion ready."):n.push("Model materialization failed."),s.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),s.error&&(n.push(""),n.push(`Error: ${s.error}`),n.push("The selected decisions were not marked applied and remain visible in materialization history.")),n.join(`
384
+ `)}function gr(s,e){let n=s.headers.origin;On(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function y(s,e,n){s.writeHead(e,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}function yr(s,e){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function vr(s,e){if(!s)return e;let n=s.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,o,i]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(o,16)};${parseInt(i,16)}m${e}\x1B[0m`}function it(s,e){try{s.res.write(`event: ${e.type}
384
385
  data: ${JSON.stringify(e)}
385
386
 
386
- `)}catch{}}function Je(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function ur(s){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),t=await fetch(`http://127.0.0.1:${s}/status`,{signal:e.signal});return clearTimeout(n),t.ok?await t.json():null}catch{return null}}function pr(s,e){return new Promise((n,t)=>{let o=a=>{s.removeListener("listening",i),t(a)},i=()=>{s.removeListener("error",o),n()};s.once("error",o),s.once("listening",i),s.listen(e,"127.0.0.1")})}function Cn(s){try{let e=it("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=it("git",["status","--porcelain","--untracked-files=all",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),o=it("git",["diff","HEAD",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Go("sha256").update(`${e}
387
+ `)}catch{}}function je(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function wr(s){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),t=await fetch(`http://127.0.0.1:${s}/status`,{signal:e.signal});return clearTimeout(n),t.ok?await t.json():null}catch{return null}}function Sr(s,e){return new Promise((n,t)=>{let o=a=>{s.removeListener("listening",i),t(a)},i=()=>{s.removeListener("error",o),n()};s.once("error",o),s.once("listening",i),s.listen(e,"127.0.0.1")})}function $n(s){try{let e=at("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=at("git",["status","--porcelain","--untracked-files=all",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),o=at("git",["diff","HEAD",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return er("sha256").update(`${e}
387
388
  ${t}
388
- ${o}`).digest("hex").slice(0,16)}catch{return}}async function _n(s={}){let e=s.port??nr,n=s.projectRoot??process.cwd(),t=await Xo(n).catch(()=>n),o=Mn(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),a=s.tempDir??fe(Zo(),"popmelt-bridge"),c=s.maxTurns??40,f=s.maxBudgetUsd??1,x=[...s.allowedTools??sr],b=s.claudePath??"claude",M=s.copilotPath??"copilot",O=s.provider??"claude",$=s.timeoutMs,G=s.restartMode??"embedded",z=e,w={},B={claude:b,codex:"codex",copilot:M};for(let[r,l]of Object.entries(B))try{let p=l.includes("/")?l:it("which",[l],{encoding:"utf-8"}).trim();w[r]={available:!0,path:p}}catch{w[r]={available:!1,path:null}}function Y(r,l){return new Promise(p=>{let u=Rn(l,["--version"],{stdio:["ignore","ignore","ignore"]}),h=!1,d=S=>{h||(h=!0,p(S))},I=setTimeout(()=>{u.kill("SIGTERM"),d(!0)},5e3);u.on("error",()=>{clearTimeout(I),d(!1)}),u.on("close",S=>{clearTimeout(I),d(S===0)})})}await Promise.all([(async()=>{w.claude&&(w.claude.models=w.claude.available&&w.claude.path?await Pn(w.claude.path).catch(()=>et):et)})(),(async()=>{w.codex&&(w.codex.models=w.codex.available&&w.codex.path?await xn(w.codex.path).catch(()=>Oe):Oe)})(),(async()=>{w.copilot&&(w.copilot.models=w.copilot.available&&w.copilot.path?await bn(w.copilot.path).catch(()=>[De]):[De])})()]);let[L,q,D]=await Promise.all([vt(t),yt(t),wt(t,w.copilot?.path??M)]),K=await an(t);w.claude&&(w.claude.mcp=L),w.codex&&(w.codex.mcp=q),w.copilot&&(w.copilot.mcp=D),L.found&&L.name&&x.push(`mcp__${L.name}__*`),await qo(a,{recursive:!0}),An(a).catch(()=>{});let k=new nt(1),J=new Xe,P=new Set,m=new st(t),W=new Le(t),A=new We(t),g=new qe(t,W,{claudePath:b,provider:O,timeoutMs:$,onEvent:r=>{for(let l of P)rt(l,r)}}),T=20,ee=300*1e3,R=[];function ie(){let r=Date.now()-ee;for(;R.length>0&&(R[0].completedAt<r||R.length>T);)R.shift()}let V=new Map,ne=null,Pe;k.addListener((r,l,p)=>{for(let u of P)(!p||!u.sourceId||u.sourceId===p)&&rt(u,r)}),J.addListener((r,l,p)=>{for(let u of P)(!p||!u.sourceId||u.sourceId===p)&&rt(u,r)}),J.setProcessor(async r=>{let l=r.provider??O,p=await g.run({provider:l,model:r.model,threadId:r.threadId}),u=await g.loadRuns(),h=p.runId?u.runs.find(S=>S.id===p.runId):void 0,d=p.proposalId?await g.findModelProposal(p.proposalId):null,I=[ar(p,h),d?["",d.title,d.summary].join(`
389
- `):""].filter(Boolean).join(`
390
- `);r.threadId&&await m.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:I,model:r.model,provider:l}),p.success?(r.status="done",r.result=I,J.broadcast({type:"done",jobId:r.id,success:!0,responseText:I,threadId:r.threadId},r.id,r.sourceId),R.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),ie()):(r.status="error",r.error=p.error??"Materialization failed",J.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:l,model:r.model},r.id,r.sourceId),R.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),ie())}),k.setProcessor(async r=>{let l=r._replyPrompt,p=r._replyImagePaths,u=r.provider??O,h;if(r.threadId){let E=await m.getThread(r.threadId);if(E){for(let C=E.messages.length-1;C>=0;C--)if(E.messages[C].sessionId){h=E.messages[C].sessionId;break}}}let d;if(h&&l){let E=(await m.getThread(r.threadId))?.messages.filter(X=>X.role==="human").pop();if(d=E?.replyToQuestion||E?.feedbackSummary||"",p&&p.length>0){d+=`
389
+ ${o}`).digest("hex").slice(0,16)}catch{return}}async function Dn(s={}){let e=s.port??dr,n=s.projectRoot??process.cwd(),t=await sr(n).catch(()=>n),o=Mn(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),a=s.tempDir??me(ar(),"popmelt-bridge"),l=s.maxTurns??40,f=s.maxBudgetUsd??1,k=[...s.allowedTools??ur],b=s.claudePath??"claude",R=s.copilotPath??"copilot",O=s.provider??"claude",$=s.timeoutMs,q=s.restartMode??"embedded",j=e,S={},F={claude:b,codex:"codex",copilot:R};for(let[r,c]of Object.entries(F))try{let p=c.includes("/")?c:at("which",[c],{encoding:"utf-8"}).trim();S[r]={available:!0,path:p}}catch{S[r]={available:!1,path:null}}function K(r,c){return new Promise(p=>{let u=Tn(c,["--version"],{stdio:["ignore","ignore","ignore"]}),h=!1,d=g=>{h||(h=!0,p(g))},M=setTimeout(()=>{u.kill("SIGTERM"),d(!0)},5e3);u.on("error",()=>{clearTimeout(M),d(!1)}),u.on("close",g=>{clearTimeout(M),d(g===0)})})}await Promise.all([(async()=>{S.claude&&(S.claude.models=S.claude.available&&S.claude.path?await Pn(S.claude.path).catch(()=>tt):tt)})(),(async()=>{S.codex&&(S.codex.models=S.codex.available&&S.codex.path?await xn(S.codex.path).catch(()=>De):De)})(),(async()=>{S.copilot&&(S.copilot.models=S.copilot.available&&S.copilot.path?await bn(S.copilot.path).catch(()=>[Ne]):[Ne])})()]);let[L,X,D]=await Promise.all([yt(t),vt(t),wt(t,S.copilot?.path??R)]),Z=await ln(t);S.claude&&(S.claude.mcp=L),S.codex&&(S.codex.mcp=X),S.copilot&&(S.copilot.mcp=D),L.found&&L.name&&k.push(`mcp__${L.name}__*`),await tr(a,{recursive:!0}),_n(a).catch(()=>{});let P=new st(1),N=new Ye,I=new Set,m=new ot(t),H=new We(t),A=new He(t),v=new Qe(t,H,{claudePath:b,provider:O,timeoutMs:$,onEvent:r=>{for(let c of I)it(c,r)}}),C=20,ne=300*1e3,T=[];function ae(){let r=Date.now()-ne;for(;T.length>0&&(T[0].completedAt<r||T.length>C);)T.shift()}let ee=new Map,oe=null,ke;P.addListener((r,c,p)=>{for(let u of I)(!p||!u.sourceId||u.sourceId===p)&&it(u,r)}),N.addListener((r,c,p)=>{for(let u of I)(!p||!u.sourceId||u.sourceId===p)&&it(u,r)}),N.setProcessor(async r=>{let c=r.provider??O,p=await v.run({provider:c,model:r.model,threadId:r.threadId}),u=await v.loadRuns(),h=p.runId?u.runs.find(M=>M.id===p.runId):void 0,d=mr(p,h);r.threadId&&await m.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c}),p.success?(r.status="done",r.result=d,N.broadcast({type:"done",jobId:r.id,success:!0,responseText:d,threadId:r.threadId},r.id,r.sourceId),T.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),ae()):(r.status="error",r.error=p.error??"Materialization failed",N.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),T.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),ae())}),P.setProcessor(async r=>{let c=r,p=c._replyPrompt,u=c._replyText,h=c._replyImagePaths,d=r.provider??O;r.threadId&&u!==void 0&&await m.updateMessage(r.threadId,r.id,{queued:!1});let M;if(r.threadId){let _=await m.getThread(r.threadId);if(_){for(let W=_.messages.length-1;W>=0;W--)if(_.messages[W].sessionId){M=_.messages[W].sessionId;break}}}let g;if(M&&p){if(g=u??p,h&&h.length>0){g+=`
391
390
 
392
- The developer attached reference images with their reply:`;for(let X of p)d+=`
393
- Attached image: use the Read tool to view the image at: ${X}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?d+=`
391
+ The developer attached reference images with their reply:`;for(let _ of h)g+=`
392
+ Attached image: use the Read tool to view the image at: ${_}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?g+=`
394
393
 
395
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:d+=`
394
+ Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:g+=`
396
395
 
397
- 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(h)d=$e(r.feedback,r.imagePaths)+`
396
+ 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)g=_e(r.feedback,r.imagePaths)+`
398
397
 
399
398
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
400
399
 
401
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(u!=="codex"?`
400
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
402
401
 
403
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let E=!l&&r.threadId?await m.getThreadHistory(r.threadId):void 0,C=l?null:await g.loadModel();d=l??gn(r.screenshotPath,r.feedback,{threadHistory:E&&E.length>0?E:void 0,provider:u,imagePaths:r.imagePaths,designModel:C??void 0,screenshotPaths:r.screenshotPaths})}let I=dr(r.color,`[\u22B9 ${z}:${r.id}]`),S=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${I} Reviewing ${S} (provider: ${u})${r.threadId?` (thread: ${r.threadId})`:""}${h?` (resuming: ${h.slice(0,8)})`:""}`);let j=(E,C)=>{E.type==="delta"&&"text"in E?k.accumulateText(C,"response",E.text):E.type==="thinking"&&"text"in E&&k.accumulateText(C,"thinking",E.text),k.broadcast(E,C,r.sourceId)},{process:Q,result:U}=u==="codex"?Ue(r.id,{prompt:d,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:h,model:r.model,onEvent:j}):u==="copilot"?jt(r.id,{prompt:d,projectRoot:t,resumeSessionId:h,model:r.model,timeoutMs:$,copilotPath:w.copilot?.path??M,onEvent:j}):Fe(r.id,{prompt:d,projectRoot:t,maxTurns:c,maxBudgetUsd:f,allowedTools:x,claudePath:b,resumeSessionId:h,model:r.model,timeoutMs:$,onEvent:j});k.setActiveProcess(r.id,Q);let v=await U;if(r.result=v.text,v.success){console.log(`${I} Iteration complete`),v.fileEdits&&v.fileEdits.length>0&&console.log(`${I} Captured ${v.fileEdits.length} file edit(s): ${v.fileEdits.map(N=>`${N.tool} ${N.file_path}`).join(", ")}`),v.editEvents&&v.editEvents.length>0&&console.log(`${I} Captured ${v.editEvents.length} edit event(s): ${v.editEvents.map(N=>`${N.operation} ${N.filePath}`).join(", ")}`),r.status="done";let E=vn(v.text),C=wn(v.text),X=C.some(N=>(N.finalScope??N.inferredScope)?.breadth==="pattern");if(C.length>0&&r.annotationIds&&r.annotationIds.length>0){let N=new Set(r.annotationIds);C.every(F=>N.has(F.annotationId))||(C=C.map((F,H)=>({...F,annotationId:r.annotationIds[H%r.annotationIds.length]})))}let le=v.fileEdits&&v.fileEdits.length>0?v.fileEdits.map(N=>`${N.tool} ${N.file_path.split("/").pop()}`):v.toolsUsed,se=k.getBufferedEvents(r.id),ae=se?ir(se.events):void 0;if(r.threadId&&await m.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:v.text,resolutions:C.length>0?C:void 0,question:E??void 0,sessionId:v.sessionId,toolsUsed:le,editEvents:v.editEvents&&v.editEvents.length>0?v.editEvents:void 0,segments:ae&&ae.length>0?ae:void 0,model:r.model,provider:u}),r.kind!=="run_eval"&&W.captureGitDiff(t).then(async N=>{let Z=Date.now(),F=r.imagePaths?Object.values(r.imagePaths).flat():[],H=[];if(r.imagePaths)for(let[oe,_]of Object.entries(r.imagePaths))for(let re=0;re<_.length;re++)H.push(`screenshots/p-${r.id}-${oe}-${re}.webp`);await W.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:Z,durationMs:Z-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:H,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:u,model:r.model,sessionId:v.sessionId,threadId:r.threadId,responseText:v.text,resolutions:C.length>0?C:[],question:E??void 0,fileEdits:v.fileEdits??[],editEvents:v.editEvents??[],toolsUsed:le,gitDiff:N},r.screenshotPath,F),X&&u!=="copilot"?await Pt({provider:u,model:r.model,threadId:r.threadId,annotationIds:r.annotationIds,sourceId:r.sourceId,reason:`Materialize model \u2014 ${r.feedback.annotations[0]?.instruction??"pattern decision"}`}):X&&console.log(`${I} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&v.text){let N=Qe(v.text);if(N){Array.isArray(N.rules)&&(N.rules=Ce(N.rules));let Z=await g.loadModel();Z&&(!N.tokens&&Z.tokens&&(N.tokens=Z.tokens),!N.components&&Z.components&&(N.components=Z.components)),await g.writeModel(N),console.log(`${I} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&v.text){let N=Wt(v.text),Z=Ht(v.text),F=N??Z;if(F&&F.length>0){let H=await A.writeSynthesized(F),oe=r._proposalId;oe&&await g.attachGeneratedEvals(oe,F.map(_=>_.id)),console.log(`${I} Eval synthesis: wrote ${F.length} ${N?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${H.cases.length} total)`)}}else if(r.kind==="run_eval"&&v.text&&r.evalId&&r.evalRunId){let N=await A.findCase(r.evalId),Z=r._evalRunScope;if(N&&Z){let F=Gt(v.text,N.assertions),H=Date.now();await A.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:H,durationMs:H-r.createdAt,scope:Z,provider:u,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:Cn(t),rawResponse:v.text,...F}),console.log(`${I} Eval run: ${N.title} \u2192 ${F.status}`)}}E&&(console.log(`${I} \u{1F4AC} Question detected: "${E.slice(0,120)}" \u2192 broadcasting to ${P.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),k.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:E,annotationIds:r.annotationIds},r.id,r.sourceId));let ce=Sn(v.text);ce.length>0&&(console.log(`${I} Novel pattern(s): ${ce.map(N=>`${N.category}/${N.element}`).join(", ")}`),k.broadcast({type:"novel_patterns",jobId:r.id,patterns:ce,threadId:r.threadId},r.id,r.sourceId)),k.broadcast({type:"done",jobId:r.id,success:!0,resolutions:C.length>0?C:void 0,responseText:v.text,threadId:r.threadId},r.id,r.sourceId),R.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${I} Error: ${v.error}`),r.status="error",r.error=v.error,r.threadId&&await m.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:v.error||"Unknown error",model:r.model,provider:u}),k.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:v.error||"Unknown error",provider:u,model:r.model,recoverable:v.recoverableError,code:v.errorCode},r.id,r.sourceId),R.push({id:r.id,status:"error",completedAt:Date.now(),error:v.error,threadId:r.threadId,annotationIds:r.annotationIds});ie()});let at=Vo(async(r,l)=>{if(cr(r,l),r.method==="OPTIONS"){l.writeHead(204),l.end();return}let p=r.url||"/",u=p.split("?")[0],h=new URL(p,`http://127.0.0.1:${z}`),d=h.pathname,I=lr(r,h);if(I&&I!==o){y(l,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:I,projectName:ot(t)});return}if(r.headers.origin){if(!$n(r.headers.origin)){y(l,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(I!==o){y(l,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:I,projectName:ot(t)});return}}try{if(r.method==="POST"&&d==="/send")await jn(r,l);else if(r.method==="GET"&&d==="/events")Bn(r,l);else if(r.method==="GET"&&d==="/status")await Un(l,I);else if(r.method==="PATCH"&&d==="/config")await Ln(r,l);else if(r.method==="POST"&&d==="/shutdown"){if(G!=="detached"){y(l,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:G});return}y(l,200,{ok:!0}),setTimeout(()=>process.exit(0),100)}else if(r.method==="POST"&&d==="/restart"){if(G!=="detached"){y(l,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:G});return}y(l,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let S of P)try{S.res.end()}catch{}at.close(()=>{Rn(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(r.method==="GET"&&d==="/capabilities")y(l,200,{providers:w});else if(r.method==="POST"&&d==="/mcp/install")await es(r,l);else if(r.method==="POST"&&d==="/reply")await Fn(r,l);else if(r.method==="POST"&&d==="/cancel")Wn(r,l);else if(r.method==="POST"&&d==="/materialize")await Hn(r,l);else if(r.method==="GET"&&d==="/materialization-runs"){let S=await g.loadRuns();y(l,200,S)}else if(r.method==="GET"&&d==="/model/proposals"){let S=await g.loadModelProposals();y(l,200,S)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let S=d.slice(17,-6);await Gn(S,l)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let S=d.slice(17,-8);await qn(S,l)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let S=d.slice(17,-14);await Qn(S,r,l)}else if(r.method==="POST"&&d==="/model/component")await ts(r,l);else if(r.method==="DELETE"&&d==="/model/component")await ns(r,l);else if(r.method==="PATCH"&&d==="/model/token")await ss(r,l);else if(r.method==="DELETE"&&d==="/model/token")await os(r,l);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:S,model:j}=await ze(r);if(S==="copilot"){y(l,400,{error:"Model consolidation is not available for Copilot yet."});return}g.consolidate({provider:S,model:j}).catch(Q=>console.error("[Bridge] Consolidation error:",Q)),y(l,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await Xn(r,l);else if(r.method==="POST"&&d==="/evals/synthesize")await Yn(r,l);else if(r.method==="GET"&&d==="/evals"){let S=await A.loadSuiteWithCurrentRuns(Cn(t));y(l,200,S)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let S=d.slice(7,-4);await Kn(S,r,l)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await Vn(d.slice(7),r,l);else if(r.method==="GET"&&d==="/model"){let S=await g.loadModel();y(l,200,{model:S})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let S=d.slice(6,d.length-7),j=parseInt(h.searchParams.get("afterSeq")??"-1",10),Q=k.getBufferedEvents(S,isNaN(j)?-1:j);Q?y(l,200,Q):y(l,404,{error:"Unknown job"})}else if(r.method==="GET"&&u.startsWith("/files/"))await cs(u.slice(7),l);else if(r.method==="GET"&&d==="/threads/recent"){let S=Math.min(Math.max(parseInt(h.searchParams.get("limit")??"5",10)||5,1),20),j=await m.listRecent(S);y(l,200,j)}else if(r.method==="GET"&&d.startsWith("/thread/")){let S=d.slice(8);await ls(S,l)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?rs(r,l):r.method==="GET"&&d==="/canvas/manifest"?await is(l):r.method==="GET"&&d==="/canvas/app.mjs"?await as(l):y(l,404,{error:"Not found"})}catch(S){console.error("[Bridge] Request error:",S),y(l,500,{error:S instanceof Error?S.message:"Internal error"})}});async function jn(r,l){let{screenshot:p,feedback:u,color:h,provider:d,model:I,sourceId:S,pastedImages:j,pageScreenshots:Q}=await Ve(r),U;try{U=JSON.parse(u)}catch{y(l,400,{error:"Invalid feedback JSON"});return}let v=ye().slice(0,8),E={};if(Q.length>0)for(let _ of Q){let re=encodeURIComponent(_.pathname),de=fe(a,`screenshot-${v}-${re}.webp`);await Ne(de,_.data),E[_.pathname]=de}let C=fe(a,`screenshot-${v}.webp`);await Ne(C,p);let X={};if(j.length>0)for(let _ of j){let re=fe(a,`pasted-${v}-${_.annotationId}-${_.index}.webp`);await Ne(re,_.data),X[_.annotationId]||(X[_.annotationId]=[]),X[_.annotationId].push(re)}let le=U.annotations.map(_=>_.linkedSelector?_.pathname?`${_.pathname}:${_.linkedSelector}`:_.linkedSelector:null).filter(_=>!!_),se;if(le.length>0){let _=await m.findContinuationThread(le);_?(se=_.id,await m.addElementIdentifiers(se,le)):se=(await m.createThread(v,le)).id}else se=(await m.createThread(v,[])).id;let ae=U.annotations.map(_=>_.id),ce=Object.keys(E).length>0,N={id:v,status:"queued",screenshotPath:C,feedback:U,createdAt:Date.now(),color:h,threadId:se,annotationIds:ae,provider:Je(d),model:I||void 0,...Object.keys(X).length>0?{imagePaths:X}:{},sourceId:S||void 0,...ce?{screenshotPaths:E}:{}},Z=new Set(U.annotations.map(_=>_.pathname).filter(Boolean)),F;if(Z.size>1){let _=new Map;for(let re of U.annotations){let de=re.pathname||"(unknown)";_.has(de)||_.set(de,[]),_.get(de).push(re.instruction||`[${re.type}]`)}F=[..._.entries()].map(([re,de])=>`\`${re}\`
404
- ${de.map(ct=>`- ${ct}`).join(`
402
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let _=!p&&r.threadId?await m.getThreadHistory(r.threadId):void 0,W=p?null:await v.loadModel();g=p??yn(r.screenshotPath,r.feedback,{threadHistory:_&&_.length>0?_:void 0,provider:d,imagePaths:r.imagePaths,designModel:W??void 0,screenshotPaths:r.screenshotPaths})}let E=vr(r.color,`[\u22B9 ${j}:${r.id}]`),G=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${E} Reviewing ${G} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${M?` (resuming: ${M.slice(0,8)})`:""}`);let z=(_,W)=>{_.type==="delta"&&"text"in _?P.accumulateText(W,"response",_.text):_.type==="thinking"&&"text"in _&&P.accumulateText(W,"thinking",_.text),P.broadcast(_,W,r.sourceId)},{process:B,result:Q}=d==="codex"?Le(r.id,{prompt:g,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:M,model:r.model,onEvent:z}):d==="copilot"?Bt(r.id,{prompt:g,projectRoot:t,resumeSessionId:M,model:r.model,timeoutMs:$,copilotPath:S.copilot?.path??R,onEvent:z}):Fe(r.id,{prompt:g,projectRoot:t,maxTurns:l,maxBudgetUsd:f,allowedTools:k,claudePath:b,resumeSessionId:M,model:r.model,timeoutMs:$,onEvent:z});P.setActiveProcess(r.id,B);let x=await Q;if(r.result=x.text,x.success){console.log(`${E} Iteration complete`),x.fileEdits&&x.fileEdits.length>0&&console.log(`${E} Captured ${x.fileEdits.length} file edit(s): ${x.fileEdits.map(J=>`${J.tool} ${J.file_path}`).join(", ")}`),x.editEvents&&x.editEvents.length>0&&console.log(`${E} Captured ${x.editEvents.length} edit event(s): ${x.editEvents.map(J=>`${J.operation} ${J.filePath}`).join(", ")}`),r.status="done";let _=vn(x.text),W=wn(x.text),te=W.some(J=>(J.finalScope??J.inferredScope)?.breadth==="pattern");if(W.length>0&&r.annotationIds&&r.annotationIds.length>0){let J=new Set(r.annotationIds);W.every(re=>J.has(re.annotationId))||(W=W.map((re,w)=>({...re,annotationId:r.annotationIds[w%r.annotationIds.length]})))}let ue=x.fileEdits&&x.fileEdits.length>0?x.fileEdits.map(J=>`${J.tool} ${J.file_path.split("/").pop()}`):x.toolsUsed,le=P.getBufferedEvents(r.id),ce=le?fr(le.events):void 0;if(r.threadId&&await m.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:x.text,resolutions:W.length>0?W:void 0,question:_??void 0,sessionId:x.sessionId,toolsUsed:ue,editEvents:x.editEvents&&x.editEvents.length>0?x.editEvents:void 0,segments:ce&&ce.length>0?ce:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&H.captureGitDiff(t).then(async J=>{let V=Date.now(),re=r.imagePaths?Object.values(r.imagePaths).flat():[],w=[];if(r.imagePaths)for(let[U,Y]of Object.entries(r.imagePaths))for(let ie=0;ie<Y.length;ie++)w.push(`screenshots/p-${r.id}-${U}-${ie}.webp`);await H.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:V,durationMs:V-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:w,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:d,model:r.model,sessionId:x.sessionId,threadId:r.threadId,responseText:x.text,resolutions:W.length>0?W:[],question:_??void 0,fileEdits:x.fileEdits??[],editEvents:x.editEvents??[],toolsUsed:ue,gitDiff:J},r.screenshotPath,re),te&&d!=="copilot"?await kt({provider:d,model:r.model,threadId:r.threadId,annotationIds:r.annotationIds,sourceId:r.sourceId,reason:`Materialize model \u2014 ${r.feedback.annotations[0]?.instruction??"pattern decision"}`}):te&&console.log(`${E} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&x.text){let J=Xe(x.text);if(J){Array.isArray(J.rules)&&(J.rules=Ae(J.rules));let V=await v.loadModel();V&&(!J.tokens&&V.tokens&&(J.tokens=V.tokens),!J.components&&V.components&&(J.components=V.components)),await v.writeModel(J),console.log(`${E} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&x.text){let J=Ht(x.text),V=Gt(x.text),re=J??V;if(re&&re.length>0){let w=await A.writeSynthesized(re),U=r._proposalId;U&&await v.attachGeneratedEvals(U,re.map(Y=>Y.id)),console.log(`${E} Eval synthesis: wrote ${re.length} ${J?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${w.cases.length} total)`)}}else if(r.kind==="run_eval"&&x.text&&r.evalId&&r.evalRunId){let J=await A.findCase(r.evalId),V=r._evalRunScope;if(J&&V){let re=qt(x.text,J.assertions),w=Date.now();await A.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:w,durationMs:w-r.createdAt,scope:V,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:$n(t),rawResponse:x.text,...re}),console.log(`${E} Eval run: ${J.title} \u2192 ${re.status}`)}}_&&(console.log(`${E} \u{1F4AC} Question detected: "${_.slice(0,120)}" \u2192 broadcasting to ${I.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),P.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:_,annotationIds:r.annotationIds},r.id,r.sourceId));let pe=Sn(x.text);pe.length>0&&(console.log(`${E} Novel pattern(s): ${pe.map(J=>`${J.category}/${J.element}`).join(", ")}`),P.broadcast({type:"novel_patterns",jobId:r.id,patterns:pe,threadId:r.threadId},r.id,r.sourceId)),P.broadcast({type:"done",jobId:r.id,success:!0,resolutions:W.length>0?W:void 0,responseText:x.text,threadId:r.threadId},r.id,r.sourceId),T.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${E} Error: ${x.error}`),r.status="error",r.error=x.error,r.threadId&&await m.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:x.error||"Unknown error",model:r.model,provider:d}),P.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:x.error||"Unknown error",provider:d,model:r.model,recoverable:x.recoverableError,code:x.errorCode},r.id,r.sourceId),T.push({id:r.id,status:"error",completedAt:Date.now(),error:x.error,threadId:r.threadId,annotationIds:r.annotationIds});ae()});let lt=ir(async(r,c)=>{if(gr(r,c),r.method==="OPTIONS"){c.writeHead(204),c.end();return}let p=r.url||"/",u=p.split("?")[0],h=new URL(p,`http://127.0.0.1:${j}`),d=h.pathname,M=yr(r,h);if(M&&M!==o){y(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:M,projectName:rt(t)});return}if(r.headers.origin){if(!On(r.headers.origin)){y(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(M!==o){y(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:M,projectName:rt(t)});return}}try{if(r.method==="POST"&&d==="/send")await Fn(r,c);else if(r.method==="GET"&&d==="/events")Ln(r,c);else if(r.method==="GET"&&d==="/status")await Wn(c,M);else if(r.method==="PATCH"&&d==="/config")await Hn(r,c);else if(r.method==="POST"&&d==="/shutdown"){if(q!=="detached"){y(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:q});return}y(c,200,{ok:!0}),setTimeout(()=>process.exit(0),100)}else if(r.method==="POST"&&d==="/restart"){if(q!=="detached"){y(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:q});return}y(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let g of I)try{g.res.end()}catch{}lt.close(()=>{Tn(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(r.method==="GET"&&d==="/capabilities")y(c,200,{providers:S});else if(r.method==="POST"&&d==="/mcp/install")await ss(r,c);else if(r.method==="POST"&&d==="/reply")await Un(r,c);else if(r.method==="POST"&&d==="/cancel")Gn(r,c);else if(r.method==="POST"&&d==="/materialize")await qn(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let g=await v.loadRuns();y(c,200,g)}else if(r.method==="GET"&&d==="/model/proposals"){let g=await v.loadModelProposals();y(c,200,g)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply-selected")){let g=d.slice(17,-15);await Xn(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let g=d.slice(17,-6);await Qn(g,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let g=d.slice(17,-8);await Yn(g,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let g=d.slice(17,-14);await Kn(g,r,c)}else if(r.method==="POST"&&d==="/model/component")await os(r,c);else if(r.method==="DELETE"&&d==="/model/component")await rs(r,c);else if(r.method==="PATCH"&&d==="/model/token")await is(r,c);else if(r.method==="DELETE"&&d==="/model/token")await as(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:g,model:E}=await ze(r);if(g==="copilot"){y(c,400,{error:"Model consolidation is not available for Copilot yet."});return}v.consolidate({provider:g,model:E}).catch(G=>console.error("[Bridge] Consolidation error:",G)),y(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await Vn(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await Zn(r,c);else if(r.method==="GET"&&d==="/evals"){let g=await A.loadSuiteWithCurrentRuns($n(t));y(c,200,g)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let g=d.slice(7,-4);await es(g,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await ts(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let g=await v.loadModel();y(c,200,{model:g})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let g=d.slice(6,d.length-7),E=parseInt(h.searchParams.get("afterSeq")??"-1",10),G=P.getBufferedEvents(g,isNaN(E)?-1:E);G?y(c,200,G):y(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&u.startsWith("/files/"))await us(u.slice(7),c);else if(r.method==="GET"&&d==="/threads/recent"){let g=Math.min(Math.max(parseInt(h.searchParams.get("limit")??"5",10)||5,1),20),E=await m.listRecent(g);y(c,200,E)}else if(r.method==="GET"&&d.startsWith("/thread/")){let g=d.slice(8);await ps(g,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?ls(r,c):r.method==="GET"&&d==="/canvas/manifest"?await cs(c):r.method==="GET"&&d==="/canvas/app.mjs"?await ds(c):y(c,404,{error:"Not found"})}catch(g){console.error("[Bridge] Request error:",g),y(c,500,{error:g instanceof Error?g.message:"Internal error"})}});async function Fn(r,c){let{screenshot:p,feedback:u,color:h,provider:d,model:M,sourceId:g,pastedImages:E,pageScreenshots:G}=await Ze(r),z;try{z=JSON.parse(u)}catch{y(c,400,{error:"Invalid feedback JSON"});return}let B=we().slice(0,8),Q={};if(G.length>0)for(let w of G){let U=encodeURIComponent(w.pathname),Y=me(a,`screenshot-${B}-${U}.webp`);await Je(Y,w.data),Q[w.pathname]=Y}let x=me(a,`screenshot-${B}.webp`);await Je(x,p);let _={};if(E.length>0)for(let w of E){let U=me(a,`pasted-${B}-${w.annotationId}-${w.index}.webp`);await Je(U,w.data),_[w.annotationId]||(_[w.annotationId]=[]),_[w.annotationId].push(U)}let W=z.annotations.map(w=>w.linkedSelector?w.pathname?`${w.pathname}:${w.linkedSelector}`:w.linkedSelector:null).filter(w=>!!w),te;if(W.length>0){let w=await m.findContinuationThread(W);w?(te=w.id,await m.addElementIdentifiers(te,W)):te=(await m.createThread(B,W)).id}else te=(await m.createThread(B,[])).id;let ue=z.annotations.map(w=>w.id),le=Object.keys(Q).length>0,ce={id:B,status:"queued",screenshotPath:x,feedback:z,createdAt:Date.now(),color:h,threadId:te,annotationIds:ue,provider:je(d),model:M||void 0,...Object.keys(_).length>0?{imagePaths:_}:{},sourceId:g||void 0,...le?{screenshotPaths:Q}:{}},pe=new Set(z.annotations.map(w=>w.pathname).filter(Boolean)),J;if(pe.size>1){let w=new Map;for(let U of z.annotations){let Y=U.pathname||"(unknown)";w.has(Y)||w.set(Y,[]),w.get(Y).push(U.instruction||`[${U.type}]`)}J=[...w.entries()].map(([U,Y])=>`\`${U}\`
403
+ ${Y.map(ie=>`- ${ie}`).join(`
405
404
  `)}`).join(`
406
- `)}else F=U.annotations.map(_=>_.instruction||`[${_.type}]`).join("; ");let H=$e(U,Object.keys(X).length>0?X:void 0);await m.appendMessage(se,{role:"human",timestamp:Date.now(),jobId:v,screenshotPath:C,...ce?{screenshotPaths:E}:{},...Object.keys(X).length>0?{imagePaths:X}:{},annotationIds:ae,feedbackSummary:F,feedbackContext:H||void 0});let oe=k.enqueue(N);y(l,200,{jobId:v,position:oe,threadId:se})}async function Fn(r,l){let p=r.headers["content-type"]||"",u,h,d,I,S,j,Q=[];if(p.includes("multipart/form-data")){let F=await Ve(r),H=F.feedback?JSON.parse(F.feedback):{};u=H.threadId,h=H.reply,d=H.color,I=H.provider,S=H.model,j=H.sourceId||F.sourceId;for(let oe of F.pastedImages)Q.push(oe.data)}else{let F=[];for await(let _ of r)F.push(typeof _=="string"?Buffer.from(_):_);let H=Buffer.concat(F).toString("utf-8"),oe;try{oe=JSON.parse(H)}catch{y(l,400,{error:"Invalid JSON"});return}u=oe.threadId,h=oe.reply,d=oe.color,I=oe.provider,S=oe.model,j=oe.sourceId}if(!u||!h){y(l,400,{error:"Missing threadId or reply"});return}if(!await m.getThread(u)){y(l,404,{error:"Thread not found"});return}let v=ye().slice(0,8),E=[];for(let F=0;F<Q.length;F++){let H=fe(a,`reply-${v}-${F}.webp`);await Ne(H,Q[F]),E.push(H)}let C="";{let F=await m.getThreadHistory(u);for(let H=F.length-1;H>=0;H--)if(F[H].screenshotPath){C=F[H].screenshotPath;break}}let X=await Zn(u);if(!C&&!X){y(l,400,{error:"No screenshot available"});return}await m.appendMessage(u,{role:"human",timestamp:Date.now(),jobId:v,replyToQuestion:h,screenshotPath:C,...E.length>0?{replyImagePaths:E}:{}});let le=await m.getThreadHistory(u),se=[];for(let F of le)if(F.annotationIds)for(let H of F.annotationIds)se.includes(H)||se.push(H);let ae=Je(I),ce=yn(C,le,ae,E.length>0?E:void 0),N={id:v,status:"queued",screenshotPath:C,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:d,threadId:u,annotationIds:se.length>0?se:void 0,provider:ae,model:S||void 0,sourceId:j||void 0};X&&(N.kind=X),N._replyPrompt=ce,E.length>0&&(N._replyImagePaths=E);let Z=k.enqueue(N);y(l,200,{jobId:v,position:Z,threadId:u})}function Bn(r,l){l.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),l.write(`event: connected
405
+ `)}else J=z.annotations.map(w=>w.instruction||`[${w.type}]`).join("; ");let V=_e(z,Object.keys(_).length>0?_:void 0);await m.appendMessage(te,{role:"human",timestamp:Date.now(),jobId:B,screenshotPath:x,...le?{screenshotPaths:Q}:{},...Object.keys(_).length>0?{imagePaths:_}:{},annotationIds:ue,feedbackSummary:J,feedbackContext:V||void 0});let re=P.enqueue(ce);y(c,200,{jobId:B,position:re,threadId:te})}async function Un(r,c){let p=r.headers["content-type"]||"",u,h,d,M,g,E,G=[];if(p.includes("multipart/form-data")){let w=await Ze(r),U=w.feedback?JSON.parse(w.feedback):{};u=U.threadId,h=U.reply,d=U.color,M=U.provider,g=U.model,E=U.sourceId||w.sourceId;for(let Y of w.pastedImages)G.push(Y.data)}else{let w=[];for await(let ie of r)w.push(typeof ie=="string"?Buffer.from(ie):ie);let U=Buffer.concat(w).toString("utf-8"),Y;try{Y=JSON.parse(U)}catch{y(c,400,{error:"Invalid JSON"});return}u=Y.threadId,h=Y.reply,d=Y.color,M=Y.provider,g=Y.model,E=Y.sourceId}if(!u||!h){y(c,400,{error:"Missing threadId or reply"});return}if(!await m.getThread(u)){y(c,404,{error:"Thread not found"});return}let B="";{let w=await m.getThreadHistory(u);for(let U=w.length-1;U>=0;U--)if(w[U].screenshotPath){B=w[U].screenshotPath;break}}let Q=await ns(u);if(!B&&!Q){y(c,400,{error:"No screenshot available"});return}let x=P.hasActiveThread(u),_=x?P.getQueuedThreadJob(u,w=>w._replyText!==void 0||w._replyPrompt!==void 0):null,W=_?.id??we().slice(0,8),te=[],ue=`${W}-${Date.now()}`;for(let w=0;w<G.length;w++){let U=me(a,`reply-${ue}-${w}.webp`);await Je(U,G[w]),te.push(U)}await m.appendMessage(u,{role:"human",timestamp:Date.now(),jobId:W,replyToQuestion:h,screenshotPath:B,...x?{queued:!0}:{},...te.length>0?{replyImagePaths:te}:{}});let le=await m.getThreadHistory(u),ce=[];for(let w of le)if(w.annotationIds)for(let U of w.annotationIds)ce.includes(U)||ce.push(U);let pe=je(M),J=xt(B,le,pe,te.length>0?te:void 0);if(_){let w=_,Y=[...w._replyTexts??(w._replyText?[w._replyText]:[]),h],ie=[...w._replyImagePaths??[],...te];w._replyTexts=Y,w._replyText=An(Y),w._replyImagePaths=ie.length>0?ie:void 0,w._replyPrompt=xt(B,le,pe,ie.length>0?ie:void 0),w.annotationIds=ce.length>0?ce:w.annotationIds,y(c,200,{jobId:W,position:1,threadId:u,bundled:!0});return}let V={id:W,status:"queued",screenshotPath:B,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:d,threadId:u,annotationIds:ce.length>0?ce:void 0,provider:pe,model:g||void 0,sourceId:E||void 0};Q&&(V.kind=Q),V._replyPrompt=J,V._replyTexts=[h],V._replyText=An([h]),te.length>0&&(V._replyImagePaths=te);let re=x?P.enqueueNext(V):P.enqueue(V);y(c,200,{jobId:W,position:re,threadId:u})}function Ln(r,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
407
406
  data: {"status":"connected"}
408
407
 
409
- `);let u=new URL(r.url||"/",`http://127.0.0.1:${z}`).searchParams.get("sourceId")||void 0,h={id:ye().slice(0,8),res:l,sourceId:u};P.add(h),r.on("close",()=>{P.delete(h)})}async function Un(r,l){let p=[...k.allActive,...J.allActive.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds??[],color:"#000000",kind:"materialize_model"}))],[u,h]=await Promise.all([g.loadRuns(),g.loadModelProposals()]);y(r,200,{ok:!0,version:En,restartMode:G,projectId:o,projectName:ot(t),projectRoot:t,requestProjectId:l,projectIdVerified:l===o,devOrigin:i,activeJob:p[0]?{id:p[0].id,status:p[0].status}:null,activeJobs:p.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds,color:d.color,kind:d.kind})),queueDepth:k.depth+J.depth,materializerQueueDepth:J.depth,materialization:{activeJob:J.active?{id:J.active.id,status:J.active.status,threadId:J.active.threadId,annotationIds:J.active.annotationIds??[],provider:J.active.provider,model:J.active.model}:null,queueDepth:J.depth,recentRuns:[...u.runs].sort((d,I)=>(I.completedAt??I.startedAt)-(d.completedAt??d.startedAt)).slice(0,10),proposals:h.proposals.slice(0,20).map(d=>({id:d.id,status:d.status,title:d.title,summary:d.summary,decisionIds:d.decisionIds,threadId:d.threadId,runId:d.runId,createdAt:d.createdAt,updatedAt:d.updatedAt,appliedAt:d.appliedAt,dismissedAt:d.dismissedAt,generatedEvalIds:d.generatedEvalIds,error:d.error}))},recentJobs:R})}async function Ln(r,l){let p=await new Promise(u=>{let h="";r.on("data",d=>{h+=d.toString()}),r.on("end",()=>u(h))});try{let u=JSON.parse(p);typeof u.devOrigin=="string"&&(i=u.devOrigin||null),y(l,200,{ok:!0,devOrigin:i})}catch{y(l,400,{error:"Invalid JSON"})}}async function Wn(r,l){let u=new URL(r.url||"/",`http://127.0.0.1:${z}`).searchParams.get("jobId"),d=(u?k.allActive.filter(S=>S.id===u):k.allActive).map(S=>S.threadId).filter(Boolean),I=u?k.cancelJob(u):k.cancelActive();for(let S of d)await m.appendMessage(S,{role:"assistant",timestamp:Date.now(),jobId:u||"",cancelled:!0});y(l,200,{cancelled:I})}async function Pt(r){let l=ye().slice(0,8),p=r.threadId,u=!p;p||(p=(await m.createThread(l,[])).id,V.set(p,"materialize_model")),u&&await m.appendMessage(p,{role:"human",timestamp:Date.now(),jobId:l,feedbackSummary:r.reason});let h={id:l,status:"queued",createdAt:Date.now(),provider:r.provider,model:r.model,threadId:p,annotationIds:r.annotationIds,sourceId:r.sourceId},d=J.enqueue(h);return{jobId:l,position:d,threadId:p}}async function Hn(r,l){if(J.isRunning){y(l,200,{skipped:!0,reason:"Already running"});return}let{provider:p,model:u}=await ze(r);if(p==="copilot"){y(l,400,{error:"Materialization is not available for Copilot yet."});return}let h=await g.getUnmaterializedPatternDecisions();if(h.length===0){y(l,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}let d=await Pt({provider:p,model:u,reason:"Materialize model \u2014 promote pattern decisions into the local taste model"});y(l,200,{started:!0,decisionCount:h.length,decisionIds:h.map(I=>I.id),...d})}async function Gn(r,l){let p=decodeURIComponent(r),u=await g.applyModelProposal(p);if(!u){y(l,404,{error:"Model proposal not found"});return}u.threadId&&await m.appendMessage(u.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${u.id}`,responseText:`Model proposal applied.
408
+ `);let u=new URL(r.url||"/",`http://127.0.0.1:${j}`).searchParams.get("sourceId")||void 0,h={id:we().slice(0,8),res:c,sourceId:u};I.add(h),r.on("close",()=>{I.delete(h)})}async function Wn(r,c){let p=[...P.allActive,...N.allActive.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds??[],color:"#000000",kind:"materialize_model"}))],[u,h]=await Promise.all([v.loadRuns(),v.loadModelProposals()]);y(r,200,{ok:!0,version:En,restartMode:q,projectId:o,projectName:rt(t),projectRoot:t,requestProjectId:c,projectIdVerified:c===o,devOrigin:i,activeJob:p[0]?{id:p[0].id,status:p[0].status}:null,activeJobs:p.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds,color:d.color,kind:d.kind})),queueDepth:P.depth+N.depth,materializerQueueDepth:N.depth,materialization:{activeJob:N.active?{id:N.active.id,status:N.active.status,threadId:N.active.threadId,annotationIds:N.active.annotationIds??[],provider:N.active.provider,model:N.active.model}:null,queueDepth:N.depth,recentRuns:[...u.runs].sort((d,M)=>(M.completedAt??M.startedAt)-(d.completedAt??d.startedAt)).slice(0,10),proposals:h.proposals.slice(0,20).map(d=>({id:d.id,status:d.status,title:d.title,summary:d.summary,decisionIds:d.decisionIds,threadId:d.threadId,runId:d.runId,createdAt:d.createdAt,updatedAt:d.updatedAt,appliedAt:d.appliedAt,dismissedAt:d.dismissedAt,generatedEvalIds:d.generatedEvalIds,error:d.error}))},recentJobs:T})}async function Hn(r,c){let p=await new Promise(u=>{let h="";r.on("data",d=>{h+=d.toString()}),r.on("end",()=>u(h))});try{let u=JSON.parse(p);typeof u.devOrigin=="string"&&(i=u.devOrigin||null),y(c,200,{ok:!0,devOrigin:i})}catch{y(c,400,{error:"Invalid JSON"})}}async function Gn(r,c){let u=new URL(r.url||"/",`http://127.0.0.1:${j}`).searchParams.get("jobId"),d=(u?P.allActive.filter(g=>g.id===u):P.allActive).map(g=>g.threadId).filter(Boolean),M=u?P.cancelJob(u):P.cancelActive();for(let g of d)await m.appendMessage(g,{role:"assistant",timestamp:Date.now(),jobId:u||"",cancelled:!0});y(c,200,{cancelled:M})}async function kt(r){let c=we().slice(0,8),p=r.threadId,u=!p;p||(p=(await m.createThread(c,[])).id,ee.set(p,"materialize_model")),u&&await m.appendMessage(p,{role:"human",timestamp:Date.now(),jobId:c,feedbackSummary:r.reason});let h={id:c,status:"queued",createdAt:Date.now(),provider:r.provider,model:r.model,threadId:p,annotationIds:r.annotationIds,sourceId:r.sourceId},d=N.enqueue(h);return{jobId:c,position:d,threadId:p}}async function qn(r,c){if(N.isRunning){y(c,200,{skipped:!0,reason:"Already running"});return}let{provider:p,model:u}=await ze(r);if(p==="copilot"){y(c,400,{error:"Materialization is not available for Copilot yet."});return}let h=await v.getUnmaterializedPatternDecisions();if(h.length===0){y(c,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}let d=await kt({provider:p,model:u,reason:"Materialize model \u2014 promote pattern decisions into the local taste model"});y(c,200,{started:!0,decisionCount:h.length,decisionIds:h.map(M=>M.id),...d})}async function Qn(r,c){let p=decodeURIComponent(r),u=await v.applyModelProposal(p);if(!u){y(c,404,{error:"Model proposal not found"});return}u.threadId&&await m.appendMessage(u.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${u.id}`,responseText:`Model proposal applied.
410
409
 
411
410
  ${u.title}
412
- ${u.summary}`}),y(l,200,{proposal:u})}async function qn(r,l){let p=decodeURIComponent(r),u=await g.dismissModelProposal(p);if(!u){y(l,404,{error:"Model proposal not found"});return}u.threadId&&await m.appendMessage(u.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${u.id}`,responseText:`Model proposal dismissed.
411
+ ${u.summary}`}),y(c,200,{proposal:u})}async function Xn(r,c,p){let u=decodeURIComponent(r),h=[];for await(let E of c)h.push(typeof E=="string"?Buffer.from(E):E);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{y(p,400,{error:"Invalid JSON"});return}let M=(d.changes??[]).flatMap(E=>{if(!Array.isArray(E.path)||E.path.length===0)return[];let G=E.path.filter(z=>typeof z=="string"||typeof z=="number");return G.length!==E.path.length?[]:[{path:G,value:E.value,remove:E.remove===!0}]});if(M.length===0){y(p,400,{error:"No selected model changes"});return}let g=await v.applySelectedModelProposal(u,M);if(!g){y(p,404,{error:"Model proposal not found"});return}g.threadId&&await m.appendMessage(g.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${g.id}`,responseText:`Model proposal applied with ${M.length} selected change${M.length===1?"":"s"}.
413
412
 
414
- ${u.title}`}),y(l,200,{proposal:u})}async function Qn(r,l,p){let u=decodeURIComponent(r),h=await g.findModelProposal(u);if(!h){y(p,404,{error:"Model proposal not found"});return}if(h.status!=="applied"){y(p,400,{error:"Only applied model proposals can be projected into evals"});return}let{provider:d,model:I}=await ze(l),S=d??h.provider??O;if(S==="copilot"){y(p,400,{error:"Eval projection is not available for Copilot yet."});return}let j=await g.loadModel(),Q=await A.loadSuite(),U=Yt({proposal:h,currentModel:j,existingSuite:Q}),v=ye().slice(0,8),E=h.threadId??(await m.createThread(v,[])).id;V.set(E,"synthesize_evals"),await m.appendMessage(E,{role:"human",timestamp:Date.now(),jobId:v,feedbackSummary:`Create eval drafts \u2014 ${h.title}`,feedbackContext:[`Model proposal: ${h.title}`,`Sources: ${h.decisionIds.length} decisions`,"Projection target: pending eval proposals"].join(`
415
- `)});let C={id:v,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#111827",threadId:E,kind:"synthesize_evals",provider:S,model:I??h.model};C._replyPrompt=U,C._proposalId=h.id;let X=k.enqueue(C);y(p,200,{jobId:v,position:X,threadId:E})}async function ze(r){try{let l=[];for await(let u of r)l.push(typeof u=="string"?Buffer.from(u):u);if(l.length===0)return{};let p=JSON.parse(Buffer.concat(l).toString());return{provider:Je(typeof p.provider=="string"?p.provider:void 0),model:typeof p.model=="string"&&p.model?p.model:void 0}}catch{return{}}}async function Xn(r,l){let p=await g.loadModel();if(!p){y(l,400,{error:"No model exists yet"});return}let u,h;try{let v=[];for await(let C of r)v.push(typeof C=="string"?Buffer.from(C):C);let E=JSON.parse(Buffer.concat(v).toString());u=E.provider,h=E.model}catch{}if(u==="copilot"){y(l,400,{error:"Rule synthesis is not available for Copilot yet."});return}let d=tn(p),I=ye().slice(0,8),j=(await m.createThread(I,[])).id;V.set(j,"synthesize"),await m.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:I,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let Q={id:I,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:j,kind:"synthesize",provider:Je(u),model:h||void 0};Q._replyPrompt=d;let U=k.enqueue(Q);y(l,200,{jobId:I,position:U,threadId:j})}async function Yn(r,l){let{provider:p,model:u}=await ze(r);if(p==="copilot"){y(l,400,{error:"Eval synthesis is not available for Copilot yet."});return}let h=await W.listDecisionIds(),d=await W.loadDecisions(h),I=await m.load(),S=await g.loadModel(),j=await A.loadSuite(),Q=Qt({decisions:d,threads:I,model:S,existingSuite:j}),U=ye().slice(0,8),E=(await m.createThread(U,[])).id;V.set(E,"synthesize_evals"),await m.appendMessage(E,{role:"human",timestamp:Date.now(),jobId:U,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let C={id:U,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#6b7280",threadId:E,kind:"synthesize_evals",provider:p,model:u||void 0};C._replyPrompt=Q;let X=k.enqueue(C);y(l,200,{jobId:U,position:X,threadId:E})}async function Kn(r,l,p){let u=decodeURIComponent(r),h=await A.findCase(u);if(!h){y(p,404,{error:"Eval not found"});return}if(h.status!=="approved"){y(p,400,{error:"Only approved evals can be run"});return}let{screenshot:d,feedback:I,provider:S,model:j,sourceId:Q}=await Ve(l),U=Je(S)??O;if(U==="copilot"){y(p,400,{error:"Eval runs are not available for Copilot yet."});return}let v={};try{v=I?JSON.parse(I):{}}catch{y(p,400,{error:"Invalid eval run context JSON"});return}let E=ye().slice(0,8),C=ye().slice(0,8),X=fe(a,`eval-run-${E}.webp`);await Ne(X,d);let le=await A.writeRunScreenshot(E,d),se=v.viewport,ae=se&&typeof se=="object"?se:{},ce={type:"current_page",url:typeof v.url=="string"?v.url:"",viewport:{width:typeof ae.width=="number"?ae.width:0,height:typeof ae.height=="number"?ae.height:0}},N=await g.loadModel(),Z=U==="claude"?L.name:U==="codex"?q.name:null,F=U==="codex"?K.length>0:typeof Z=="string"&&/chrome|devtools/i.test(Z),H=Xt({evalCase:h,scope:ce,model:N,screenshotPath:X,chromeDevtoolsAvailable:F}),_=(await m.createThread(C,[])).id;V.set(_,"run_eval");let re={timestamp:new Date().toISOString(),url:ce.url,viewport:ce.viewport,scrollPosition:{x:typeof v.scrollX=="number"?v.scrollX:0,y:typeof v.scrollY=="number"?v.scrollY:0},annotations:[],styleModifications:[]};await m.appendMessage(_,{role:"human",timestamp:Date.now(),jobId:C,screenshotPath:X,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${ce.url||"unknown"}`,"Assertions:",...h.assertions.map(us=>`- ${us}`)].join(`
416
- `)});let de={id:C,status:"queued",screenshotPath:X,feedback:re,createdAt:Date.now(),color:"#111827",threadId:_,kind:"run_eval",evalId:u,evalRunId:E,provider:U,model:j||void 0,sourceId:Q||void 0};de._replyPrompt=H,de._evalRunScope=ce,de._evalScreenshotPath=le;let ct=k.enqueue(de);y(p,200,{jobId:C,runId:E,position:ct,threadId:_,screenshotPath:le})}async function Vn(r,l,p){let u=decodeURIComponent(r),h={},d,I,S;try{let Q=[];for await(let v of l)Q.push(typeof v=="string"?Buffer.from(v):v);let U=JSON.parse(Buffer.concat(Q).toString());d=U.status,I=U.title,S=U.assertions}catch{y(p,400,{error:"Invalid JSON"});return}if(d!==void 0&&d!=="pending"&&d!=="approved"&&d!=="rejected"){y(p,400,{error:"Invalid status"});return}if(d&&(h.status=d),I!==void 0){if(typeof I!="string"||I.trim().length===0){y(p,400,{error:"Invalid title"});return}h.title=I.trim()}if(S!==void 0){if(!Array.isArray(S)){y(p,400,{error:"Invalid assertions"});return}let Q=S.filter(U=>typeof U=="string").map(U=>U.trim()).filter(Boolean);if(Q.length===0){y(p,400,{error:"Invalid assertions"});return}h.assertions=Q}if(!h.status&&!h.title&&!h.assertions){y(p,400,{error:"No eval changes provided"});return}let j=await A.updateCase(u,h);if(!j){y(p,404,{error:"Eval not found"});return}y(p,200,{eval:j})}async function Zn(r){let l=V.get(r);if(l)return l;let h=(await m.getThread(r))?.messages.find(d=>d.role==="human")?.feedbackSummary??"";if(h.startsWith("Synthesize evals"))return V.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return V.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return V.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return V.set(r,"materialize_model"),"materialize_model"}async function es(r,l){let p=[];for await(let j of r)p.push(typeof j=="string"?Buffer.from(j):j);let u;if(p.length>0)try{u=JSON.parse(Buffer.concat(p).toString("utf-8")).serverUrl}catch{}let h=[];w.claude?.available&&w.claude.mcp&&!w.claude.mcp.found&&h.push(await hn(u)),w.codex?.available&&w.codex.mcp&&!w.codex.mcp.found&&h.push(await fn(u)),w.copilot?.available&&w.copilot.mcp&&!w.copilot.mcp.found&&h.push(await mn(u,w.copilot.path??M));let[d,I,S]=await Promise.all([vt(t),yt(t),wt(t,w.copilot?.path??M)]);w.claude&&(w.claude.mcp=d),w.codex&&(w.codex.mcp=I),w.copilot&&(w.copilot.mcp=S),y(l,200,{results:h,capabilities:{providers:w}})}async function ts(r,l){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(l,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){y(l,400,{error:"Missing or invalid name"});return}let h=await g.addComponent(u.name);y(l,200,h)}async function ns(r,l){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(l,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){y(l,400,{error:"Missing or invalid name"});return}let h=await g.removeComponent(u.name);y(l,200,h)}async function ss(r,l){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(l,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"||typeof u.value!="string"){y(l,400,{error:"Missing or invalid path/value"});return}let h=await g.updateToken(u.path,u.value);y(l,200,h)}async function os(r,l){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(l,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"){y(l,400,{error:"Missing or invalid path"});return}let h=await g.removeToken(u.path);y(l,200,h)}function rs(r,l){let p=i??"http://localhost:3000";if(!i){let h=r.headers.referer||r.headers.origin;if(h)try{let d=new URL(typeof h=="string"?h:h[0]||"");(d.hostname==="localhost"||d.hostname==="127.0.0.1")&&(p=d.origin)}catch{}}let u=Mt(z,p);l.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),l.end(u)}async function is(r){let l=Date.now();if(ne&&l<ne.expires){y(r,200,ne.data);return}try{let{scanForComponents:p}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:u}=await import("./render-generator-HWFLZYC3.mjs"),h=await p(t);ne={data:h,expires:l+5e3},u(h,t,Pe).then(d=>{Pe=d}).catch(d=>console.warn("[Bridge] Render generation failed:",d)),y(r,200,h)}catch(p){console.error("[Bridge] Scanner error:",p),y(r,500,{error:"Failed to scan components"})}}async function as(r){let l=[fe(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),fe(t,"packages","popmelt","dist","canvas.mjs")];try{let p=tr(import.meta.url);l.unshift(fe(er(p),"canvas.mjs"))}catch{}for(let p of l)try{let u=await Tn(p,"utf-8");r.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),r.end(u);return}catch{}console.error("[Bridge] Canvas bundle not found in:",l),y(r,404,{error:"Canvas bundle not found"})}async function cs(r,l){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){y(l,400,{error:"Invalid filename"});return}try{let p=await Tn(fe(a,r)),u=r.split(".").pop()?.toLowerCase(),h=u==="png"?"image/png":u==="webp"?"image/webp":u==="jpg"||u==="jpeg"?"image/jpeg":"application/octet-stream";l.writeHead(200,{"Content-Type":h,"Cache-Control":"public, max-age=3600"}),l.end(p)}catch{y(l,404,{error:"File not found"})}}function je(r){return`/files/${ot(r)}`}async function ls(r,l){let p=await m.getThread(r);if(!p){y(l,404,{error:"Thread not found"});return}let u=(await A.loadRuns()).runs.filter(S=>S.threadId===r).sort((S,j)=>j.completedAt-S.completedAt)[0],h=u?await A.findCase(u.evalId):null,d=await g.findModelProposalByThread(r),I=p.messages.map(({screenshotPath:S,screenshotPaths:j,imagePaths:Q,replyImagePaths:U,...v})=>({...v,...v.role==="assistant"&&u?{evalRun:{...u,title:h?.title}}:{},...S?{screenshotUrl:je(S)}:{},...j?{screenshotUrls:Object.fromEntries(Object.entries(j).map(([E,C])=>[E,je(C)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([E,C])=>[E,C.map(je)]))}:{},...U?{replyImageUrls:U.map(je)}:{}}));y(l,200,{id:p.id,createdAt:p.createdAt,messages:I,modelProposal:d})}let kt=9,It=!1;for(let r=e;r<e+kt;r++)try{await pr(at,r),z=r,It=!0,console.log(`[\u22B9 is watching :${z}]`);break}catch(l){if(l.code==="EADDRINUSE"){let p=await ur(r);if(p&&p.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw l}if(!It)throw new Error(`[Bridge] All ports ${e}\u2013${e+kt-1} in use`);for(let[r,l]of Object.entries(w))!l.available||!l.path||Y(r,l.path).then(p=>{if(p)console.log(`[Bridge] ${r} warmed up`);else{console.warn(`[Bridge] ${r} warm-up failed \u2014 marking unavailable`),l.available=!1,l.path=null;for(let u of P)rt(u,{type:"capabilities_changed",data:{}})}});let ds=setInterval(()=>{An(a).catch(()=>{})},or);return{port:z,projectId:o,close:async()=>{clearInterval(ds),await k.destroyAsync();for(let r of P)try{r.res.end()}catch{}return P.clear(),new Promise(r=>{at.close(()=>r())})}}}async function An(s){try{let e=await Qo(s),n=Date.now();for(let t of e){let o=fe(s,t);try{let i=await Yo(o);n-i.mtimeMs>rr&&await Ko(o)}catch{}}}catch{}}var gr=parseInt(process.env.POPMELT_PORT||"1111",10),Dn=process.env.POPMELT_PROJECT_ROOT||process.cwd(),vr=process.env.POPMELT_DEV_ORIGIN||void 0,yr=process.env.POPMELT_COPILOT_PATH||void 0,Nn=On(Dn,".popmelt"),Jn=On(Nn,"bridge.lock");async function wr(s){await hr(Nn,{recursive:!0}),await mr(Jn,JSON.stringify({pid:process.pid,port:s,startedAt:Date.now()})+`
417
- `)}async function zn(){try{await fr(Jn)}catch{}}async function Sr(){let s=await _n({port:gr,projectRoot:Dn,devOrigin:vr,copilotPath:yr,restartMode:"detached"});await wr(s.port),await new Promise(e=>{let n=async()=>{await s.close(),await zn(),e()};process.on("SIGTERM",n),process.on("SIGINT",n)})}Sr().catch(s=>{console.error("[popmelt bridge-entry] Fatal:",s),zn().finally(()=>process.exit(1))});
413
+ ${g.title}`}),y(p,200,{proposal:g})}async function Yn(r,c){let p=decodeURIComponent(r),u=await v.dismissModelProposal(p);if(!u){y(c,404,{error:"Model proposal not found"});return}u.threadId&&await m.appendMessage(u.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${u.id}`,responseText:`Model proposal dismissed.
414
+
415
+ ${u.title}`}),y(c,200,{proposal:u})}async function Kn(r,c,p){let u=decodeURIComponent(r),h=await v.findModelProposal(u);if(!h){y(p,404,{error:"Model proposal not found"});return}if(h.status!=="applied"){y(p,400,{error:"Only applied model proposals can be projected into evals"});return}let{provider:d,model:M}=await ze(c),g=d??h.provider??O;if(g==="copilot"){y(p,400,{error:"Eval projection is not available for Copilot yet."});return}let E=await v.loadModel(),G=await A.loadSuite(),z=Kt({proposal:h,currentModel:E,existingSuite:G}),B=we().slice(0,8),Q=h.threadId??(await m.createThread(B,[])).id;ee.set(Q,"synthesize_evals"),await m.appendMessage(Q,{role:"human",timestamp:Date.now(),jobId:B,feedbackSummary:`Create eval drafts \u2014 ${h.title}`,feedbackContext:[`Model proposal: ${h.title}`,`Sources: ${h.decisionIds.length} decisions`,"Projection target: pending eval proposals"].join(`
416
+ `)});let x={id:B,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#111827",threadId:Q,kind:"synthesize_evals",provider:g,model:M??h.model};x._replyPrompt=z,x._proposalId=h.id;let _=P.enqueue(x);y(p,200,{jobId:B,position:_,threadId:Q})}async function ze(r){try{let c=[];for await(let u of r)c.push(typeof u=="string"?Buffer.from(u):u);if(c.length===0)return{};let p=JSON.parse(Buffer.concat(c).toString());return{provider:je(typeof p.provider=="string"?p.provider:void 0),model:typeof p.model=="string"&&p.model?p.model:void 0}}catch{return{}}}async function Vn(r,c){let p=await v.loadModel();if(!p){y(c,400,{error:"No model exists yet"});return}let u,h;try{let B=[];for await(let x of r)B.push(typeof x=="string"?Buffer.from(x):x);let Q=JSON.parse(Buffer.concat(B).toString());u=Q.provider,h=Q.model}catch{}if(u==="copilot"){y(c,400,{error:"Rule synthesis is not available for Copilot yet."});return}let d=nn(p),M=we().slice(0,8),E=(await m.createThread(M,[])).id;ee.set(E,"synthesize"),await m.appendMessage(E,{role:"human",timestamp:Date.now(),jobId:M,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let G={id:M,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:E,kind:"synthesize",provider:je(u),model:h||void 0};G._replyPrompt=d;let z=P.enqueue(G);y(c,200,{jobId:M,position:z,threadId:E})}async function Zn(r,c){let{provider:p,model:u}=await ze(r);if(p==="copilot"){y(c,400,{error:"Eval synthesis is not available for Copilot yet."});return}let h=await H.listDecisionIds(),d=await H.loadDecisions(h),M=await m.load(),g=await v.loadModel(),E=await A.loadSuite(),G=Xt({decisions:d,threads:M,model:g,existingSuite:E}),z=we().slice(0,8),Q=(await m.createThread(z,[])).id;ee.set(Q,"synthesize_evals"),await m.appendMessage(Q,{role:"human",timestamp:Date.now(),jobId:z,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let x={id:z,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#6b7280",threadId:Q,kind:"synthesize_evals",provider:p,model:u||void 0};x._replyPrompt=G;let _=P.enqueue(x);y(c,200,{jobId:z,position:_,threadId:Q})}async function es(r,c,p){let u=decodeURIComponent(r),h=await A.findCase(u);if(!h){y(p,404,{error:"Eval not found"});return}if(h.status!=="approved"){y(p,400,{error:"Only approved evals can be run"});return}let{screenshot:d,feedback:M,provider:g,model:E,sourceId:G}=await Ze(c),z=je(g)??O;if(z==="copilot"){y(p,400,{error:"Eval runs are not available for Copilot yet."});return}let B={};try{B=M?JSON.parse(M):{}}catch{y(p,400,{error:"Invalid eval run context JSON"});return}let Q=we().slice(0,8),x=we().slice(0,8),_=me(a,`eval-run-${Q}.webp`);await Je(_,d);let W=await A.writeRunScreenshot(Q,d),te=B.viewport,ue=te&&typeof te=="object"?te:{},le={type:"current_page",url:typeof B.url=="string"?B.url:"",viewport:{width:typeof ue.width=="number"?ue.width:0,height:typeof ue.height=="number"?ue.height:0}},ce=await v.loadModel(),pe=z==="claude"?L.name:z==="codex"?X.name:null,J=z==="codex"?Z.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),V=Yt({evalCase:h,scope:le,model:ce,screenshotPath:_,chromeDevtoolsAvailable:J}),w=(await m.createThread(x,[])).id;ee.set(w,"run_eval");let U={timestamp:new Date().toISOString(),url:le.url,viewport:le.viewport,scrollPosition:{x:typeof B.scrollX=="number"?B.scrollX:0,y:typeof B.scrollY=="number"?B.scrollY:0},annotations:[],styleModifications:[]};await m.appendMessage(w,{role:"human",timestamp:Date.now(),jobId:x,screenshotPath:_,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${le.url||"unknown"}`,"Assertions:",...h.assertions.map(fs=>`- ${fs}`)].join(`
417
+ `)});let Y={id:x,status:"queued",screenshotPath:_,feedback:U,createdAt:Date.now(),color:"#111827",threadId:w,kind:"run_eval",evalId:u,evalRunId:Q,provider:z,model:E||void 0,sourceId:G||void 0};Y._replyPrompt=V,Y._evalRunScope=le,Y._evalScreenshotPath=W;let ie=P.enqueue(Y);y(p,200,{jobId:x,runId:Q,position:ie,threadId:w,screenshotPath:W})}async function ts(r,c,p){let u=decodeURIComponent(r),h={},d,M,g;try{let G=[];for await(let B of c)G.push(typeof B=="string"?Buffer.from(B):B);let z=JSON.parse(Buffer.concat(G).toString());d=z.status,M=z.title,g=z.assertions}catch{y(p,400,{error:"Invalid JSON"});return}if(d!==void 0&&d!=="pending"&&d!=="approved"&&d!=="rejected"){y(p,400,{error:"Invalid status"});return}if(d&&(h.status=d),M!==void 0){if(typeof M!="string"||M.trim().length===0){y(p,400,{error:"Invalid title"});return}h.title=M.trim()}if(g!==void 0){if(!Array.isArray(g)){y(p,400,{error:"Invalid assertions"});return}let G=g.filter(z=>typeof z=="string").map(z=>z.trim()).filter(Boolean);if(G.length===0){y(p,400,{error:"Invalid assertions"});return}h.assertions=G}if(!h.status&&!h.title&&!h.assertions){y(p,400,{error:"No eval changes provided"});return}let E=await A.updateCase(u,h);if(!E){y(p,404,{error:"Eval not found"});return}y(p,200,{eval:E})}async function ns(r){let c=ee.get(r);if(c)return c;let h=(await m.getThread(r))?.messages.find(d=>d.role==="human")?.feedbackSummary??"";if(h.startsWith("Synthesize evals"))return ee.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return ee.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return ee.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return ee.set(r,"materialize_model"),"materialize_model"}async function ss(r,c){let p=[];for await(let E of r)p.push(typeof E=="string"?Buffer.from(E):E);let u;if(p.length>0)try{u=JSON.parse(Buffer.concat(p).toString("utf-8")).serverUrl}catch{}let h=[];S.claude?.available&&S.claude.mcp&&!S.claude.mcp.found&&h.push(await fn(u)),S.codex?.available&&S.codex.mcp&&!S.codex.mcp.found&&h.push(await mn(u)),S.copilot?.available&&S.copilot.mcp&&!S.copilot.mcp.found&&h.push(await gn(u,S.copilot.path??R));let[d,M,g]=await Promise.all([yt(t),vt(t),wt(t,S.copilot?.path??R)]);S.claude&&(S.claude.mcp=d),S.codex&&(S.codex.mcp=M),S.copilot&&(S.copilot.mcp=g),y(c,200,{results:h,capabilities:{providers:S}})}async function os(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(c,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){y(c,400,{error:"Missing or invalid name"});return}let h=await v.addComponent(u.name);y(c,200,h)}async function rs(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(c,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){y(c,400,{error:"Missing or invalid name"});return}let h=await v.removeComponent(u.name);y(c,200,h)}async function is(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(c,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"||typeof u.value!="string"){y(c,400,{error:"Missing or invalid path/value"});return}let h=await v.updateToken(u.path,u.value);y(c,200,h)}async function as(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(c,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"){y(c,400,{error:"Missing or invalid path"});return}let h=await v.removeToken(u.path);y(c,200,h)}function ls(r,c){let p=i??"http://localhost:3000";if(!i){let h=r.headers.referer||r.headers.origin;if(h)try{let d=new URL(typeof h=="string"?h:h[0]||"");(d.hostname==="localhost"||d.hostname==="127.0.0.1")&&(p=d.origin)}catch{}}let u=Rt(j,p);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(u)}async function cs(r){let c=Date.now();if(oe&&c<oe.expires){y(r,200,oe.data);return}try{let{scanForComponents:p}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:u}=await import("./render-generator-HWFLZYC3.mjs"),h=await p(t);oe={data:h,expires:c+5e3},u(h,t,ke).then(d=>{ke=d}).catch(d=>console.warn("[Bridge] Render generation failed:",d)),y(r,200,h)}catch(p){console.error("[Bridge] Scanner error:",p),y(r,500,{error:"Failed to scan components"})}}async function ds(r){let c=[me(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),me(t,"packages","popmelt","dist","canvas.mjs")];try{let p=cr(import.meta.url);c.unshift(me(lr(p),"canvas.mjs"))}catch{}for(let p of c)try{let u=await Cn(p,"utf-8");r.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),r.end(u);return}catch{}console.error("[Bridge] Canvas bundle not found in:",c),y(r,404,{error:"Canvas bundle not found"})}async function us(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){y(c,400,{error:"Invalid filename"});return}try{let p=await Cn(me(a,r)),u=r.split(".").pop()?.toLowerCase(),h=u==="png"?"image/png":u==="webp"?"image/webp":u==="jpg"||u==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":h,"Cache-Control":"public, max-age=3600"}),c.end(p)}catch{y(c,404,{error:"File not found"})}}function Be(r){return`/files/${rt(r)}`}async function ps(r,c){let p=await m.getThread(r);if(!p){y(c,404,{error:"Thread not found"});return}let u=(await A.loadRuns()).runs.filter(g=>g.threadId===r).sort((g,E)=>E.completedAt-g.completedAt)[0],h=u?await A.findCase(u.evalId):null,d=await v.findModelProposalByThread(r),M=p.messages.map(({screenshotPath:g,screenshotPaths:E,imagePaths:G,replyImagePaths:z,...B})=>({...B,...B.role==="assistant"&&u?{evalRun:{...u,title:h?.title}}:{},...g?{screenshotUrl:Be(g)}:{},...E?{screenshotUrls:Object.fromEntries(Object.entries(E).map(([Q,x])=>[Q,Be(x)]))}:{},...G?{imageUrls:Object.fromEntries(Object.entries(G).map(([Q,x])=>[Q,x.map(Be)]))}:{},...z?{replyImageUrls:z.map(Be)}:{}}));y(c,200,{id:p.id,createdAt:p.createdAt,messages:M,modelProposal:d})}let It=9,Mt=!1;for(let r=e;r<e+It;r++)try{await Sr(lt,r),j=r,Mt=!0,console.log(`[\u22B9 is watching :${j}]`);break}catch(c){if(c.code==="EADDRINUSE"){let p=await wr(r);if(p&&p.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!Mt)throw new Error(`[Bridge] All ports ${e}\u2013${e+It-1} in use`);for(let[r,c]of Object.entries(S))!c.available||!c.path||K(r,c.path).then(p=>{if(p)console.log(`[Bridge] ${r} warmed up`);else{console.warn(`[Bridge] ${r} warm-up failed \u2014 marking unavailable`),c.available=!1,c.path=null;for(let u of I)it(u,{type:"capabilities_changed",data:{}})}});let hs=setInterval(()=>{_n(a).catch(()=>{})},pr);return{port:j,projectId:o,close:async()=>{clearInterval(hs),await P.destroyAsync();for(let r of I)try{r.res.end()}catch{}return I.clear(),new Promise(r=>{lt.close(()=>r())})}}}async function _n(s){try{let e=await nr(s),n=Date.now();for(let t of e){let o=me(s,t);try{let i=await or(o);n-i.mtimeMs>hr&&await rr(o)}catch{}}}catch{}}var kr=parseInt(process.env.POPMELT_PORT||"1111",10),Jn=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Ir=process.env.POPMELT_DEV_ORIGIN||void 0,Mr=process.env.POPMELT_COPILOT_PATH||void 0,jn=Nn(Jn,".popmelt"),zn=Nn(jn,"bridge.lock");async function Rr(s){await br(jn,{recursive:!0}),await Pr(zn,JSON.stringify({pid:process.pid,port:s,startedAt:Date.now()})+`
418
+ `)}async function Bn(){try{await xr(zn)}catch{}}async function Er(){let s=await Dn({port:kr,projectRoot:Jn,devOrigin:Ir,copilotPath:Mr,restartMode:"detached"});await Rr(s.port),await new Promise(e=>{let n=async()=>{await s.close(),await Bn(),e()};process.on("SIGTERM",n),process.on("SIGINT",n)})}Er().catch(s=>{console.error("[popmelt bridge-entry] Fatal:",s),Bn().finally(()=>process.exit(1))});