@popmelt.com/core 0.7.6 → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as Jo}from"child_process";import{readFile as Bo,unlink as Fo}from"fs/promises";import{join as jo}from"path";import{execFileSync as et,spawn as Sn}from"child_process";import{createHash as Pn,randomUUID as Se}from"crypto";import{mkdir as wo,readFile as bn,readdir as So,stat as bo,unlink as xo,writeFile as Ae}from"fs/promises";import{createServer as ko}from"http";import{tmpdir as Po}from"os";import{basename as gt,dirname as Eo,join as me}from"path";import{fileURLToPath as Ro}from"url";function bt(s,t){return`<!DOCTYPE html>
2
+ import{spawn as cr}from"child_process";import{readFile as dr,unlink as ur}from"fs/promises";import{join as pr}from"path";import{execFileSync as at,spawn as Cn}from"child_process";import{createHash as Uo,randomUUID as we}from"crypto";import{mkdir as Lo,readFile as $n,readdir as Wo,realpath as Ho,stat as Go,unlink as qo,writeFile as Je}from"fs/promises";import{createServer as Qo}from"http";import{tmpdir as Xo}from"os";import{basename as rt,dirname as Yo,join as me}from"path";import{fileURLToPath as Ko}from"url";function Rt(s,e){return`<!DOCTYPE html>
3
3
  <html>
4
4
  <head>
5
5
  <meta charset="utf-8">
@@ -21,17 +21,17 @@ import{spawn as Jo}from"child_process";import{readFile as Bo,unlink as Fo}from"f
21
21
  <script type="module">
22
22
  import { mountCanvas } from 'http://localhost:${s}/canvas/app.mjs';
23
23
  mountCanvas(document.getElementById('root'), {
24
- devOrigin: '${t}',
24
+ devOrigin: '${e}',
25
25
  bridgeOrigin: 'http://localhost:${s}',
26
26
  });
27
27
  </script>
28
28
  </body>
29
- </html>`}import{spawn as qn}from"child_process";import{createInterface as Yn}from"readline";var Kn=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"]),xt=1e5;function Qn(s){let t=s.input?.file_path||s.input?.path;if(!t)return;let n=t.includes(".")?`.${t.split(".").pop().toLowerCase()}`:"";if(!Kn.has(n))return;let e;if(s.name==="Write"&&typeof s.input?.content=="string"?e=s.input.content:s.name==="Edit"&&typeof s.input?.new_string=="string"&&(e=s.input.new_string),!!e)return e.length>xt?e.slice(0,xt)+`
30
- \u2026[truncated]`:e}function Be(s,t){let{prompt:n,projectRoot:e,maxTurns:o=40,maxBudgetUsd:i=1,allowedTools:a=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:m,model:P,timeoutMs:v=3e5,onEvent:B}=t,z=[];m?z.push("--resume",m,"-p",n):z.push("-p",n),z.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(i)),P&&z.push("--model",P);for(let S of a)z.push("--allowedTools",S);let A=qn(c,z,{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),W=new Promise(S=>{let X,H=[],K=[],Z=[],Q=!1,V="",N,_,R=!1,k=setTimeout(()=>{R=!0,A.kill("SIGTERM"),setTimeout(()=>{try{A.kill("SIGKILL")}catch{}},5e3)},v),w=Yn({input:A.stdout}),C=new Set;w.on("line",x=>{if(x.trim())try{let b=JSON.parse(x);b.session_id&&!X&&(X=b.session_id);let G=b.type??(b.event?.type?`event.${b.event.type}`:"unknown");if(C.add(G),b.type==="result"&&b.result&&H.length===0){let E=typeof b.result=="string"?b.result:"";E&&(H.push(E),B?.({type:"delta",jobId:s,text:E},s))}if(b.type==="assistant"&&Array.isArray(b.message?.content)){typeof b.error=="string"&&(N=b.error);for(let E of b.message.content){if(E.type==="text"&&E.text&&(H.push(E.text),B?.({type:"delta",jobId:s,text:E.text},s)),E.type==="tool_use"&&E.name){let ie=E.input?.file_path||E.input?.path||void 0,re=Qn(E);if(B?.({type:"tool_use",jobId:s,tool:E.name,...ie?{file:ie}:{},...re?{content:re}:{}},s),E.name==="Edit"&&E.input?.file_path){let ne={tool:"Edit",file_path:E.input.file_path,old_string:E.input.old_string,new_string:E.input.new_string,replace_all:E.input.replace_all};K.push(ne),Z.push({sequence:Z.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 E.name==="Write"&&E.input?.file_path&&(K.push({tool:"Write",file_path:E.input.file_path,content:E.input.content}),Z.push({sequence:Z.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:E.input.file_path,content:typeof E.input.content=="string"?E.input.content:void 0}))}E.type==="thinking"&&E.thinking&&B?.({type:"thinking",jobId:s,text:E.thinking},s)}}b.type==="result"&&b.is_error===!0&&(Q=!0,typeof b.error=="string"&&(N=b.error),typeof b.result=="string"&&(_=b.result)),b.type==="user"&&b.tool_use_result?.file?.filePath&&B?.({type:"tool_use",jobId:s,tool:"Read",file:b.tool_use_result.file.filePath},s)}catch{}});let J=[];A.stderr?.on("data",x=>{J.push(x.toString())}),A.on("close",x=>{if(clearTimeout(k),w.close(),H.length===0&&C.size>0&&console.warn(`[Claude:${s}] No text captured. Event types seen: ${[...C].join(", ")}`),R)Q=!0,V=`Timed out after ${Math.round(v/6e4)} minutes`;else if(x!==0&&x!==null){Q=!0;let G=J.join("").trim(),E=H.join("").trim(),ie=H.length===0&&C.size>0?` (no text captured, event types: ${[...C].join(", ")})`:"";V=G||_||E||`Claude process exited with code ${x}${ie}`}Q&&!V&&_&&(V=_);let b=Vn(V,N);S({sessionId:X,text:H.join(""),success:!Q,error:Q?b.message:void 0,errorCode:Q?b.code:void 0,recoverableError:Q?b.recoverable:void 0,fileEdits:K.length>0?K:void 0,editEvents:Z.length>0?Z:void 0})}),A.on("error",x=>{clearTimeout(k),Q=!0,V=x.message,S({sessionId:X,text:H.join(""),success:!1,error:V,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:K.length>0?K:void 0,editEvents:Z.length>0?Z:void 0})})});return{process:A,result:W}}function Vn(s,t){let n=s.trim()||"Claude CLI failed",e=`${t??""} ${n}`.toLowerCase();return e.includes("authentication_failed")||e.includes("not logged in")||e.includes("please run /login")||e.includes("api key")?{message:n,code:"claude_auth_required",recoverable:!0}:e.includes("model")&&(e.includes("not found")||e.includes("unknown")||e.includes("unavailable"))?{message:n,code:"claude_model_unavailable",recoverable:!0}:{message:n,code:t||"claude_error",recoverable:!1}}import{spawn as Zn,spawnSync as Tt}from"child_process";import{readFileSync as es,statSync as ts}from"fs";import{basename as ns,extname as ss,isAbsolute as os,relative as Mt,resolve as rs}from"path";import{createInterface as is}from"readline";function kt(s){let t=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return t?t[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var Pt=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"]),st=2e5,as=1e5,Ct=2e5;function $t(s){let t=ns(s).toLowerCase(),n=ss(s).toLowerCase();return Pt.has(n)||Pt.has(t)}function _t(s,t){let n=os(t)?t:rs(s,t),e=Mt(s,n);return e===""||e.startsWith("..")?null:n}function Fe(s,t){if(!$t(t))return;let n=_t(s,t);if(n)try{let e=ts(n);return e.isFile()?e.size>st?{exists:!0,truncated:!0}:{exists:!0,content:es(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function cs(s,t){for(let n of t){let e=s[n];if(typeof e=="string")return e}}function ls(s){let t=s?.toLowerCase()??"";return t.includes("add")||t.includes("create")?"create":t.includes("delete")||t.includes("remove")?"delete":t.includes("rename")||t.includes("move")?"rename":t.includes("modify")||t.includes("update")||t.includes("edit")?"modify":"unknown"}function Et(s){return cs(s,["patch","diff","unifiedDiff","unified_diff"])}function ot(s,t){return s.length<=t?{text:s}:{text:s.slice(0,t),truncated:!0}}function Rt(s,t){let n=Tt("git",t,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:Ct+65536});return n.status!==0?null:n.stdout??""}function ds(s){let t=new Set;for(let n of s.split(`
31
- `)){if(n.length<4)continue;let e=n.slice(3).trim();if(!e)continue;e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1));let o=e.split(" -> ");for(let i of o)i&&t.add(i)}return[...t]}function It(s){let t=Rt(s,["status","--porcelain=v1","-uall"]);if(t===null)return;let n=Rt(s,["diff","--no-ext-diff","HEAD","--"])??"",e=ot(n,Ct);return{status:t,changedFiles:ds(t),...e.text?{diff:e.text}:{},...e.truncated?{diffTruncated:!0}:{}}}function us(s,t){return!s||!t?!1:s.status!==t.status||(s.diff??"")!==(t.diff??"")}function ps(s,t){if(!$t(t))return;let n=_t(s,t);if(!n)return;let e=Mt(s,n);if(e===""||e.startsWith(".."))return;let o=Tt("git",["show",`HEAD:${e}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:st+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",a=ot(i,st);return{exists:!0,content:a.text,...a.truncated?{truncated:!0}:{}}}function fs(s,t,n){return t.map(e=>{let o=n.has(e)?n.get(e):ps(s,e),i=Fe(s,e);return{filePath:e,...o?{before:o}:{},...i?{after:i}:{}}})}function je(s,t){let{prompt:n,projectRoot:e,screenshotPath:o,resumeSessionId:i,model:a,onEvent:c,sandboxMode:m="workspace-write",configOverrides:P=[]}=t,v=[];if(i){v.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${m}"`);for(let A of P)v.push("-c",A);a&&v.push("-m",a),v.push(i),v.push(n),o&&v.push("--image",o)}else{v.push("exec","--skip-git-repo-check","--json","--sandbox",m);for(let A of P)v.push("-c",A);a&&v.push("-m",a),v.push(n),o&&v.push("--image",o)}let B=Zn("codex",v,{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),z=new Promise(A=>{let W,S=[],X=[],H=[],K=new Map,Z=new Map,Q=!1,V="",N=is({input:B.stdout}),_=new Set;N.on("line",k=>{if(k.trim())try{let w=JSON.parse(k),C=w.type??"unknown";if(_.add(C),C==="thread.started"&&w.thread_id&&!W&&(W=w.thread_id),(C==="item.agentMessage.delta"||C==="item/agentMessage/delta")&&w.delta?.text&&(S.push(w.delta.text),c?.({type:"delta",jobId:s,text:w.delta.text},s)),(C==="item.reasoning.delta"||C==="item/reasoning/delta")&&w.delta?.text&&c?.({type:"thinking",jobId:s,text:w.delta.text},s),(C==="item.started"||C==="item/started")&&w.item){let J=w.item.type;if(J==="command_execution"){let x=w.item.command,b=x?kt(x):void 0,G=It(e),E=new Map;for(let re of G?.changedFiles??[])E.set(re,Fe(e,re));typeof w.item.id=="string"&&Z.set(w.item.id,{...x?{rawCommand:x}:{},...b?{command:b}:{},...G?{beforeWorktree:G}:{},beforeSnapshots:E});let ie=b?`Bash: ${b.split(`
32
- `)[0].slice(0,80)}`:"Bash";X.push(ie),c?.({type:"tool_use",jobId:s,tool:"Bash",...b?{content:b}:{}},s)}else if(J==="file_change"){let x=w.item.filename||w.item.path;x&&!K.has(x)&&K.set(x,Fe(e,x)),X.push(x?`Edit ${x.split("/").pop()}`:"Edit"),c?.({type:"tool_use",jobId:s,tool:"Edit",...x?{file:x}:{}},s)}else if(J==="file_read"){let x=w.item.filename||w.item.path;X.push(x?`Read ${x.split("/").pop()}`:"Read"),c?.({type:"tool_use",jobId:s,tool:"Read",...x?{file:x}:{}},s)}else if(J==="web_search")X.push("WebSearch"),c?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if(J==="mcp_tool_call"){let x=w.item.tool_name||w.item.name||"MCP";X.push(x),c?.({type:"tool_use",jobId:s,tool:x},s)}}if((C==="item.completed"||C==="item/completed")&&w.item){if(w.item.type==="agent_message"){let J=w.item.text;typeof J=="string"&&J&&(S.push(J),c?.({type:"delta",jobId:s,text:J},s))}else if(w.item.type==="reasoning"){let J=w.item.text;typeof J=="string"&&J&&c?.({type:"thinking",jobId:s,text:J},s)}else if(w.item.type==="file_change"&&Array.isArray(w.item.changes))for(let J of w.item.changes){let x=J.path||J.filename,b=J.kind==="add"?"Write":"Edit";if(x){X.push(`${b} ${x.split("/").pop()}`),c?.({type:"tool_use",jobId:s,tool:b,file:x},s);let G=J,E=typeof G.kind=="string"?G.kind:void 0,ie=ls(E),re=K.get(x),ne=Fe(e,x);H.push({sequence:H.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:ie,filePath:x,...re?{before:re}:{},...ne?{after:ne}:{},...Et(G)?{patch:Et(G)}:{},...E?{rawKind:E}:{}}),K.set(x,ne)}}else if(w.item.type==="command_execution"){let J=typeof w.item.id=="string"?w.item.id:void 0,x=J?Z.get(J):void 0,b=typeof w.item.command=="string"?w.item.command:x?.rawCommand,G=b?kt(b):x?.command,E=It(e);if(us(x?.beforeWorktree,E)){let ie=[...new Set([...x?.beforeWorktree?.changedFiles??[],...E?.changedFiles??[]])],re=typeof w.item.aggregated_output=="string"?ot(w.item.aggregated_output,as):void 0,ne=typeof w.item.exit_code=="number"?w.item.exit_code:w.item.exit_code===null?null:void 0,Ne=typeof w.item.status=="string"?w.item.status:void 0;H.push({sequence:H.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...b?{rawCommand:b}:{},...G?{command:G}:{},...ne!==void 0?{exitCode:ne}:{},...Ne?{status:Ne}:{},...re?{output:re.text}:{},...re?.truncated?{outputTruncated:!0}:{},...x?.beforeWorktree?{beforeWorktree:x.beforeWorktree}:{},...E?{afterWorktree:E}:{},...ie.length>0?{touchedFiles:fs(e,ie,x?.beforeSnapshots??new Map)}:{}})}J&&Z.delete(J)}}C==="turn.failed"&&(Q=!0,V=w.error?.message||w.message||"Turn failed")}catch{}});let R=[];B.stderr?.on("data",k=>{R.push(k.toString())}),B.on("close",k=>{N.close(),S.length===0&&_.size>0&&console.warn(`[Codex:${s}] No text captured. Event types seen: ${[..._].join(", ")}`),k!==0&&k!==null&&(Q=!0,V=R.join("")||`Codex process exited with code ${k}`),A({sessionId:W,text:S.join(""),success:!Q,error:Q?V:void 0,editEvents:H.length>0?H:void 0,toolsUsed:X.length>0?X:void 0})}),B.on("error",k=>{Q=!0,V=k.message,A({sessionId:W,text:S.join(""),success:!1,error:V,editEvents:H.length>0?H:void 0,toolsUsed:X.length>0?X:void 0})})});return{process:B,result:z}}import{spawn as hs}from"child_process";import{createInterface as ms}from"readline";function Ot(s,t){let n=s.trim()||"Copilot CLI failed",e=n.toLowerCase();return e.includes("no authentication information")||e.includes("not authenticated")||e.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`."}:e.includes("model")&&(e.includes("not available")||e.includes("not found")||e.includes("disabled")||e.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:t?`Copilot rejected ${t}. Choose another model or ask your administrator to enable it.`:n}:e.includes("mcp")&&(e.includes("blocked")||e.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."}:e.includes("permission")||e.includes("denied")||e.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:n}:{code:"copilot_error",recoverable:!1,message:n}}function At(s,t){let{prompt:n,projectRoot:e,resumeSessionId:o,model:i,timeoutMs:a=3e5,onEvent:c,copilotPath:m="copilot"}=t,P=["--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&&P.push(`--resume=${o}`),i&&P.push("--model",i),P.push("-p",n);let v=hs(m,P,{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),B=new Promise(z=>{let A,W=[],S=[],X=!1,H="",K=!1,Z=setTimeout(()=>{K=!0,v.kill("SIGTERM"),setTimeout(()=>{try{v.kill("SIGKILL")}catch{}},5e3)},a),Q=ms({input:v.stdout}),V=new Set,N=[];Q.on("line",R=>{if(R.trim())try{let k=JSON.parse(R),w=Pe(k);V.add(w),N.length<5&&vs(w)&&N.push(R.slice(0,800));let C=ke(k,["sessionId","session_id","id"],["session","conversation","thread"]);C&&!A&&(A=C);let J=gs(k,W.length===0);J&&(W.push(J),c?.({type:"delta",jobId:s,text:J},s));let x=ys(k);x&&c?.({type:"thinking",jobId:s,text:x},s);let b=ws(k);b&&(S.push(b.label),c?.({type:"tool_use",jobId:s,tool:b.tool,...b.file?{file:b.file}:{},...b.content?{content:b.content}:{}},s));let G=Ss(k);G&&(X=!0,H=G)}catch{}});let _=[];v.stderr?.on("data",R=>{_.push(R.toString())}),v.on("close",R=>{clearTimeout(Z),Q.close(),W.length===0&&V.size>0&&(console.warn(`[Copilot:${s}] No text captured. Event types seen: ${[...V].join(", ")}`),N.length>0&&console.warn(`[Copilot:${s}] Sample text-bearing candidates: ${N.join(`
33
- `)}`)),K?(X=!0,H=`Timed out after ${Math.round(a/6e4)} minutes`):R!==0&&R!==null&&(X=!0,H=_.join("").trim()||H||`Copilot process exited with code ${R}`);let k=X?Ot(H,i):null;z({sessionId:A,text:W.join(""),success:!X,error:k?.message,errorCode:k?.code,recoverableError:k?.recoverable,provider:"copilot",toolsUsed:S.length>0?S:void 0})}),v.on("error",R=>{clearTimeout(Z);let k=Ot(R.message,i);z({sessionId:A,text:W.join(""),success:!1,error:k.message,errorCode:k.code,recoverableError:k.recoverable,provider:"copilot",toolsUsed:S.length>0?S:void 0})})});return{process:v,result:B}}function Pe(s){if(typeof s.type=="string")return s.type;let t=s.update;return t&&typeof t.sessionUpdate=="string"?t.sessionUpdate:typeof s.event=="string"?s.event:"unknown"}function gs(s,t=!1){let n=Pe(s).toLowerCase(),e=s.update,o=e?.content;if(e?.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"&&t)return pe(s.message)??pe(s.content)??pe(s);if(n==="result"&&t)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"&&rt(s))return s.text;if(typeof s.message=="string"&&rt(s))return s.message;if(typeof s.delta=="string"&&rt(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(e=>!!e);return n.length>0?n.join(""):void 0}if(typeof s!="object")return;let t=s;if(typeof t.text=="string")return t.text;if(typeof t.content=="string")return t.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let e=pe(t[n]);if(e)return e}}function vs(s){let t=s.toLowerCase();return t.includes("assistant.message")||t==="result"}function ys(s){if(typeof s.thinking=="string")return s.thinking;if(typeof s.reasoning=="string")return s.reasoning;let t=s.update;if(t?.sessionUpdate==="reasoning_chunk"){let n=t.content;if(typeof n?.text=="string")return n.text}}function ws(s){let t=ke(s,["tool","toolName","tool_name","name"]),n=ke(s,["command","cmd"]),e=ke(s,["file","path","filename","filePath"]),o=Pe(s);if(n||o.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
34
- `)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(t)return{tool:t,label:e?`${t} ${e.split("/").pop()}`:t,...e?{file:e}:{}};if(e&&(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} ${e.split("/").pop()}`,file:e}}}function Ss(s){if(typeof s.error=="string")return s.error;if(s.error&&typeof s.error=="object"){let t=s.error;if(typeof t.message=="string")return t.message}if(typeof s.message=="string"&&Pe(s).toLowerCase().includes("error"))return s.message}function ke(s,t,n=[]){for(let e of t){let o=s[e];if(typeof o=="string")return o}for(let[e,o]of Object.entries(s)){if(!o||typeof o!="object"||n.length>0&&!n.some(a=>e.toLowerCase().includes(a)))continue;let i=ke(o,t);if(i)return i}}function rt(s){let t=Pe(s).toLowerCase();return(typeof s.role=="string"?s.role.toLowerCase():"")==="assistant"||t.includes("assistant")||t.includes("agent_message")}import{execFile as bs}from"child_process";import{copyFile as Dt,mkdir as Nt,readdir as xs,readFile as ks,writeFile as Ps}from"fs/promises";import{join as ye}from"path";var Ue=class{constructor(t){this.projectRoot=t;let n=ye(t,".popmelt");this.decisionsDir=ye(n,"decisions"),this.screenshotsDir=ye(n,"screenshots")}async persist(t,n,e){try{await Nt(this.decisionsDir,{recursive:!0}),await Nt(this.screenshotsDir,{recursive:!0});try{await Dt(n,ye(this.screenshotsDir,`s-${t.id}.webp`))}catch{}for(let o=0;o<e.length;o++)try{let i=t.pastedImagePaths[o];i&&await Dt(e[o],ye(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await Ps(ye(this.decisionsDir,`d-${t.id}.json`),JSON.stringify(t,null,2))}catch(o){console.error("[DecisionStore] Failed to persist decision record:",o)}}async listDecisionIds(){try{return(await xs(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(t){try{let n=await ks(ye(this.decisionsDir,`d-${t}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(t){return(await Promise.all(t.map(e=>this.loadDecision(e)))).filter(e=>e!==null)}captureGitDiff(t){return new Promise(n=>{bs("git",["diff","HEAD"],{cwd:t,timeout:5e3,maxBuffer:1024*1024},(e,o)=>{if(e){n(null);return}n(o||null)})})}};import{mkdir as Ee,readFile as Jt,writeFile as Re}from"fs/promises";import{join as Ie}from"path";var Es=80,Rs=24,Bt=1e3,ze=class{constructor(t){this.evalsDir=Ie(t,".popmelt","evals"),this.suitePath=Ie(this.evalsDir,"evals.json"),this.runsPath=Ie(this.evalsDir,"runs.json"),this.screenshotsDir=Ie(this.evalsDir,"screenshots")}async loadSuite(){try{let t=await Jt(this.suitePath,"utf-8"),n=JSON.parse(t);if(n?.version===1&&Array.isArray(n.cases))return n}catch{}return{version:1,updatedAt:0,cases:[]}}async loadRuns(){try{let t=await Jt(this.runsPath,"utf-8"),n=JSON.parse(t);if(n?.version===1&&Array.isArray(n.runs))return n}catch{}return{version:1,updatedAt:0,runs:[]}}async loadSuiteWithRuns(){let[t,n]=await Promise.all([this.loadSuite(),this.loadRuns()]);return{...t,runs:n.runs}}async loadSuiteWithCurrentRuns(t){let n=await this.loadSuiteWithRuns();return t?{...n,runs:n.runs.filter(e=>e.codeFingerprint===t)}:n}async writeSynthesized(t){let n=await this.loadSuite(),e=new Map(n.cases.map(a=>[a.id,a])),o=new Set;for(let a of t){let c=e.get(a.id);c&&(c.title!==a.title||c.prompt!==a.prompt||JSON.stringify(c.assertions)!==JSON.stringify(a.assertions))&&o.add(a.id),e.set(a.id,a)}let i={version:1,updatedAt:Date.now(),cases:[...e.values()]};return await Ee(this.evalsDir,{recursive:!0}),await Re(this.suitePath,JSON.stringify(i,null,2)),o.size>0&&await this.invalidateRunsForEvals(o),i}async updateCase(t,n){let e=await this.loadSuite(),o=n.title!==void 0||n.assertions!==void 0,i=e.cases.map(c=>c.id===t?{...c,...n.status?{status:n.status}:{},...n.title?{title:n.title}:{},...n.assertions?{assertions:n.assertions}:{}}:c),a=i.find(c=>c.id===t)??null;return a?(await Ee(this.evalsDir,{recursive:!0}),await Re(this.suitePath,JSON.stringify({version:1,updatedAt:Date.now(),cases:i},null,2)),o&&await this.invalidateRunsForEvals(new Set([t])),a):null}async invalidateRunsForEvals(t){let e=(await this.loadRuns()).runs.filter(i=>!t.has(i.evalId)),o={version:1,updatedAt:Date.now(),runs:e};return await Ee(this.evalsDir,{recursive:!0}),await Re(this.runsPath,JSON.stringify(o,null,2)),o}async writeRun(t){let n=await this.loadRuns(),e=[t,...n.runs.filter(i=>i.id!==t.id)].slice(0,200),o={version:1,updatedAt:Date.now(),runs:e};return await Ee(this.evalsDir,{recursive:!0}),await Re(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(t,n){return await Ee(this.screenshotsDir,{recursive:!0}),await Re(Ie(this.screenshotsDir,`eval-${t}.webp`),n),`evals/screenshots/eval-${t}.webp`}async findCase(t){return(await this.loadSuite()).cases.find(e=>e.id===t)??null}};function Ft(s){let t=s.match(/<evals>\s*([\s\S]*?)\s*<\/evals>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]),e=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return e?zt(e):null}catch{return null}}function jt(s){let t=s.match(/<eval_proposals>\s*([\s\S]*?)\s*<\/eval_proposals>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]),e=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return e?zt(e,"pending"):null}catch{return null}}function Ut(s,t){let n=s.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let e=JSON.parse(n[1]),o=_s(e.assertionResults,t),i=Os(o);return{status:i,summary:he(e.summary)||Ht(i),assertionResults:o,tooling:As(e.tooling)}}catch{}return{status:"needs_review",summary:Le(s.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:t.map(e=>({assertion:e,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function zt(s,t="approved"){let n=[];return s.forEach((e,o)=>{if(!e||typeof e!="object")return;let i=e,a=he(i.title),c=he(i.prompt),m=he(i.rationale),P=be(i.assertions);if(!a||!c||P.length===0)return;let v=Ms(i.category),B=Ds(he(i.id))||`eval-${Gt(a).slice(0,32)||o+1}`,z=Cs(i.status)??t;n.push({id:B,title:a,status:z,category:v,prompt:c,assertions:P,rationale:m||"Inferred from Popmelt design history.",sourceDecisionIds:be(i.sourceDecisionIds),sourceThreadIds:be(i.sourceThreadIds)})}),n}function Lt(s){let t=[...s.decisions].sort((e,o)=>o.createdAt-e.createdAt).slice(0,Es),n=Object.values(s.threads.threads).sort((e,o)=>o.updatedAt-e.updatedAt).slice(0,Rs);return`You are helping a designer turn organic Popmelt annotation history into a project eval suite.
29
+ </html>`}import{spawn as ls}from"child_process";import{createInterface as cs}from"readline";var ds=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"]),Tt=1e5;function us(s){let e=s.input?.file_path||s.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!ds.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>Tt?t.slice(0,Tt)+`
30
+ \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: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 A=ls(l,O,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),G=new Promise(z=>{let w,F=[],Y=[],L=[],q=!1,D="",K,k,J=!1,P=setTimeout(()=>{J=!0,A.kill("SIGTERM"),setTimeout(()=>{try{A.kill("SIGKILL")}catch{}},5e3)},b),m=cs({input:A.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&&F.length===0){let R=typeof T.result=="string"?T.result:"";R&&(F.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&&(F.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=us(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=>{$.push(g.toString())}),A.on("close",g=>{if(clearTimeout(P),m.close(),F.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=$.join("").trim(),R=F.join("").trim(),ie=F.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=ps(D,K);z({sessionId:w,text:F.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})}),A.on("error",g=>{clearTimeout(P),q=!0,D=g.message,z({sessionId:w,text:F.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:A,result:G}}function ps(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 hs,spawnSync as Dt}from"child_process";import{readFileSync as fs,statSync as ms}from"fs";import{basename as gs,extname as vs,isAbsolute as ys,relative as Nt,resolve as ws}from"path";import{createInterface as Ss}from"readline";function Ct(s){let e=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var $t=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"]),dt=2e5,bs=1e5,Jt=2e5;function zt(s){let e=gs(s).toLowerCase(),n=vs(s).toLowerCase();return $t.has(n)||$t.has(e)}function jt(s,e){let n=ys(e)?e:ws(s,e),t=Nt(s,n);return t===""||t.startsWith("..")?null:n}function Ue(s,e){if(!zt(e))return;let n=jt(s,e);if(n)try{let t=ms(n);return t.isFile()?t.size>dt?{exists:!0,truncated:!0}:{exists:!0,content:fs(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function xs(s,e){for(let n of e){let t=s[n];if(typeof t=="string")return t}}function Ps(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 xs(s,["patch","diff","unifiedDiff","unified_diff"])}function ut(s,e){return s.length<=e?{text:s}:{text:s.slice(0,e),truncated:!0}}function _t(s,e){let n=Dt("git",e,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:Jt+65536});return n.status!==0?null:n.stdout??""}function ks(s){let e=new Set;for(let n of s.split(`
31
+ `)){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 Ot(s){let e=_t(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=_t(s,["diff","--no-ext-diff","HEAD","--"])??"",t=ut(n,Jt);return{status:e,changedFiles:ks(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Is(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function Ms(s,e){if(!zt(e))return;let n=jt(s,e);if(!n)return;let t=Nt(s,n);if(t===""||t.startsWith(".."))return;let o=Dt("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:dt+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",a=ut(i,dt);return{exists:!0,content:a.text,...a.truncated?{truncated:!0}:{}}}function Es(s,e,n){return e.map(t=>{let o=n.has(t)?n.get(t):Ms(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:x=[]}=e,b=[];if(i){b.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${f}"`);for(let A of x)b.push("-c",A);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 A of x)b.push("-c",A);a&&b.push("-m",a),b.push(n),o&&b.push("--image",o)}let M=hs("codex",b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),O=new Promise(A=>{let G,z=[],w=[],F=[],Y=new Map,L=new Map,q=!1,D="",K=Ss({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),l?.({type:"delta",jobId:s,text:m.delta.text},s)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&m.delta?.text&&l?.({type:"thinking",jobId:s,text:m.delta.text},s),(W==="item.started"||W==="item/started")&&m.item){let $=m.item.type;if($==="command_execution"){let g=m.item.command,T=g?Ct(g):void 0,ee=Ot(t),R=new Map;for(let V of ee?.changedFiles??[])R.set(V,Ue(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(`
32
+ `)[0].slice(0,80)}`:"Bash";w.push(ie),l?.({type:"tool_use",jobId:s,tool:"Bash",...T?{content:T}:{}},s)}else if($==="file_change"){let g=m.item.filename||m.item.path;g&&!Y.has(g)&&Y.set(g,Ue(t,g)),w.push(g?`Edit ${g.split("/").pop()}`:"Edit"),l?.({type:"tool_use",jobId:s,tool:"Edit",...g?{file:g}:{}},s)}else if($==="file_read"){let g=m.item.filename||m.item.path;w.push(g?`Read ${g.split("/").pop()}`:"Read"),l?.({type:"tool_use",jobId:s,tool:"Read",...g?{file:g}:{}},s)}else if($==="web_search")w.push("WebSearch"),l?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if($==="mcp_tool_call"){let g=m.item.tool_name||m.item.name||"MCP";w.push(g),l?.({type:"tool_use",jobId:s,tool:g},s)}}if((W==="item.completed"||W==="item/completed")&&m.item){if(m.item.type==="agent_message"){let $=m.item.text;typeof $=="string"&&$&&(z.push($),l?.({type:"delta",jobId:s,text:$},s))}else if(m.item.type==="reasoning"){let $=m.item.text;typeof $=="string"&&$&&l?.({type:"thinking",jobId:s,text:$},s)}else if(m.item.type==="file_change"&&Array.isArray(m.item.changes))for(let $ of m.item.changes){let g=$.path||$.filename,T=$.kind==="add"?"Write":"Edit";if(g){w.push(`${T} ${g.split("/").pop()}`),l?.({type:"tool_use",jobId:s,tool:T,file:g},s);let ee=$,R=typeof ee.kind=="string"?ee.kind:void 0,ie=Ps(R),V=Y.get(g),ne=Ue(t,g);F.push({sequence:F.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:ie,filePath:g,...V?{before:V}:{},...ne?{after:ne}:{},...At(ee)?{patch:At(ee)}:{},...R?{rawKind:R}:{}}),Y.set(g,ne)}}else if(m.item.type==="command_execution"){let $=typeof m.item.id=="string"?m.item.id:void 0,g=$?L.get($):void 0,T=typeof m.item.command=="string"?m.item.command:g?.rawCommand,ee=T?Ct(T):g?.command,R=Ot(t);if(Is(g?.beforeWorktree,R)){let ie=[...new Set([...g?.beforeWorktree?.changedFiles??[],...R?.changedFiles??[]])],V=typeof m.item.aggregated_output=="string"?ut(m.item.aggregated_output,bs):void 0,ne=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",...T?{rawCommand:T}:{},...ee?{command:ee}:{},...ne!==void 0?{exitCode:ne}:{},...ke?{status:ke}:{},...V?{output:V.text}:{},...V?.truncated?{outputTruncated:!0}:{},...g?.beforeWorktree?{beforeWorktree:g.beforeWorktree}:{},...R?{afterWorktree:R}:{},...ie.length>0?{touchedFiles:Es(t,ie,g?.beforeSnapshots??new Map)}:{}})}$&&L.delete($)}}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}`),A({sessionId:G,text:z.join(""),success:!q,error:q?D:void 0,editEvents:F.length>0?F:void 0,toolsUsed:w.length>0?w:void 0})}),M.on("error",P=>{q=!0,D=P.message,A({sessionId:G,text:z.join(""),success:!1,error:D,editEvents:F.length>0?F:void 0,toolsUsed:w.length>0?w:void 0})})});return{process:M,result:O}}import{spawn as Rs}from"child_process";import{createInterface as Ts}from"readline";function Bt(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 Ft(s,e){let{prompt:n,projectRoot:t,resumeSessionId:o,model:i,timeoutMs:a=3e5,onEvent:l,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=Rs(f,x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),M=new Promise(O=>{let A,G=[],z=[],w=!1,F="",Y=!1,L=setTimeout(()=>{Y=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},a),q=Ts({input:b.stdout}),D=new Set,K=[];q.on("line",J=>{if(J.trim())try{let P=JSON.parse(J),m=Me(P);D.add(m),K.length<5&&$s(m)&&K.push(J.slice(0,800));let W=Ie(P,["sessionId","session_id","id"],["session","conversation","thread"]);W&&!A&&(A=W);let $=Cs(P,G.length===0);$&&(G.push($),l?.({type:"delta",jobId:s,text:$},s));let g=As(P);g&&l?.({type:"thinking",jobId:s,text:g},s);let T=_s(P);T&&(z.push(T.label),l?.({type:"tool_use",jobId:s,tool:T.tool,...T.file?{file:T.file}:{},...T.content?{content:T.content}:{}},s));let ee=Os(P);ee&&(w=!0,F=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(`
33
+ `)}`)),Y?(w=!0,F=`Timed out after ${Math.round(a/6e4)} minutes`):J!==0&&J!==null&&(w=!0,F=k.join("").trim()||F||`Copilot process exited with code ${J}`);let P=w?Bt(F,i):null;O({sessionId:A,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=Bt(J.message,i);O({sessionId:A,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 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 Cs(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 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"&&pt(s))return s.text;if(typeof s.message=="string"&&pt(s))return s.message;if(typeof s.delta=="string"&&pt(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 $s(s){let e=s.toLowerCase();return e.includes("assistant.message")||e==="result"}function As(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 _s(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(`
34
+ `)[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 Os(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 pt(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 Ds}from"child_process";import{copyFile as Ut,mkdir as Lt,readdir as Ns,readFile as Js,writeFile as zs}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 Lt(this.decisionsDir,{recursive:!0}),await Lt(this.screenshotsDir,{recursive:!0});try{await Ut(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 Ut(t[o],Se(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await zs(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 Ns(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 Js(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=>{Ds("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(t,o)=>{if(t){n(null);return}n(o||null)})})}};import{mkdir as Ee,readFile as Wt,writeFile as Re}from"fs/promises";import{join as Te}from"path";var js=80,Bs=24,Ht=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 Wt(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 Wt(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 Ee(this.evalsDir,{recursive:!0}),await Re(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 Ee(this.evalsDir,{recursive:!0}),await Re(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 Ee(this.evalsDir,{recursive:!0}),await Re(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 Ee(this.evalsDir,{recursive:!0}),await Re(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(e,n){return await Ee(this.screenshotsDir,{recursive:!0}),await Re(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 Gt(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?Xt(t):null}catch{return null}}function qt(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?Xt(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=Gs(t.assertionResults,e),i=qs(o);return{status:i,summary:fe(t.summary)||Zt(i),assertionResults:o,tooling:Qs(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 Xt(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),x=xe(i.assertions);if(!a||!l||x.length===0)return;let b=Ls(i.category),M=Xs(fe(i.id))||`eval-${en(a).slice(0,32)||o+1}`,O=Ws(i.status)??e;n.push({id:M,title:a,status:O,category:b,prompt:l,assertions:x,rationale:f||"Inferred from Popmelt design history.",sourceDecisionIds:xe(i.sourceDecisionIds),sourceThreadIds:xe(i.sourceThreadIds)})}),n}function Yt(s){let e=[...s.decisions].sort((t,o)=>o.createdAt-t.createdAt).slice(0,js),n=Object.values(s.threads.threads).sort((t,o)=>o.updatedAt-t.updatedAt).slice(0,Bs);return`You are helping a designer turn organic Popmelt annotation history into a project eval suite.
35
35
 
36
36
  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.
37
37
 
@@ -46,12 +46,12 @@ ${JSON.stringify(s.existingSuite,null,2)}
46
46
  \`\`\`
47
47
 
48
48
  ## Recent Decisions
49
- ${t.map(Is).join(`
49
+ ${e.map(Fs).join(`
50
50
 
51
51
  `)||"No decisions found."}
52
52
 
53
53
  ## Recent Threads
54
- ${n.map(Ts).join(`
54
+ ${n.map(Us).join(`
55
55
 
56
56
  `)||"No threads found."}
57
57
 
@@ -87,7 +87,7 @@ Allowed categories: component, layout, copy, interaction, visual, workflow.
87
87
  Return only the <evals> block after approval.
88
88
 
89
89
  ## First Response Structured Block
90
- 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 Wt(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
+ 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 Kt(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.
91
91
 
92
92
  ## Eval
93
93
  \`\`\`json
@@ -138,38 +138,88 @@ The block must be valid JSON with this shape:
138
138
  "evidenceTypes": ["screenshot", "dom", "computed_styles"]
139
139
  }
140
140
  }
141
+
141
142
  \`\`\`
142
143
 
143
144
  Allowed statuses: pass, fail, needs_review.
144
- Allowed chromeDevtools values: available, unavailable, unknown.`}function Is(s){let t=s.annotations??[],n=s.resolutions??[],e=s.editEvents??[],o=t.map(c=>c.instruction).filter(Boolean).join(`
145
- `),i=n.map(c=>{let m=c.finalScope??c.inferredScope??c.declaredScope;return`- ${c.status}: ${c.summary}${m?` [${m.breadth}/${m.target}]`:""}`}).join(`
146
- `),a=[...new Set([...n.flatMap(c=>c.filesModified??[]),...e.map(c=>c.filePath).filter(c=>!!c)])].slice(0,12);return`### Decision ${s.id}
145
+ Allowed chromeDevtools values: available, unavailable, unknown.`}function Vt(s){return`You are turning an approved Popmelt taste-model update into draft evals.
146
+
147
+ 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.
148
+
149
+ Do not edit files or run commands.
150
+
151
+ ## Approved Model Proposal
152
+ \`\`\`json
153
+ ${JSON.stringify({id:s.proposal.id,title:s.proposal.title,summary:s.proposal.summary,decisionIds:s.proposal.decisionIds,proposedModel:s.proposal.proposedModel},null,2)}
154
+ \`\`\`
155
+
156
+ ## Current Applied Model
157
+ \`\`\`json
158
+ ${JSON.stringify(s.currentModel??null,null,2)}
159
+ \`\`\`
160
+
161
+ ## Existing Eval Suite
162
+ \`\`\`json
163
+ ${JSON.stringify(s.existingSuite,null,2)}
164
+ \`\`\`
165
+
166
+ ## Instructions
167
+ 1. Generate only evals that directly project the approved model proposal into observable checks.
168
+ 2. Prefer a small number of durable evals over broad coverage. Avoid duplicates of existing evals.
169
+ 3. Each eval should include concise assertions that can be judged on a page or codebase.
170
+ 4. Set every generated eval status to "pending" so the designer can approve, edit, or reject it.
171
+ 5. Cite the proposal's decision IDs in sourceDecisionIds.
172
+ 6. End with exactly one <eval_proposals> block containing valid JSON.
173
+
174
+ Each eval must use this shape:
175
+
176
+ \`\`\`json
177
+ {
178
+ "id": "eval-short-stable-id",
179
+ "title": "Short human-readable name",
180
+ "status": "pending",
181
+ "category": "component",
182
+ "prompt": "The eval instruction an agent should satisfy.",
183
+ "assertions": ["Observable expectation 1", "Observable expectation 2"],
184
+ "rationale": "Why this eval projects the approved model value.",
185
+ "sourceDecisionIds": ["decision-id"],
186
+ "sourceThreadIds": ["${s.proposal.threadId??""}"]
187
+ }
188
+ \`\`\`
189
+
190
+ Allowed categories: component, layout, copy, interaction, visual, workflow.
191
+
192
+ <eval_proposals>
193
+ []
194
+ </eval_proposals>`}function Fs(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(l=>l.instruction).filter(Boolean).join(`
195
+ `),i=n.map(l=>{let f=l.finalScope??l.inferredScope??l.declaredScope;return`- ${l.status}: ${l.summary}${f?` [${f.breadth}/${f.target}]`:""}`}).join(`
196
+ `),a=[...new Set([...n.flatMap(l=>l.filesModified??[]),...t.map(l=>l.filePath).filter(l=>!!l)])].slice(0,12);return`### Decision ${s.id}
147
197
  Thread: ${s.threadId??"none"}
148
198
  Created: ${new Date(s.createdAt).toISOString()}
149
199
  URL: ${s.url||"unknown"}
150
200
  Instructions:
151
- ${Le(o||"(none)",Bt)}
201
+ ${Ge(o||"(none)",Ht)}
152
202
  Resolutions:
153
- ${Le(i||"(none)",Bt)}
154
- Files: ${a.length>0?a.join(", "):"none"}`}function Ts(s){let n=s.messages.slice(0,2).concat(s.messages.length>4?s.messages.slice(-2):s.messages.slice(2)).map(e=>{let o=e.feedbackSummary??e.replyToQuestion??e.question??e.responseText??"",i=e.resolutions?.map(a=>`${a.status}: ${a.summary}`).join("; ")??"";return`- ${e.role}: ${Le(o||i||"(no text)",500)}`}).join(`
203
+ ${Ge(i||"(none)",Ht)}
204
+ Files: ${a.length>0?a.join(", "):"none"}`}function Us(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(`
155
205
  `);return`### Thread ${s.id}
156
206
  Messages: ${s.messages.length}
157
207
  Updated: ${new Date(s.updatedAt).toISOString()}
158
- ${n}`}function he(s){return typeof s=="string"?s.trim():""}function be(s){return Array.isArray(s)?s.filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim()):[]}function Ms(s){let t=he(s);return t==="component"||t==="layout"||t==="copy"||t==="interaction"||t==="visual"||t==="workflow"?t:"visual"}function Cs(s){let t=he(s);return t==="pending"||t==="approved"||t==="rejected"?t:null}function $s(s){let t=he(s);return t==="pass"||t==="fail"||t==="needs_review"?t:null}function _s(s,t){let e=(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:$s(i.status)??"needs_review",summary:he(i.summary)||Ht("needs_review"),evidence:be(i.evidence)}:null}).filter(o=>o!==null);return e.length>0?e:t.map(o=>({assertion:o,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function Os(s){return s.some(t=>t.status==="fail")?"fail":s.some(t=>t.status==="needs_review")?"needs_review":"pass"}function As(s){if(!s||typeof s!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let t=s,n=he(t.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:be(t.evidenceTypes).length>0?be(t.evidenceTypes):["screenshot"]}}function Ht(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 Ds(s){return Gt(s).slice(0,48)}function Gt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Le(s,t){return s.length>t?`${s.slice(0,t)}...`:s}import{readFile as Xt,writeFile as ve}from"fs/promises";import{join as it}from"path";var te="[Materializer]",Ns={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null};function Js(s){return Array.isArray(s)?s.map((t,n)=>typeof t=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:t,sources:[]}:t&&typeof t=="object"&&typeof t.text=="string"?t:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(t),sources:[]}):[]}function Te(s){let t=[];for(let n of s){if(!n||typeof n!="object")continue;let e=n;if(typeof e.id!="string"||typeof e.text!="string"){console.warn(`${te} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}t.push({id:e.id,scope:typeof e.scope=="string"?e.scope:"general",text:e.text,sources:Array.isArray(e.sources)?e.sources.filter(o=>typeof o=="string"):[]})}return t.length>30&&console.warn(`${te} Rule count ${t.length} exceeds cap of 30`),t}var We=class{constructor(t,n,e={}){this.projectRoot=t;this.decisionStore=n;this.options=e;this.cachedIndex=null;this.running=!1;let o=it(t,".popmelt");this.indexPath=it(o,"materialized.json"),this.modelPath=it(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let t=await Xt(this.modelPath,"utf-8"),n=JSON.parse(t);return Array.isArray(n.rules)&&(n.rules=Js(n.rules)),n}catch{return null}}async addComponent(t){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let e=n.components;return e[t]?{added:!1,alreadyExists:!0}:(e[t]={description:""},await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${te} Added component "${t}" to model`),{added:!0,alreadyExists:!1})}async updateToken(t,n){let e=await this.loadModel();e||(e={tokens:{},components:{},rules:[]});let o=t.split("."),i=e;for(let m=0;m<o.length-1;m++){let P=o[m];(!i[P]||typeof i[P]!="object")&&(i[P]={}),i=i[P]}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 m=i[a];m&&typeof m=="object"&&m!==null&&"value"in m?m.value=n:i[a]=n}return await ve(this.modelPath,JSON.stringify(e,null,2)),console.log(`${te} Updated token "${t}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(t){let n=await this.loadModel();if(!n)return{removed:!1};let e=t.split("."),o=n;for(let a=0;a<e.length-1;a++){let c=e[a];if(!o[c]||typeof o[c]!="object")return{removed:!1};o=o[c]}let i=e[e.length-1];return i in o?(delete o[i],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${te} Removed token "${t}" from model`),{removed:!0}):{removed:!1}}async removeComponent(t){let n=await this.loadModel();if(!n)return{removed:!1};let e=n.components;return!e||!e[t]?{removed:!1}:(delete e[t],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${te} Removed component "${t}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let t=await this.loadIndex(),n=new Set(t.materializedIds),o=(await this.decisionStore.listDecisionIds()).filter(a=>!n.has(a));return o.length===0?[]:(await this.decisionStore.loadDecisions(o)).filter(a=>a.resolutions.some(c=>(c.finalScope??c.inferredScope)?.breadth==="pattern"))}async run(t={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;try{let n=await this.getUnmaterializedPatternDecisions();if(n.length===0)return{processedIds:[],success:!0};let e=n.map(v=>v.id);console.log(`${te} Processing ${e.length} pattern-scoped decision(s): ${e.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:e});let o=await this.loadModel(),i=Bs(n,o),a=!0,c;try{let v=`mat-${Date.now()}`,{provider:B,result:z}=this.spawnModelAgent(v,i,t,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]}),A=await z;if(!A.success)a=!1,c=A.error,console.error(`${te} ${B} spawn error:`,c);else{let W=He(A.text);W?(Array.isArray(W.rules)&&(W.rules=Te(W.rules)),await ve(this.modelPath,JSON.stringify(W,null,2)),console.log(`${te} Successfully materialized ${e.length} decision(s) with ${B} \u2192 ${this.modelPath}`)):(a=!1,c="No <model> block found in response",console.error(`${te} ${c}`))}}catch(v){a=!1,c=v instanceof Error?v.message:String(v),console.error(`${te} Error:`,c)}let m=await this.loadIndex(),P=new Set(m.materializedIds);for(let v of e)P.add(v);return m.materializedIds=[...P],m.lastRunAt=Date.now(),m.lastRunDecisionIds=e,m.lastRunError=c??null,await this.persistIndex(m),this.options.onEvent?.({type:"materialize_done",decisionIds:e,success:a,error:c}),{processedIds:e,success:a,error:c}}finally{this.running=!1}}async consolidate(t={}){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 e=Fs(n),{provider:o,result:i}=this.spawnModelAgent(`consolidate-${Date.now()}`,e,t,{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=He(a.text);return c?(Array.isArray(c.rules)&&(c.rules=Te(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 e=n instanceof Error?n.message:String(n);return console.error(`${te} Consolidation error:`,e),{success:!1,error:e}}finally{this.running=!1}}async writeModel(t){Array.isArray(t.rules)&&(t.rules=Te(t.rules)),await ve(this.modelPath,JSON.stringify(t,null,2)),console.log(`${te} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let t=await Xt(this.indexPath,"utf-8"),n=JSON.parse(t);return this.cachedIndex=n,n}catch{return this.cachedIndex={...Ns,materializedIds:[],lastRunDecisionIds:[]},this.cachedIndex}}async persistIndex(t){this.cachedIndex=t;try{await ve(this.indexPath,JSON.stringify(t,null,2))}catch(n){console.error(`${te} Failed to write index:`,n)}}spawnModelAgent(t,n,e,o){let i=e.provider??this.options.provider??"claude",a=this.options.onEvent?(c,m)=>this.options.onEvent?.(c):void 0;return i==="codex"?{provider:"codex",...je(t,{prompt:n,projectRoot:this.projectRoot,model:e.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",...Be(t,{prompt:n,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?e.model??this.options.model:void 0,timeoutMs:this.options.timeoutMs,onEvent:a})})}};function He(s){let t=s.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}function Bs(s,t){let n=s.map(i=>{let c=i.resolutions.filter(v=>(v.finalScope??v.inferredScope)?.breadth==="pattern").map(v=>{let z=(v.finalScope??v.inferredScope)?.target??"unknown",A=v.filesModified?.join(", ")??"none";return`- **${v.summary}** [scope: pattern/${z}]
208
+ ${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 Ls(s){let e=fe(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function Ws(s){let e=fe(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function Hs(s){let e=fe(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Gs(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:Hs(i.status)??"needs_review",summary:fe(i.summary)||Zt("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 qs(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Qs(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 Zt(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 Xs(s){return en(s).slice(0,48)}function en(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 tn}from"crypto";import{mkdir as ht,readFile as qe,writeFile as ye}from"fs/promises";import{dirname as ft,join as Ce}from"path";var te="[Materializer]",nn={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Ys={version:1,runs:[]},Ks={version:1,updatedAt:0,proposals:[]},Vs=12;function Zs(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 $e(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 eo(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function to(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 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(l=>!t.has(l))}}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=Zs(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 ye(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],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 ye(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 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 ye(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 ye(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(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,Vs);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(),l=oo(o,a),f=eo(o,t.totalCandidateDecisionCount,l);n=tn().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,A;try{let z=`mat-${Date.now()}`,{provider:w,result:F}=this.spawnModelAgent(z,l,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});x={...x,provider:w},await this.persistRun(x);let Y=await F;if(!Y.success)b=!1,M=Y.error,console.error(`${te} ${w} spawn error:`,M);else{let L=Xe(Y.text);if(L){Array.isArray(L.rules)&&(L.rules=$e(L.rules)),O=to(L,i);let q=await this.createModelProposal({decisionIds:i,proposedModel:L,runId:n,threadId:e.threadId,provider:w,model:e.model??this.options.model});A=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:A}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:b,error:M}),{processedIds:i,success:b,error:M,runId:n,proposalId:A}}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=ro(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 l=Xe(a.text);return l?(Array.isArray(l.rules)&&(l.rules=$e(l.rules)),!l.tokens&&n.tokens&&(l.tokens=n.tokens),!l.components&&n.components&&(l.components=n.components),await ye(this.modelPath,JSON.stringify(l,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=$e(e.rules)),await ye(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 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={...nn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...nn,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 ht(ft(this.indexPath),{recursive:!0}),await ye(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${te} 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{...Ys,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{...Ks,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:tn().slice(0,8),status:"pending",title:no(e.proposedModel),summary:so(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 ht(ft(this.proposalsPath),{recursive:!0}),await ye(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 ht(ft(this.runsPath),{recursive:!0}),await ye(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 l of e){let f=i.decisions[l],x=f?.runIds.includes(t)?f.runIds:[...f?.runIds??[],t];i.decisions[l]={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?(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(`${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 no(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 so(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 oo(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",A=b.filesModified?.join(", ")??"none";return`- **${b.summary}** [scope: pattern/${O}]
159
209
  Files modified: ${A}`}).join(`
160
- `),m=i.annotations.map(v=>v.instruction).filter(Boolean).join(`
161
- `),P=i.gitDiff?`
210
+ `),f=i.annotations.map(b=>b.instruction).filter(Boolean).join(`
211
+ `),x=i.gitDiff?`
162
212
  \`\`\`diff
163
213
  ${i.gitDiff.slice(0,2e3)}
164
214
  \`\`\``:"";return`### Decision ${i.id} (${new Date(i.createdAt).toISOString()})
165
215
  Page: ${i.url}
166
- ${c}
167
- ${P}
168
- ${m?`
216
+ ${l}
217
+ ${x}
218
+ ${f?`
169
219
  Original instructions:
170
- ${m}`:""}`}).join(`
220
+ ${f}`:""}`}).join(`
171
221
 
172
- `),e=s.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
222
+ `),t=s.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
173
223
 
174
224
  ## Instructions
175
225
  1. Review the current model (if any) and the new decisions below.
@@ -177,9 +227,9 @@ ${m}`:""}`}).join(`
177
227
  3. Output the complete updated model as a JSON object inside <model> tags.
178
228
  4. Do not edit files or run commands. Return only the <model> block.
179
229
 
180
- ${t?`## Current Model
230
+ ${e?`## Current Model
181
231
  \`\`\`json
182
- ${JSON.stringify(t,null,2)}
232
+ ${JSON.stringify(e,null,2)}
183
233
  \`\`\`
184
234
 
185
235
  Merge the new decisions into the existing model. Preserve existing entries that are not contradicted by new decisions.`:"No model exists yet. Create one from scratch based on the decisions below."}
@@ -203,7 +253,7 @@ Fields:
203
253
  - \`id\`: 8-character hex string. Preserve IDs for unchanged rules. Generate new IDs for new or merged rules.
204
254
  - \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
205
255
  - \`text\`: A clear, enforceable design rule
206
- - \`sources\`: Array of decision IDs that informed this rule. For new rules from these decisions, use: ${JSON.stringify(e)}
256
+ - \`sources\`: Array of decision IDs that informed this rule. For new rules from these decisions, use: ${JSON.stringify(t)}
207
257
 
208
258
  ### Rule guidelines
209
259
  - **Hard cap: 30 rules maximum.** Merge rules covering the same concern into one.
@@ -241,7 +291,7 @@ Example:
241
291
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
242
292
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
243
293
  - bindings: Tailwind class names (without responsive prefixes) that use this token
244
- Include property and bindings when the decision context has class-level evidence.`}function Fs(s){return`You are consolidating a design model's rules. The model has accumulated too many rules and needs cleanup.
294
+ Include property and bindings when the decision context has class-level evidence.`}function ro(s){return`You are consolidating a design model's rules. The model has accumulated too many rules and needs cleanup.
245
295
 
246
296
  ## Current Model
247
297
  \`\`\`json
@@ -280,7 +330,7 @@ Output the complete model inside <model> tags. Preserve tokens and components as
280
330
 
281
331
  <model>
282
332
  { "tokens": { ... }, "components": { ... }, "rules": [ ... ] }
283
- </model>`}function qt(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
+ </model>`}function sn(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.
284
334
 
285
335
  ## Current Model
286
336
  \`\`\`json
@@ -313,47 +363,56 @@ These are my proposed rule changes. Would you like to approve all of them, adjus
313
363
  </question>
314
364
 
315
365
  ## After approval
316
- 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.`}import{execFile as js}from"child_process";import{readFile as ct}from"fs/promises";import{homedir as Xe}from"os";import{join as ue}from"path";var lt=/popmelt/i,Us=/chrome|devtools/i;function we(){return{found:!1,name:null,scope:null,disabled:!1}}function xe(s,t,n=!1){return{found:!0,name:s,scope:t,disabled:n}}function Me(s){for(let t of Object.keys(s))if(lt.test(t))return t;return null}async function Ge(s){try{let t=await ct(s,"utf-8");return JSON.parse(t)}catch{return null}}async function dt(s){let t=Xe(),n=await Ge(ue(t,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=Me(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 m=Me(c.mcpServers);if(m){let P=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(v=>lt.test(v));return xe(m,"project",P)}}}}}let e=await Ge(ue(s,".mcp.json"));if(e&&typeof e=="object"){let o=e;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=Me(o.mcpServers);if(a){let c=await Yt(s,a);return xe(a,"mcp.json",c)}}let i=Me(o);if(i&&i!=="mcpServers"){let a=await Yt(s,i);return xe(i,"mcp.json",a)}}return we()}async function Yt(s,t){let n=ue(s,".claude","settings.local.json"),e=await Ge(n);if(e&&typeof e=="object"){let o=e;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===t)}return!1}var zs=/^\[mcp_servers\.([^\]]+)\]/;function Ls(s){return s.replace(/^"(.+)"$/,"$1")}function Ws(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function Qt(s){let t=s.split(`
317
- `),n=[],e=null;for(let o of t){let i=o.match(zs);i?(e&&n.push({name:e.name,body:e.bodyLines.join(`
318
- `)}),e={name:i[1],bodyLines:[]}):o.startsWith("[")?e&&(n.push({name:e.name,body:e.bodyLines.join(`
319
- `)}),e=null):e&&e.bodyLines.push(o)}return e&&n.push({name:e.name,body:e.bodyLines.join(`
320
- `)}),n}function Vt(s){return/enabled\s*=\s*false/i.test(s)}async function ut(s){let t=process.env.CODEX_HOME||ue(Xe(),".codex"),n=await Kt(ue(t,"config.toml"),"user");if(n.found)return n;let e=await Kt(ue(s,".codex","config.toml"),"project");return e.found?e:we()}async function Hs(s,t){let n=process.env.CODEX_HOME||ue(Xe(),".codex"),e=new Set;for(let o of[ue(n,"config.toml"),ue(s,".codex","config.toml")])try{let i=await ct(o,"utf-8");for(let a of Qt(i)){if(Ws(a.name)||Vt(a.body))continue;let c=Ls(a.name);t.test(c)&&e.add(c)}}catch{}return[...e]}async function Zt(s){return Hs(s,Us)}async function pt(s,t="copilot"){let n=await Gs(t);if(n.found)return n;let e=process.env.COPILOT_HOME||ue(Xe(),".copilot"),o=await at(ue(e,"mcp-config.json"),"user");if(o.found)return o;let i=await at(ue(s,".mcp.json"),"mcp.json");if(i.found)return i;let a=await at(ue(s,".github","mcp.json"),"mcp.json");return a.found?a:we()}async function Gs(s){try{let t=await new Promise((n,e)=>{js(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){e(o);return}n(i)})});return en(JSON.parse(t),"user")}catch{return we()}}async function at(s,t){let n=await Ge(s);return en(n,t)}function en(s,t){if(!s||typeof s!="object")return we();let n=s,e=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=Me(e);return o?xe(o,t):we()}async function Kt(s,t){try{let n=await ct(s,"utf-8"),e=Qt(n);for(let o of e)if(lt.test(o.name)){let i=Vt(o.body);return xe(o.name,t,i)}}catch{}return we()}import{execFile as tn}from"child_process";import{mkdir as Xs,readFile as nn,writeFile as sn}from"fs/promises";import{homedir as on}from"os";import{dirname as qs,join as ft}from"path";var ht="https://mcp.popmelt.com/mcp";async function rn(s=ht){let t=ft(on(),".claude.json"),n;try{let o=await nn(t,"utf-8");n=JSON.parse(o)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let e=n.mcpServers;for(let o of Object.keys(e))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return e.popmelt={type:"http",url:s},await sn(t,JSON.stringify(n,null,2)+`
321
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function an(s=ht){let t=process.env.CODEX_HOME||ft(on(),".codex"),n=ft(t,"config.toml"),e;try{e=await nn(n,"utf-8")}catch{e=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(e))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Xs(qs(n),{recursive:!0});let o=`
366
+ 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 io}from"child_process";import{readFile as gt}from"fs/promises";import{homedir as Ve}from"os";import{join as ue}from"path";var vt=/popmelt/i,ao=/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 Ae(s){for(let e of Object.keys(s))if(vt.test(e))return e;return null}async function Ke(s){try{let e=await gt(s,"utf-8");return JSON.parse(e)}catch{return null}}async function yt(s){let e=Ve(),n=await Ke(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 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=Ae(l.mcpServers);if(f){let x=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(b=>vt.test(b));return Pe(f,"project",x)}}}}}let t=await Ke(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 l=await on(s,a);return Pe(a,"mcp.json",l)}}let i=Ae(o);if(i&&i!=="mcpServers"){let a=await on(s,i);return Pe(i,"mcp.json",a)}}return be()}async function on(s,e){let n=ue(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 lo=/^\[mcp_servers\.([^\]]+)\]/;function co(s){return s.replace(/^"(.+)"$/,"$1")}function uo(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function an(s){let e=s.split(`
367
+ `),n=[],t=null;for(let o of e){let i=o.match(lo);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
368
+ `)}),t={name:i[1],bodyLines:[]}):o.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
369
+ `)}),t=null):t&&t.bodyLines.push(o)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
370
+ `)}),n}function ln(s){return/enabled\s*=\s*false/i.test(s)}async function wt(s){let e=process.env.CODEX_HOME||ue(Ve(),".codex"),n=await rn(ue(e,"config.toml"),"user");if(n.found)return n;let t=await rn(ue(s,".codex","config.toml"),"project");return t.found?t:be()}async function po(s,e){let n=process.env.CODEX_HOME||ue(Ve(),".codex"),t=new Set;for(let o of[ue(n,"config.toml"),ue(s,".codex","config.toml")])try{let i=await gt(o,"utf-8");for(let a of an(i)){if(uo(a.name)||ln(a.body))continue;let l=co(a.name);e.test(l)&&t.add(l)}}catch{}return[...t]}async function cn(s){return po(s,ao)}async function St(s,e="copilot"){let n=await ho(e);if(n.found)return n;let t=process.env.COPILOT_HOME||ue(Ve(),".copilot"),o=await mt(ue(t,"mcp-config.json"),"user");if(o.found)return o;let i=await mt(ue(s,".mcp.json"),"mcp.json");if(i.found)return i;let a=await mt(ue(s,".github","mcp.json"),"mcp.json");return a.found?a:be()}async function ho(s){try{let e=await new Promise((n,t)=>{io(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return dn(JSON.parse(e),"user")}catch{return be()}}async function mt(s,e){let n=await Ke(s);return dn(n,e)}function dn(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=Ae(t);return o?Pe(o,e):be()}async function rn(s,e){try{let n=await gt(s,"utf-8"),t=an(n);for(let o of t)if(vt.test(o.name)){let i=ln(o.body);return Pe(o.name,e,i)}}catch{}return be()}import{execFile as un}from"child_process";import{mkdir as fo,readFile as pn,writeFile as hn}from"fs/promises";import{homedir as fn}from"os";import{dirname as mo,join as bt}from"path";var xt="https://mcp.popmelt.com/mcp";async function mn(s=xt){let e=bt(fn(),".claude.json"),n;try{let o=await pn(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 hn(e,JSON.stringify(n,null,2)+`
371
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function gn(s=xt){let e=process.env.CODEX_HOME||bt(fn(),".codex"),n=bt(e,"config.toml"),t;try{t=await pn(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await fo(mo(n),{recursive:!0});let o=`
322
372
  [mcp_servers.popmelt]
323
373
  url = "${s}"
324
- `;return await sn(n,e+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function cn(s=ht,t="copilot"){let n=await Ys(t);if(Ks(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((e,o)=>{tn(t,["mcp","add","--transport","http","--json","popmelt",s],{encoding:"utf-8",timeout:1e4},i=>{if(i){o(i);return}e()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(e){return{installed:!1,provider:"copilot",scope:null,reason:e instanceof Error?e.message:"install_failed"}}}async function Ys(s){try{let t=await new Promise((n,e)=>{tn(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){e(o);return}n(i)})});return JSON.parse(t)}catch{return null}}function Ks(s){if(!s||typeof s!="object")return!1;let t=s,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t;return Object.keys(n).some(e=>/popmelt/i.test(e))}async function qe(s){let n=(s.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let e=n[1]||n[2],o=await Qs(s),i=Buffer.from(`--${e}`),a=Buffer.from(`--${e}--`),c,m,P,v,B,z,A,W,S,X,H,K,Z=[],Q=[],V=0,N=[];for(;V<o.length;){let _=o.indexOf(i,V);if(_===-1)break;let R=_+i.length;if(o.slice(_,_+a.length).equals(a))break;let k=R;o[k]===13&&o[k+1]===10&&(k+=2);let w=o.indexOf(`\r
374
+ `;return await hn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function vn(s=xt,e="copilot"){let n=await go(e);if(vo(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{un(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 go(s){try{let e=await new Promise((n,t)=>{un(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 vo(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 yo(s),i=Buffer.from(`--${t}`),a=Buffer.from(`--${t}--`),l,f,x,b,M,O,A,G,z,w,F,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
325
375
  \r
326
- `,k);if(w===-1)break;let C=o.slice(k,w).toString("utf-8"),J=w+4,x=o.indexOf(i,J),b=x!==-1?x-2:o.length;N.push({headers:C,body:o.slice(J,b)}),V=x!==-1?x:o.length}for(let _ of N){let R=_.headers.match(/name="([^"]+)"/);if(!R)continue;let k=R[1];if(k==="screenshot")c=_.body;else if(k==="feedback")m=_.body.toString("utf-8");else if(k==="color")P=_.body.toString("utf-8");else if(k==="provider")v=_.body.toString("utf-8");else if(k==="model")B=_.body.toString("utf-8");else if(k==="goal")z=_.body.toString("utf-8");else if(k==="pageUrl")A=_.body.toString("utf-8");else if(k==="viewport")W=_.body.toString("utf-8");else if(k==="planId")S=_.body.toString("utf-8");else if(k==="manifest")X=_.body.toString("utf-8");else if(k==="tasks")H=_.body.toString("utf-8");else if(k==="sourceId")K=_.body.toString("utf-8");else if(k.startsWith("screenshot-")){let w=k.slice(11);try{let C=decodeURIComponent(w);Q.push({pathname:C,data:_.body})}catch{}}else if(k.startsWith("image-")){let w=k.split("-"),C=parseInt(w[w.length-1],10),J=w.slice(1,-1).join("-");J&&!isNaN(C)&&Z.push({annotationId:J,index:C,data:_.body})}}if(!c)throw new Error("Missing screenshot field");return m||(m=""),{screenshot:c,feedback:m,color:P,provider:v,model:B,goal:z,pageUrl:A,viewport:W,planId:S,manifest:X,tasks:H,sourceId:K,pastedImages:Z,pageScreenshots:Q}}function Qs(s){return new Promise((t,n)=>{let e=[];s.on("data",o=>e.push(o)),s.on("end",()=>t(Buffer.concat(e))),s.on("error",n)})}function Ce(s,t){let n=[];if(s.annotations.length>0){n.push("## Annotations");for(let e of s.annotations){let o=e.elements.map(c=>{let m=[c.selector];return c.reactComponent&&m.push(`(${c.reactComponent})`),m.join(" ")}).join(", "),i=e.instruction||"No text";n.push(`- id=${e.id} [${e.type}] ${i} \u2192 Elements: ${o||"none"}`);let a=t?.[e.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 e of s.styleModifications){let o=e.element?.reactComponent?`(${e.element.reactComponent})`:"";for(let i of e.changes)n.push(`- ${e.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 e of s.spacingTokenChanges){n.push(`
327
- ### ${e.tokenName}: ${e.originalPx}px \u2192 ${e.newPx}px`);for(let o of e.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} ${e.originalPx}px \u2192 ${e.newPx}px`),n.push(` class="${o.className}"`)}}}if(s.inspectedElement){let e=s.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let o=[e.selector];e.reactComponent&&o.push(`(${e.reactComponent})`),e.context&&o.push(`in ${e.context}`),e.textContent&&o.push(`"${e.textContent.slice(0,80)}"`),n.push(`- ${o.join(" ")}`)}return n.join(`
328
- `)}function ln(s,t,n){let e=[],i=new Set(t.annotations.map(a=>a.pathname).filter(Boolean)).size>1;if(e.push("You are reviewing a UI screenshot with developer annotations."),e.push(""),!i&&n?.provider!=="codex"&&(e.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`),e.push("")),e.push(`The developer annotated their running app at ${t.url} (${t.viewport.width}x${t.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){e.push(""),e.push("## Previous Conversation");let a=0;for(let c of n.threadHistory)if(c.role==="human")a++,c.replyToQuestion?(e.push(`### Round ${a} (human) \u2014 reply`),e.push(`"${c.replyToQuestion}"`)):(e.push(`### Round ${a} (human)`),c.feedbackSummary&&e.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&e.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)e.push(`### Round ${a} (assistant) \u2014 question`),e.push(`"${c.question}"`);else{if(e.push(`### Round ${a} (assistant)`),c.responseText&&e.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let m of c.resolutions){let P=m.finalScope??m.inferredScope,v=P?` [${P.breadth} ${P.target}]`:"";e.push(`- ${m.annotationId}: ${m.status}${v} \u2014 ${m.summary}`),m.filesModified&&m.filesModified.length>0&&e.push(` Files: ${m.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&e.push(`Tools used: ${c.toolsUsed.join(", ")}`)}e.push(""),e.push("The current round is shown in full below.")}if(n?.designModel){e.push(""),e.push("## Established Design Policies"),e.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let a=n.designModel.rules;if(Array.isArray(a)&&a.length>0)if(e.push(""),e.push("Rules:"),a.length>0&&typeof a[0]=="object"&&a[0]!==null&&"scope"in a[0]){let v=new Map;for(let B of a)if(typeof B=="object"&&B!==null&&"text"in B){let z=B,A=z.scope||"general";v.has(A)||v.set(A,[]),v.get(A).push(z.text)}for(let[B,z]of v){e.push(`**${B.charAt(0).toUpperCase()+B.slice(1)}**`);for(let A of z)e.push(`- ${A}`)}}else for(let v of a)typeof v=="string"&&e.push(`- ${v}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(e.push(""),e.push("Design tokens:"),e.push("```json"),e.push(JSON.stringify(c,null,2)),e.push("```"));let m=n.designModel.components;m&&typeof m=="object"&&(e.push(""),e.push("Component patterns:"),e.push("```json"),e.push(JSON.stringify(m,null,2)),e.push("```")),e.push(""),e.push("### Novel Pattern Detection"),e.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),e.push("<novel>"),e.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),e.push("</novel>"),e.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),e.push("- `element`: What you are styling or creating"),e.push("- `decision`: What you decided to do (specific values)"),e.push("- `reason`: Why this is novel (what is missing from the model)"),e.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(e.push(""),e.push("## Design Context"),e.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code.")),i){let a=n?.screenshotPaths??{},c=new Map;for(let m of t.annotations){let P=m.pathname||new URL(t.url).pathname;c.has(P)||c.set(P,[]),c.get(P).push(m)}e.push(""),e.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[m,P]of c){e.push(""),e.push(`## Page: ${m}`);let v=a[m];v&&n?.provider!=="codex"?e.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${v}`):!v&&n?.provider!=="codex"&&(Object.keys(a).length===0?(e.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${s}`),e.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):e.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let B={...t,annotations:P,styleModifications:t.styleModifications},z=Ce(B,n?.imagePaths);z&&(e.push(""),e.push(z))}}else{let a=Ce(t,n?.imagePaths);a&&(e.push(""),e.push(a))}return e.push(""),e.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),e.push(""),e.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e.push(""),e.push("## Resolution"),e.push("After completing all work, output a resolution block listing what you did for each annotation:"),e.push("<resolution>"),e.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),e.push("</resolution>"),e.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),e.push(""),e.push("### Scope classification"),e.push("Each resolution MUST include scope fields:"),e.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),e.push("- `inferredScope`: What scope the change actually has, based on what you modified."),e.push("Scope has two dimensions:"),e.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),e.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),e.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),e.push("If you cannot confidently determine scope, set it to null."),e.push(""),e.push("## Questions"),e.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),e.push('<question>What do you mean by "..."?</question>'),e.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),e.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),e.join(`
329
- `)}function dn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function un(s,t,n,e){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=t.find(a=>a.role==="human"&&a.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),t.length>0){o.push(""),o.push("## Conversation History");let a=0;for(let c of t)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."),e&&e.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let a of e)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(`
330
- `)}function Vs(s){if(typeof s!="object"||s===null)return!1;let t=s;return(t.breadth==="instance"||t.breadth==="pattern")&&(t.target==="element"||t.target==="component"||t.target==="token")}function Zs(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 t=s;for(let n of["declaredScope","inferredScope","finalScope"])if(t[n]!==void 0&&t[n]!==null&&!Vs(t[n]))return!1;return!0}function pn(s){let t=s.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!t||!t[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(Zs):[]}catch{return[]}}function fn(s){let t=s.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!t?.[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(e=>{if(typeof e!="object"||e===null)return!1;let o=e;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}import{execFile as eo}from"child_process";import{readdir as to,readFile as no,stat as so}from"fs/promises";import{homedir as $e}from"os";import{join as ge}from"path";var Ke=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static"},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static"}],_e=[{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"}],Oe={id:"",label:"Default",source:"cli"},oo=/^\s*-\s+"([^"]+)"/;function ro(s){let t=[],n=!1;for(let e of s.split(`
331
- `)){if(/^\s*`model`:/.test(e)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(e))break;if(!n)continue;let o=e.match(oo);if(!o?.[1])continue;let i=o[1];t.push({id:i,label:mt(i),source:"cli"})}return Qe([Oe,...t])}function io(s){let t=JSON.parse(s);return(Array.isArray(t.models)?t.models:[]).filter(e=>e.visibility===void 0||e.visibility==="list").sort((e,o)=>{let i=typeof e.priority=="number"?e.priority:Number.MAX_SAFE_INTEGER,a=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-a}).flatMap(e=>{let o=typeof e.slug=="string"?e.slug:typeof e.id=="string"?e.id:"";if(!o)return[];let i=typeof e.display_name=="string"&&e.display_name.trim()?e.display_name.trim():mt(o);return[{id:o,label:i,source:"cli"}]})}function ao(s){let t=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Qe(t.map(n=>({id:n,label:mt(n),source:"cli"})))}function mt(s){if(!s)return"Default";let t={"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(t[s])return t[s];if(t[n])return t[n];let e=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(e){let i=e[1]==="sonnet"?"Sonn":po(e[1]),a=e[2]&&e[3]?` ${e[2]}.${e[3]}`:"";return`${i}${a}${e[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 hn(s="copilot"){let t=await Ye(s,["help","config"]),n=ro(t);return n.length>1?n:[Oe]}async function mn(s="codex"){let t=await Ye(s,["debug","models"]).catch(async()=>{let e=process.env.CODEX_HOME||ge($e(),".codex");return vn(ge(e,"models_cache.json"))}),n=io(t);return n.length>0?Qe([...n,..._e]):_e}async function gn(s="claude"){let t=ge($e(),".claude"),n=[ge($e(),".claude","stats-cache.json"),ge($e(),".claude","settings.json"),ge($e(),".claude.json"),ge(t,"cache","changelog.md")],[e,o,i]=await Promise.all([Ye(s,["--help"]).catch(()=>""),Ye(s,["--version"]).catch(()=>""),co(t).catch(()=>[])]),a=uo([...n,...i]),c=await Promise.all(a.map(P=>vn(P).catch(()=>""))),m=ao([e,o,...c].join(`
332
- `));return Qe([...Ke,...m])}function Ye(s,t,n=5e3){return new Promise((e,o)=>{eo(s,t,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}e(a)})})}async function vn(s){return no(s,"utf-8")}async function co(s){let t=[ge(s,"projects"),ge(s,"telemetry")],n=[];for(let e of t)await yn(e,n,4);return n.sort((e,o)=>o.mtimeMs-e.mtimeMs).slice(0,80).map(e=>e.path)}async function yn(s,t,n){if(n<0)return;let e;try{e=await to(s,{withFileTypes:!0})}catch{return}await Promise.all(e.map(async o=>{let i=ge(s,o.name);if(o.isDirectory()){await yn(i,t,n-1);return}if(!(!o.isFile()||!lo(o.name)))try{let a=await so(i);if(a.size>2e6)return;t.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function lo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function Qe(s){let t=new Set,n=[];for(let e of s)t.has(e.id)||(t.add(e.id),n.push(e));return n}function uo(s){return[...new Set(s)]}function po(s){return s.charAt(0).toUpperCase()+s.slice(1)}var Ve=class{constructor(t=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=t}setProcessor(t){this.processor=t}get active(){let t=this.activeJobs.values().next();return t.done?null:t.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(t,n){n?this.activeProcesses.set(t,n):this.activeProcesses.delete(t)}enqueue(t){return this.queue.push(t),this.processNext(),this.queue.length+this.activeJobs.size}addListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}broadcast(t,n,e){let o=this.bufferEvent(n,t);for(let i of this.listeners)i(o,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let o={...n,seq:e.nextSeq++};return e.events.push(o),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),o}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),o=this.accumulators.get(t)??{response:"",thinking:""},i=this.activeJobs.has(t);if(!e)return null;let a=n<0?e.events:e.events.filter(c=>c.seq>n);return{jobId:t,events:a,currentSeq:e.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(t,n,e){let o=this.accumulators.get(t);o||(o={response:"",thinking:""},this.accumulators.set(t,o)),o[n]+=e}getAccumulated(t){return this.accumulators.get(t)??null}scheduleBufferCleanup(t){let n=this.cleanupTimers.get(t);n&&clearTimeout(n);let e=setTimeout(()=>{this.eventBuffers.delete(t),this.accumulators.delete(t),this.cleanupTimers.delete(t)},6e4);this.cleanupTimers.set(t,e)}cancelJob(t){let n=this.activeProcesses.get(t),e=this.activeJobs.get(t);return!n||!e?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(t),this.activeJobs.delete(t),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:"Cancelled by user",cancelled:!0,provider:e.provider,model:e.model},e.id,e.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let t=Array.from(this.activeJobs.keys());for(let n of t)this.cancelJob(n);return!0}destroy(){for(let t of this.activeProcesses.values())t.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}async destroyAsync(t=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 e of n)try{e.kill("SIGTERM")}catch{}await Promise.all(n.map(e=>new Promise(o=>{let i=!1,a=()=>{i||(i=!0,o())};e.on("exit",a),e.on("error",a),setTimeout(()=>{if(!i){try{e.kill("SIGKILL")}catch{}setTimeout(a,500)}},t)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let t=this.queue.shift();this.activeJobs.set(t.id,t),t.status="running",this.broadcast({type:"job_started",jobId:t.id,position:0,threadId:t.threadId},t.id,t.sourceId),this.processor(t).catch(n=>{t.status="error",t.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,provider:t.provider,model:t.model},t.id,t.sourceId)}).finally(()=>{this.activeJobs.delete(t.id),this.activeProcesses.delete(t.id),this.scheduleBufferCleanup(t.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id)})}}};import{mkdir as fo,readFile as ho,writeFile as mo}from"fs/promises";import{dirname as go,join as vo}from"path";var yo={version:1,threads:{}},Ze=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=vo(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await ho(this.filePath,"utf-8"),n=JSON.parse(t);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...yo,threads:{}},this.cache}async getThread(t){return(await this.load()).threads[t]??null}async findContinuationThread(t){if(t.length===0)return null;let n=await this.load(),e=new Set(t);for(let o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>e.has(a)))return o;return null}async createThread(t,n){let e=await this.load(),o={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=o,await this.persist(),o}async appendMessage(t,n){let o=(await this.load()).threads[t];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let o=(await this.load()).threads[t];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(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((o,i)=>i.updatedAt-o.updatedAt),e.slice(0,t).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(t,n=6){let e=await this.getThread(t);return!e||e.messages.length===0?[]:e.messages.length<=n?e.messages:[e.messages[0],...e.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await fo(go(this.filePath),{recursive:!0}),await mo(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var wn="0.7.6";var Io=1111,To=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Mo=1800*1e3,Co=3600*1e3;function En(s){if(!s)return!1;try{let t=new URL(s);return t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="::1"||t.hostname==="[::1]"}catch{return!1}}function $o(s){let t=[];for(let n of s)if(n.type==="delta"){let e=n.text;if(!e)continue;let o=t[t.length-1];o&&o.kind==="text"?o.text+=e:t.push({kind:"text",text:e})}else if(n.type==="tool_use"){let e=n.tool||"",o=n.file??void 0,i=n.content??void 0,a=o?o.split("/").pop()??o:void 0,c;switch(e){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(`
333
- `)[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=e?`Using ${e}`:"tool";break}let m=o??i??void 0,P=t[t.length-1];P&&P.kind==="tool_group"&&P.tool===e?P.items.push({label:c,detail:m}):t.push({kind:"tool_group",tool:e,items:[{label:c,detail:m}]})}return t}function _o(s,t){let n=s.headers.origin;En(n)&&(t.setHeader("Access-Control-Allow-Origin",n),t.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function y(s,t,n){s.writeHead(t,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}function Oo(s,t){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||t.searchParams.get("projectId")||null}function Ao(s,t){if(!s)return t;let n=s.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return t;let[,e,o,i]=n;return`\x1B[38;2;${parseInt(e,16)};${parseInt(o,16)};${parseInt(i,16)}m${t}\x1B[0m`}function vt(s,t){try{s.res.write(`event: ${t.type}
334
- data: ${JSON.stringify(t)}
335
-
336
- `)}catch{}}function De(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function Do(s){try{let t=new AbortController,n=setTimeout(()=>t.abort(),500),e=await fetch(`http://127.0.0.1:${s}/status`,{signal:t.signal});return clearTimeout(n),e.ok?await e.json():null}catch{return null}}function No(s,t){return new Promise((n,e)=>{let o=a=>{s.removeListener("listening",i),e(a)},i=()=>{s.removeListener("error",o),n()};s.once("error",o),s.once("listening",i),s.listen(t,"127.0.0.1")})}function xn(s){try{let t=et("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],e=et("git",["status","--porcelain","--untracked-files=all",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),o=et("git",["diff","HEAD",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Pn("sha256").update(`${t}
337
- ${e}
338
- ${o}`).digest("hex").slice(0,16)}catch{return}}async function yt(s={}){let t=s.port??Io,n=s.projectRoot??process.cwd(),e=Pn("sha256").update(n).digest("hex").slice(0,12),o=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),i=s.tempDir??me(Po(),"popmelt-bridge"),a=s.maxTurns??40,c=s.maxBudgetUsd??1,m=[...s.allowedTools??To],P=s.claudePath??"claude",v=s.copilotPath??"copilot",B=s.provider??"claude",z=s.timeoutMs,A=s.restartMode??"embedded",W=t,S={},X={claude:P,codex:"codex",copilot:v};for(let[r,l]of Object.entries(X))try{let p=l.includes("/")?l:et("which",[l],{encoding:"utf-8"}).trim();S[r]={available:!0,path:p}}catch{S[r]={available:!1,path:null}}function H(r,l){return new Promise(p=>{let d=Sn(l,["--version"],{stdio:["ignore","ignore","ignore"]}),f=!1,u=O=>{f||(f=!0,p(O))},g=setTimeout(()=>{d.kill("SIGTERM"),u(!0)},5e3);d.on("error",()=>{clearTimeout(g),u(!1)}),d.on("close",O=>{clearTimeout(g),u(O===0)})})}await Promise.all([(async()=>{S.claude&&(S.claude.models=S.claude.available&&S.claude.path?await gn(S.claude.path).catch(()=>Ke):Ke)})(),(async()=>{S.codex&&(S.codex.models=S.codex.available&&S.codex.path?await mn(S.codex.path).catch(()=>_e):_e)})(),(async()=>{S.copilot&&(S.copilot.models=S.copilot.available&&S.copilot.path?await hn(S.copilot.path).catch(()=>[Oe]):[Oe])})()]);let[K,Z,Q]=await Promise.all([dt(n),ut(n),pt(n,S.copilot?.path??v)]),V=await Zt(n);S.claude&&(S.claude.mcp=K),S.codex&&(S.codex.mcp=Z),S.copilot&&(S.copilot.mcp=Q),K.found&&K.name&&m.push(`mcp__${K.name}__*`),await wo(i,{recursive:!0}),kn(i).catch(()=>{});let N=new Ve(1),_=new Set,R=new Ze(n),k=new Ue(n),w=new ze(n),C=new We(n,k,{claudePath:P,provider:B,timeoutMs:z,onEvent:r=>{for(let l of _)vt(l,r)}}),J=20,x=300*1e3,b=[],G=new Map,E=null,ie;N.addListener((r,l,p)=>{for(let d of _)(!p||!d.sourceId||d.sourceId===p)&&vt(d,r)}),N.setProcessor(async r=>{let l=r._replyPrompt,p=r._replyImagePaths,d=r.provider??B,f;if(r.threadId){let I=await R.getThread(r.threadId);if(I){for(let T=I.messages.length-1;T>=0;T--)if(I.messages[T].sessionId){f=I.messages[T].sessionId;break}}}let u;if(f&&l){let I=(await R.getThread(r.threadId))?.messages.filter(se=>se.role==="human").pop();if(u=I?.replyToQuestion||I?.feedbackSummary||"",p&&p.length>0){u+=`
339
-
340
- The developer attached reference images with their reply:`;for(let se of p)u+=`
341
- Attached image: use the Read tool to view the image at: ${se}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?u+=`
342
-
343
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:u+=`
344
-
345
- 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(f)u=Ce(r.feedback,r.imagePaths)+`
376
+ `,P);if(m===-1)break;let W=o.slice(P,m).toString("utf-8"),$=m+4,g=o.indexOf(i,$),T=g!==-1?g-2:o.length;K.push({headers:W,body:o.slice($,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")l=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")A=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")F=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),$=m.slice(1,-1).join("-");$&&!isNaN(W)&&L.push({annotationId:$,index:W,data:k.body})}}if(!l)throw new Error("Missing screenshot field");return f||(f=""),{screenshot:l,feedback:f,color:x,provider:b,model:M,goal:O,pageUrl:A,viewport:G,planId:z,manifest:w,tasks:F,sourceId:Y,pastedImages:L,pageScreenshots:q}}function yo(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(`
377
+ ### ${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(`
378
+ `)}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 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(", ")}`)}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 M of a)if(typeof M=="object"&&M!==null&&"text"in M){let O=M,A=O.scope||"general";b.has(A)||b.set(A,[]),b.get(A).push(O.text)}for(let[M,O]of b){t.push(`**${M.charAt(0).toUpperCase()+M.slice(1)}**`);for(let A of O)t.push(`- ${A}`)}}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 x=f.pathname||new URL(e.url).pathname;l.has(x)||l.set(x,[]),l.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 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 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(`
379
+ `)}function wn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Sn(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(`
380
+ `)}function wo(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 So(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&&!wo(e[n]))return!1;return!0}function bn(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(So):[]}catch{return[]}}function xn(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 bo}from"child_process";import{readdir as xo,readFile as Po,stat as ko}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"},Io=/^\s*-\s+"([^"]+)"/;function Mo(s){let e=[],n=!1;for(let t of s.split(`
381
+ `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let o=t.match(Io);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:Pt(i),source:"cli"})}return nt([Ne,...e])}function Eo(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 Ro(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":Ao(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 Pn(s="copilot"){let e=await et(s,["help","config"]),n=Mo(e);return n.length>1?n:[Ne]}async function kn(s="codex"){let e=await et(s,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||ge(Oe(),".codex");return Mn(ge(t,"models_cache.json"))}),n=Eo(e);return n.length>0?nt([...n,...De]):De}async function In(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(()=>""),To(e).catch(()=>[])]),a=$o([...n,...i]),l=await Promise.all(a.map(x=>Mn(x).catch(()=>""))),f=Ro([t,o,...l].join(`
382
+ `));return nt([...tt,...f])}function et(s,e,n=5e3){return new Promise((t,o)=>{bo(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function Mn(s){return Po(s,"utf-8")}async function To(s){let e=[ge(s,"projects"),ge(s,"telemetry")],n=[];for(let t of e)await En(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function En(s,e,n){if(n<0)return;let t;try{t=await xo(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=ge(s,o.name);if(o.isDirectory()){await En(i,e,n-1);return}if(!(!o.isFile()||!Co(o.name)))try{let a=await ko(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function Co(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 $o(s){return[...new Set(s)]}function Ao(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}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 _o,readFile as Oo,writeFile as Do}from"fs/promises";import{dirname as No,join as Jo}from"path";var zo={version:1,threads:{}},ot=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=Jo(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await Oo(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={...zo,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(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 _o(No(this.filePath),{recursive:!0}),await Do(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function Rn(s){return Bo(s).slice(0,12)}var jo=[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 Bo(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):Fo(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,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=ve(M[D-15],7)^ve(M[D-15],18)^M[D-15]>>>3,k=ve(M[D-2],17)^ve(M[D-2],19)^M[D-2]>>>10;M[D]=M[D-16]+K+M[D-7]+k>>>0}let A=t,G=o,z=i,w=a,F=l,Y=f,L=x,q=b;for(let D=0;D<64;D++){let K=ve(F,6)^ve(F,11)^ve(F,25),k=F&Y^~F&L,J=q+K+k+jo[D]+M[D]>>>0,P=ve(A,2)^ve(A,13)^ve(A,22),m=A&G^A&z^G&z,W=P+m>>>0;q=L,L=Y,Y=F,F=w+J>>>0,w=z,z=G,G=A,A=J+W>>>0}t=t+A>>>0,o=o+G>>>0,i=i+z>>>0,a=a+w>>>0,l=l+F>>>0,f=f+Y>>>0,x=x+L>>>0,b=b+q>>>0}return[t,o,i,a,l,f,x,b].map(O=>O.toString(16).padStart(8,"0")).join("")}function ve(s,e){return s>>>e|s<<32-e}function Fo(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 Tn="0.7.7";var Vo=1111,Zo=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],er=1800*1e3,tr=3600*1e3;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 nr(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,x=e[e.length-1];x&&x.kind==="tool_group"&&x.tool===t?x.items.push({label:l,detail:f}):e.push({kind:"tool_group",tool:t,items:[{label:l,detail:f}]})}return e}function sr(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(`
384
+ `)}function or(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 rr(s,e){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function ir(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}
385
+ data: ${JSON.stringify(e)}
386
+
387
+ `)}catch{}}function ze(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function ar(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 lr(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 An(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 Uo("sha256").update(`${e}
388
+ ${t}
389
+ ${o}`).digest("hex").slice(0,16)}catch{return}}async function kt(s={}){let e=s.port??Vo,n=s.projectRoot??process.cwd(),t=await Ho(n).catch(()=>n),o=Rn(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),a=s.tempDir??me(Xo(),"popmelt-bridge"),l=s.maxTurns??40,f=s.maxBudgetUsd??1,x=[...s.allowedTools??Zo],b=s.claudePath??"claude",M=s.copilotPath??"copilot",O=s.provider??"claude",A=s.timeoutMs,G=s.restartMode??"embedded",z=e,w={},F={claude:b,codex:"codex",copilot:M};for(let[r,c]of Object.entries(F))try{let p=c.includes("/")?c:at("which",[c],{encoding:"utf-8"}).trim();w[r]={available:!0,path:p}}catch{w[r]={available:!1,path:null}}function Y(r,c){return new Promise(p=>{let u=Cn(c,["--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 In(w.claude.path).catch(()=>tt):tt)})(),(async()=>{w.codex&&(w.codex.models=w.codex.available&&w.codex.path?await kn(w.codex.path).catch(()=>De):De)})(),(async()=>{w.copilot&&(w.copilot.models=w.copilot.available&&w.copilot.path?await Pn(w.copilot.path).catch(()=>[Ne]):[Ne])})()]);let[L,q,D]=await Promise.all([yt(t),wt(t),St(t,w.copilot?.path??M)]),K=await cn(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 Lo(a,{recursive:!0}),_n(a).catch(()=>{});let k=new st(1),J=new Ye,P=new Set,m=new ot(t),W=new We(t),$=new He(t),g=new Qe(t,W,{claudePath:b,provider:O,timeoutMs:A,onEvent:r=>{for(let c of P)it(c,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,ke;k.addListener((r,c,p)=>{for(let u of P)(!p||!u.sourceId||u.sourceId===p)&&it(u,r)}),J.addListener((r,c,p)=>{for(let u of P)(!p||!u.sourceId||u.sourceId===p)&&it(u,r)}),J.setProcessor(async r=>{let c=r.provider??O,p=await g.run({provider:c,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=[sr(p,h),d?["",d.title,d.summary].join(`
390
+ `):""].filter(Boolean).join(`
391
+ `);r.threadId&&await m.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:I,model:r.model,provider:c}),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:c,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 c=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&&c){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+=`
392
+
393
+ The developer attached reference images with their reply:`;for(let X of p)d+=`
394
+ Attached image: use the Read tool to view the image at: ${X}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?d+=`
395
+
396
+ Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:d+=`
397
+
398
+ 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)+`
346
399
 
347
400
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
348
401
 
349
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
402
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(u!=="codex"?`
350
403
 
351
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let I=!l&&r.threadId?await R.getThreadHistory(r.threadId):void 0,T=l?null:await C.loadModel();u=l??ln(r.screenshotPath,r.feedback,{threadHistory:I&&I.length>0?I:void 0,provider:d,imagePaths:r.imagePaths,designModel:T??void 0,screenshotPaths:r.screenshotPaths})}let g=Ao(r.color,`[\u22B9 ${W}:${r.id}]`),O=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${g} Reviewing ${O} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${f?` (resuming: ${f.slice(0,8)})`:""}`);let F=(I,T)=>{I.type==="delta"&&"text"in I?N.accumulateText(T,"response",I.text):I.type==="thinking"&&"text"in I&&N.accumulateText(T,"thinking",I.text),N.broadcast(I,T,r.sourceId)},{process:q,result:j}=d==="codex"?je(r.id,{prompt:u,projectRoot:n,screenshotPath:r.screenshotPath,resumeSessionId:f,model:r.model,onEvent:F}):d==="copilot"?At(r.id,{prompt:u,projectRoot:n,resumeSessionId:f,model:r.model,timeoutMs:z,copilotPath:S.copilot?.path??v,onEvent:F}):Be(r.id,{prompt:u,projectRoot:n,maxTurns:a,maxBudgetUsd:c,allowedTools:m,claudePath:P,resumeSessionId:f,model:r.model,timeoutMs:z,onEvent:F});N.setActiveProcess(r.id,q);let h=await j;if(r.result=h.text,h.success){console.log(`${g} Iteration complete`),h.fileEdits&&h.fileEdits.length>0&&console.log(`${g} Captured ${h.fileEdits.length} file edit(s): ${h.fileEdits.map($=>`${$.tool} ${$.file_path}`).join(", ")}`),h.editEvents&&h.editEvents.length>0&&console.log(`${g} Captured ${h.editEvents.length} edit event(s): ${h.editEvents.map($=>`${$.operation} ${$.filePath}`).join(", ")}`),r.status="done";let I=dn(h.text),T=pn(h.text);if(T.length>0&&r.annotationIds&&r.annotationIds.length>0){let $=new Set(r.annotationIds);T.every(D=>$.has(D.annotationId))||(T=T.map((D,U)=>({...D,annotationId:r.annotationIds[U%r.annotationIds.length]})))}let se=h.fileEdits&&h.fileEdits.length>0?h.fileEdits.map($=>`${$.tool} ${$.file_path.split("/").pop()}`):h.toolsUsed,ee=N.getBufferedEvents(r.id),ae=ee?$o(ee.events):void 0;if(r.threadId&&await R.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:h.text,resolutions:T.length>0?T:void 0,question:I??void 0,sessionId:h.sessionId,toolsUsed:se,editEvents:h.editEvents&&h.editEvents.length>0?h.editEvents:void 0,segments:ae&&ae.length>0?ae:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&k.captureGitDiff(n).then(async $=>{let Y=Date.now(),D=r.imagePaths?Object.values(r.imagePaths).flat():[],U=[];if(r.imagePaths)for(let[le,M]of Object.entries(r.imagePaths))for(let oe=0;oe<M.length;oe++)U.push(`screenshots/p-${r.id}-${le}-${oe}.webp`);await k.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:Y,durationMs:Y-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:U,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:d,model:r.model,sessionId:h.sessionId,threadId:r.threadId,responseText:h.text,resolutions:T.length>0?T:[],question:I??void 0,fileEdits:h.fileEdits??[],editEvents:h.editEvents??[],toolsUsed:se,gitDiff:$},r.screenshotPath,D)}).catch(()=>{}),T.length>0){let $=T.some(Y=>(Y.finalScope??Y.inferredScope)?.breadth==="pattern");$&&d!=="copilot"?C.run({provider:d,model:r.model}).catch(()=>{}):$&&console.log(`${g} Skipping materialization for Copilot provider`)}if(r.kind==="synthesize"&&h.text){let $=He(h.text);if($){Array.isArray($.rules)&&($.rules=Te($.rules));let Y=await C.loadModel();Y&&(!$.tokens&&Y.tokens&&($.tokens=Y.tokens),!$.components&&Y.components&&($.components=Y.components)),await C.writeModel($),console.log(`${g} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&h.text){let $=Ft(h.text),Y=jt(h.text),D=$??Y;if(D&&D.length>0){let U=await w.writeSynthesized(D);console.log(`${g} Eval synthesis: wrote ${D.length} ${$?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${U.cases.length} total)`)}}else if(r.kind==="run_eval"&&h.text&&r.evalId&&r.evalRunId){let $=await w.findCase(r.evalId),Y=r._evalRunScope;if($&&Y){let D=Ut(h.text,$.assertions),U=Date.now();await w.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:U,durationMs:U-r.createdAt,scope:Y,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:xn(n),rawResponse:h.text,...D}),console.log(`${g} Eval run: ${$.title} \u2192 ${D.status}`)}}I&&(console.log(`${g} \u{1F4AC} Question detected: "${I.slice(0,120)}" \u2192 broadcasting to ${_.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),N.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:I,annotationIds:r.annotationIds},r.id,r.sourceId));let ce=fn(h.text);ce.length>0&&(console.log(`${g} Novel pattern(s): ${ce.map($=>`${$.category}/${$.element}`).join(", ")}`),N.broadcast({type:"novel_patterns",jobId:r.id,patterns:ce,threadId:r.threadId},r.id,r.sourceId)),N.broadcast({type:"done",jobId:r.id,success:!0,resolutions:T.length>0?T:void 0,responseText:h.text,threadId:r.threadId},r.id,r.sourceId),b.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${g} Error: ${h.error}`),r.status="error",r.error=h.error,r.threadId&&await R.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:h.error||"Unknown error",model:r.model,provider:d}),N.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:h.error||"Unknown error",provider:d,model:r.model,recoverable:h.recoverableError,code:h.errorCode},r.id,r.sourceId),b.push({id:r.id,status:"error",completedAt:Date.now(),error:h.error,threadId:r.threadId,annotationIds:r.annotationIds});let L=Date.now()-x;for(;b.length>0&&(b[0].completedAt<L||b.length>J);)b.shift()});let re=ko(async(r,l)=>{if(_o(r,l),r.method==="OPTIONS"){l.writeHead(204),l.end();return}let p=r.url||"/",d=p.split("?")[0],f=new URL(p,`http://127.0.0.1:${W}`),u=f.pathname;if(r.headers.origin){if(!En(r.headers.origin)){y(l,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}let g=Oo(r,f);if(g!==e){y(l,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:e,requestProjectId:g,projectName:gt(n)});return}}try{if(r.method==="POST"&&u==="/send")await ne(r,l);else if(r.method==="GET"&&u==="/events")Rn(r,l);else if(r.method==="GET"&&u==="/status")In(l);else if(r.method==="PATCH"&&u==="/config")await Tn(r,l);else if(r.method==="POST"&&u==="/shutdown"){if(A!=="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:A});return}y(l,200,{ok:!0}),setTimeout(()=>process.exit(0),100)}else if(r.method==="POST"&&u==="/restart"){if(A!=="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:A});return}y(l,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let g of _)try{g.res.end()}catch{}re.close(()=>{Sn(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"&&u==="/capabilities")y(l,200,{providers:S});else if(r.method==="POST"&&u==="/mcp/install")await Nn(r,l);else if(r.method==="POST"&&u==="/reply")await Ne(r,l);else if(r.method==="POST"&&u==="/cancel")Mn(r,l);else if(r.method==="POST"&&u==="/materialize")await Cn(r,l);else if(r.method==="POST"&&u==="/model/component")await Jn(r,l);else if(r.method==="DELETE"&&u==="/model/component")await Bn(r,l);else if(r.method==="PATCH"&&u==="/model/token")await Fn(r,l);else if(r.method==="DELETE"&&u==="/model/token")await jn(r,l);else if(r.method==="POST"&&u==="/model/consolidate"){let{provider:g,model:O}=await tt(r);if(g==="copilot"){y(l,400,{error:"Model consolidation is not available for Copilot yet."});return}C.consolidate({provider:g,model:O}).catch(F=>console.error("[Bridge] Consolidation error:",F)),y(l,200,{started:!0})}else if(r.method==="POST"&&u==="/model/synthesize")await $n(r,l);else if(r.method==="POST"&&u==="/evals/synthesize")await _n(r,l);else if(r.method==="GET"&&u==="/evals"){let g=await w.loadSuiteWithCurrentRuns(xn(n));y(l,200,g)}else if(r.method==="POST"&&u.startsWith("/evals/")&&u.endsWith("/run")){let g=u.slice(7,-4);await On(g,r,l)}else if(r.method==="PATCH"&&u.startsWith("/evals/"))await An(u.slice(7),r,l);else if(r.method==="GET"&&u==="/model"){let g=await C.loadModel();y(l,200,{model:g})}else if(r.method==="GET"&&u.startsWith("/jobs/")&&u.endsWith("/events")){let g=u.slice(6,u.length-7),O=parseInt(f.searchParams.get("afterSeq")??"-1",10),F=N.getBufferedEvents(g,isNaN(O)?-1:O);F?y(l,200,F):y(l,404,{error:"Unknown job"})}else if(r.method==="GET"&&d.startsWith("/files/"))await Wn(d.slice(7),l);else if(r.method==="GET"&&u==="/threads/recent"){let g=Math.min(Math.max(parseInt(f.searchParams.get("limit")??"5",10)||5,1),20),O=await R.listRecent(g);y(l,200,O)}else if(r.method==="GET"&&u.startsWith("/thread/")){let g=u.slice(8);await Hn(g,l)}else r.method==="GET"&&(u==="/canvas"||u==="/canvas/")?Un(r,l):r.method==="GET"&&u==="/canvas/manifest"?await zn(l):r.method==="GET"&&u==="/canvas/app.mjs"?await Ln(l):y(l,404,{error:"Not found"})}catch(g){console.error("[Bridge] Request error:",g),y(l,500,{error:g instanceof Error?g.message:"Internal error"})}});async function ne(r,l){let{screenshot:p,feedback:d,color:f,provider:u,model:g,sourceId:O,pastedImages:F,pageScreenshots:q}=await qe(r),j;try{j=JSON.parse(d)}catch{y(l,400,{error:"Invalid feedback JSON"});return}let h=Se().slice(0,8),L={};if(q.length>0)for(let M of q){let oe=encodeURIComponent(M.pathname),de=me(i,`screenshot-${h}-${oe}.webp`);await Ae(de,M.data),L[M.pathname]=de}let I=me(i,`screenshot-${h}.webp`);await Ae(I,p);let T={};if(F.length>0)for(let M of F){let oe=me(i,`pasted-${h}-${M.annotationId}-${M.index}.webp`);await Ae(oe,M.data),T[M.annotationId]||(T[M.annotationId]=[]),T[M.annotationId].push(oe)}let se=j.annotations.map(M=>M.linkedSelector?M.pathname?`${M.pathname}:${M.linkedSelector}`:M.linkedSelector:null).filter(M=>!!M),ee;if(se.length>0){let M=await R.findContinuationThread(se);M?(ee=M.id,await R.addElementIdentifiers(ee,se)):ee=(await R.createThread(h,se)).id}else ee=(await R.createThread(h,[])).id;let ae=j.annotations.map(M=>M.id),ce=Object.keys(L).length>0,$={id:h,status:"queued",screenshotPath:I,feedback:j,createdAt:Date.now(),color:f,threadId:ee,annotationIds:ae,provider:De(u),model:g||void 0,...Object.keys(T).length>0?{imagePaths:T}:{},sourceId:O||void 0,...ce?{screenshotPaths:L}:{}},Y=new Set(j.annotations.map(M=>M.pathname).filter(Boolean)),D;if(Y.size>1){let M=new Map;for(let oe of j.annotations){let de=oe.pathname||"(unknown)";M.has(de)||M.set(de,[]),M.get(de).push(oe.instruction||`[${oe.type}]`)}D=[...M.entries()].map(([oe,de])=>`\`${oe}\`
352
- ${de.map(nt=>`- ${nt}`).join(`
404
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let E=!c&&r.threadId?await m.getThreadHistory(r.threadId):void 0,C=c?null:await g.loadModel();d=c??yn(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=ir(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"?Le(r.id,{prompt:d,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:h,model:r.model,onEvent:j}):u==="copilot"?Ft(r.id,{prompt:d,projectRoot:t,resumeSessionId:h,model:r.model,timeoutMs:A,copilotPath:w.copilot?.path??M,onEvent:j}):Fe(r.id,{prompt:d,projectRoot:t,maxTurns:l,maxBudgetUsd:f,allowedTools:x,claudePath:b,resumeSessionId:h,model:r.model,timeoutMs:A,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=wn(v.text),C=bn(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(B=>N.has(B.annotationId))||(C=C.map((B,H)=>({...B,annotationId:r.annotationIds[H%r.annotationIds.length]})))}let ce=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?nr(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:ce,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(),B=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:ce,gitDiff:N},r.screenshotPath,B),X&&u!=="copilot"?await It({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=Xe(v.text);if(N){Array.isArray(N.rules)&&(N.rules=$e(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=Gt(v.text),Z=qt(v.text),B=N??Z;if(B&&B.length>0){let H=await $.writeSynthesized(B),oe=r._proposalId;oe&&await g.attachGeneratedEvals(oe,B.map(_=>_.id)),console.log(`${I} Eval synthesis: wrote ${B.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 $.findCase(r.evalId),Z=r._evalRunScope;if(N&&Z){let B=Qt(v.text,N.assertions),H=Date.now();await $.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:An(t),rawResponse:v.text,...B}),console.log(`${I} Eval run: ${N.title} \u2192 ${B.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 le=xn(v.text);le.length>0&&(console.log(`${I} Novel pattern(s): ${le.map(N=>`${N.category}/${N.element}`).join(", ")}`),k.broadcast({type:"novel_patterns",jobId:r.id,patterns:le,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 lt=Qo(async(r,c)=>{if(or(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:${z}`),d=h.pathname,I=rr(r,h);if(I&&I!==o){y(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:I,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(I!==o){y(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:I,projectName:rt(t)});return}}try{if(r.method==="POST"&&d==="/send")await Dn(r,c);else if(r.method==="GET"&&d==="/events")Jn(r,c);else if(r.method==="GET"&&d==="/status")await zn(c,I);else if(r.method==="PATCH"&&d==="/config")await jn(r,c);else if(r.method==="POST"&&d==="/shutdown"){if(G!=="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:G});return}y(c,200,{ok:!0}),setTimeout(()=>process.exit(0),100)}else if(r.method==="POST"&&d==="/restart"){if(G!=="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:G});return}y(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let S of P)try{S.res.end()}catch{}lt.close(()=>{Cn(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:w});else if(r.method==="POST"&&d==="/mcp/install")await Yn(r,c);else if(r.method==="POST"&&d==="/reply")await Nn(r,c);else if(r.method==="POST"&&d==="/cancel")Bn(r,c);else if(r.method==="POST"&&d==="/materialize")await Fn(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let S=await g.loadRuns();y(c,200,S)}else if(r.method==="GET"&&d==="/model/proposals"){let S=await g.loadModelProposals();y(c,200,S)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let S=d.slice(17,-6);await Un(S,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let S=d.slice(17,-8);await Ln(S,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let S=d.slice(17,-14);await Wn(S,r,c)}else if(r.method==="POST"&&d==="/model/component")await Kn(r,c);else if(r.method==="DELETE"&&d==="/model/component")await Vn(r,c);else if(r.method==="PATCH"&&d==="/model/token")await Zn(r,c);else if(r.method==="DELETE"&&d==="/model/token")await es(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:S,model:j}=await je(r);if(S==="copilot"){y(c,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(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await Hn(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await Gn(r,c);else if(r.method==="GET"&&d==="/evals"){let S=await $.loadSuiteWithCurrentRuns(An(t));y(c,200,S)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let S=d.slice(7,-4);await qn(S,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await Qn(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let S=await g.loadModel();y(c,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(c,200,Q):y(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&u.startsWith("/files/"))await os(u.slice(7),c);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(c,200,j)}else if(r.method==="GET"&&d.startsWith("/thread/")){let S=d.slice(8);await rs(S,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?ts(r,c):r.method==="GET"&&d==="/canvas/manifest"?await ns(c):r.method==="GET"&&d==="/canvas/app.mjs"?await ss(c):y(c,404,{error:"Not found"})}catch(S){console.error("[Bridge] Request error:",S),y(c,500,{error:S instanceof Error?S.message:"Internal error"})}});async function Dn(r,c){let{screenshot:p,feedback:u,color:h,provider:d,model:I,sourceId:S,pastedImages:j,pageScreenshots:Q}=await Ze(r),U;try{U=JSON.parse(u)}catch{y(c,400,{error:"Invalid feedback JSON"});return}let v=we().slice(0,8),E={};if(Q.length>0)for(let _ of Q){let re=encodeURIComponent(_.pathname),de=me(a,`screenshot-${v}-${re}.webp`);await Je(de,_.data),E[_.pathname]=de}let C=me(a,`screenshot-${v}.webp`);await Je(C,p);let X={};if(j.length>0)for(let _ of j){let re=me(a,`pasted-${v}-${_.annotationId}-${_.index}.webp`);await Je(re,_.data),X[_.annotationId]||(X[_.annotationId]=[]),X[_.annotationId].push(re)}let ce=U.annotations.map(_=>_.linkedSelector?_.pathname?`${_.pathname}:${_.linkedSelector}`:_.linkedSelector:null).filter(_=>!!_),se;if(ce.length>0){let _=await m.findContinuationThread(ce);_?(se=_.id,await m.addElementIdentifiers(se,ce)):se=(await m.createThread(v,ce)).id}else se=(await m.createThread(v,[])).id;let ae=U.annotations.map(_=>_.id),le=Object.keys(E).length>0,N={id:v,status:"queued",screenshotPath:C,feedback:U,createdAt:Date.now(),color:h,threadId:se,annotationIds:ae,provider:ze(d),model:I||void 0,...Object.keys(X).length>0?{imagePaths:X}:{},sourceId:S||void 0,...le?{screenshotPaths:E}:{}},Z=new Set(U.annotations.map(_=>_.pathname).filter(Boolean)),B;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}]`)}B=[..._.entries()].map(([re,de])=>`\`${re}\`
405
+ ${de.map(ct=>`- ${ct}`).join(`
353
406
  `)}`).join(`
354
- `)}else D=j.annotations.map(M=>M.instruction||`[${M.type}]`).join("; ");let U=Ce(j,Object.keys(T).length>0?T:void 0);await R.appendMessage(ee,{role:"human",timestamp:Date.now(),jobId:h,screenshotPath:I,...ce?{screenshotPaths:L}:{},...Object.keys(T).length>0?{imagePaths:T}:{},annotationIds:ae,feedbackSummary:D,feedbackContext:U||void 0});let le=N.enqueue($);y(l,200,{jobId:h,position:le,threadId:ee})}async function Ne(r,l){let p=r.headers["content-type"]||"",d,f,u,g,O,F,q=[];if(p.includes("multipart/form-data")){let D=await qe(r),U=D.feedback?JSON.parse(D.feedback):{};d=U.threadId,f=U.reply,u=U.color,g=U.provider,O=U.model,F=U.sourceId||D.sourceId;for(let le of D.pastedImages)q.push(le.data)}else{let D=[];for await(let M of r)D.push(typeof M=="string"?Buffer.from(M):M);let U=Buffer.concat(D).toString("utf-8"),le;try{le=JSON.parse(U)}catch{y(l,400,{error:"Invalid JSON"});return}d=le.threadId,f=le.reply,u=le.color,g=le.provider,O=le.model,F=le.sourceId}if(!d||!f){y(l,400,{error:"Missing threadId or reply"});return}if(!await R.getThread(d)){y(l,404,{error:"Thread not found"});return}let h=Se().slice(0,8),L=[];for(let D=0;D<q.length;D++){let U=me(i,`reply-${h}-${D}.webp`);await Ae(U,q[D]),L.push(U)}let I="";{let D=await R.getThreadHistory(d);for(let U=D.length-1;U>=0;U--)if(D[U].screenshotPath){I=D[U].screenshotPath;break}}let T=await Dn(d);if(!I&&!T){y(l,400,{error:"No screenshot available"});return}await R.appendMessage(d,{role:"human",timestamp:Date.now(),jobId:h,replyToQuestion:f,screenshotPath:I,...L.length>0?{replyImagePaths:L}:{}});let se=await R.getThreadHistory(d),ee=[];for(let D of se)if(D.annotationIds)for(let U of D.annotationIds)ee.includes(U)||ee.push(U);let ae=De(g),ce=un(I,se,ae,L.length>0?L:void 0),$={id:h,status:"queued",screenshotPath:I,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:u,threadId:d,annotationIds:ee.length>0?ee:void 0,provider:ae,model:O||void 0,sourceId:F||void 0};T&&($.kind=T),$._replyPrompt=ce,L.length>0&&($._replyImagePaths=L);let Y=N.enqueue($);y(l,200,{jobId:h,position:Y,threadId:d})}function Rn(r,l){l.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),l.write(`event: connected
407
+ `)}else B=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,...le?{screenshotPaths:E}:{},...Object.keys(X).length>0?{imagePaths:X}:{},annotationIds:ae,feedbackSummary:B,feedbackContext:H||void 0});let oe=k.enqueue(N);y(c,200,{jobId:v,position:oe,threadId:se})}async function Nn(r,c){let p=r.headers["content-type"]||"",u,h,d,I,S,j,Q=[];if(p.includes("multipart/form-data")){let B=await Ze(r),H=B.feedback?JSON.parse(B.feedback):{};u=H.threadId,h=H.reply,d=H.color,I=H.provider,S=H.model,j=H.sourceId||B.sourceId;for(let oe of B.pastedImages)Q.push(oe.data)}else{let B=[];for await(let _ of r)B.push(typeof _=="string"?Buffer.from(_):_);let H=Buffer.concat(B).toString("utf-8"),oe;try{oe=JSON.parse(H)}catch{y(c,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(c,400,{error:"Missing threadId or reply"});return}if(!await m.getThread(u)){y(c,404,{error:"Thread not found"});return}let v=we().slice(0,8),E=[];for(let B=0;B<Q.length;B++){let H=me(a,`reply-${v}-${B}.webp`);await Je(H,Q[B]),E.push(H)}let C="";{let B=await m.getThreadHistory(u);for(let H=B.length-1;H>=0;H--)if(B[H].screenshotPath){C=B[H].screenshotPath;break}}let X=await Xn(u);if(!C&&!X){y(c,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 ce=await m.getThreadHistory(u),se=[];for(let B of ce)if(B.annotationIds)for(let H of B.annotationIds)se.includes(H)||se.push(H);let ae=ze(I),le=Sn(C,ce,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=le,E.length>0&&(N._replyImagePaths=E);let Z=k.enqueue(N);y(c,200,{jobId:v,position:Z,threadId:u})}function Jn(r,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
355
408
  data: {"status":"connected"}
356
409
 
357
- `);let d=new URL(r.url||"/",`http://127.0.0.1:${W}`).searchParams.get("sourceId")||void 0,f={id:Se().slice(0,8),res:l,sourceId:d};_.add(f),r.on("close",()=>{_.delete(f)})}function In(r){let l=N.allActive;y(r,200,{ok:!0,version:wn,restartMode:A,projectId:e,projectName:gt(n),devOrigin:o,activeJob:l[0]?{id:l[0].id,status:l[0].status}:null,activeJobs:l.map(p=>({id:p.id,status:p.status,threadId:p.threadId,annotationIds:p.annotationIds,color:p.color,kind:p.kind})),queueDepth:N.depth,recentJobs:b})}async function Tn(r,l){let p=await new Promise(d=>{let f="";r.on("data",u=>{f+=u.toString()}),r.on("end",()=>d(f))});try{let d=JSON.parse(p);typeof d.devOrigin=="string"&&(o=d.devOrigin||null),y(l,200,{ok:!0,devOrigin:o})}catch{y(l,400,{error:"Invalid JSON"})}}async function Mn(r,l){let d=new URL(r.url||"/",`http://127.0.0.1:${W}`).searchParams.get("jobId"),u=(d?N.allActive.filter(O=>O.id===d):N.allActive).map(O=>O.threadId).filter(Boolean),g=d?N.cancelJob(d):N.cancelActive();for(let O of u)await R.appendMessage(O,{role:"assistant",timestamp:Date.now(),jobId:d||"",cancelled:!0});y(l,200,{cancelled:g})}async function Cn(r,l){if(C.isRunning){y(l,200,{skipped:!0,reason:"Already running"});return}let{provider:p,model:d}=await tt(r);if(p==="copilot"){y(l,400,{error:"Materialization is not available for Copilot yet."});return}let f=await C.getUnmaterializedPatternDecisions();if(f.length===0){y(l,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}C.run({provider:p,model:d}).catch(()=>{}),y(l,200,{started:!0,decisionCount:f.length,decisionIds:f.map(u=>u.id)})}async function tt(r){try{let l=[];for await(let d of r)l.push(typeof d=="string"?Buffer.from(d):d);if(l.length===0)return{};let p=JSON.parse(Buffer.concat(l).toString());return{provider:De(typeof p.provider=="string"?p.provider:void 0),model:typeof p.model=="string"&&p.model?p.model:void 0}}catch{return{}}}async function $n(r,l){let p=await C.loadModel();if(!p){y(l,400,{error:"No model exists yet"});return}let d,f;try{let h=[];for await(let I of r)h.push(typeof I=="string"?Buffer.from(I):I);let L=JSON.parse(Buffer.concat(h).toString());d=L.provider,f=L.model}catch{}if(d==="copilot"){y(l,400,{error:"Rule synthesis is not available for Copilot yet."});return}let u=qt(p),g=Se().slice(0,8),F=(await R.createThread(g,[])).id;G.set(F,"synthesize"),await R.appendMessage(F,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let q={id:g,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:F,kind:"synthesize",provider:De(d),model:f||void 0};q._replyPrompt=u;let j=N.enqueue(q);y(l,200,{jobId:g,position:j,threadId:F})}async function _n(r,l){let{provider:p,model:d}=await tt(r);if(p==="copilot"){y(l,400,{error:"Eval synthesis is not available for Copilot yet."});return}let f=await k.listDecisionIds(),u=await k.loadDecisions(f),g=await R.load(),O=await C.loadModel(),F=await w.loadSuite(),q=Lt({decisions:u,threads:g,model:O,existingSuite:F}),j=Se().slice(0,8),L=(await R.createThread(j,[])).id;G.set(L,"synthesize_evals"),await R.appendMessage(L,{role:"human",timestamp:Date.now(),jobId:j,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let I={id:j,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:L,kind:"synthesize_evals",provider:p,model:d||void 0};I._replyPrompt=q;let T=N.enqueue(I);y(l,200,{jobId:j,position:T,threadId:L})}async function On(r,l,p){let d=decodeURIComponent(r),f=await w.findCase(d);if(!f){y(p,404,{error:"Eval not found"});return}if(f.status!=="approved"){y(p,400,{error:"Only approved evals can be run"});return}let{screenshot:u,feedback:g,provider:O,model:F,sourceId:q}=await qe(l),j=De(O)??B;if(j==="copilot"){y(p,400,{error:"Eval runs are not available for Copilot yet."});return}let h={};try{h=g?JSON.parse(g):{}}catch{y(p,400,{error:"Invalid eval run context JSON"});return}let L=Se().slice(0,8),I=Se().slice(0,8),T=me(i,`eval-run-${L}.webp`);await Ae(T,u);let se=await w.writeRunScreenshot(L,u),ee=h.viewport,ae=ee&&typeof ee=="object"?ee:{},ce={type:"current_page",url:typeof h.url=="string"?h.url:"",viewport:{width:typeof ae.width=="number"?ae.width:0,height:typeof ae.height=="number"?ae.height:0}},$=await C.loadModel(),Y=j==="claude"?K.name:j==="codex"?Z.name:null,D=j==="codex"?V.length>0:typeof Y=="string"&&/chrome|devtools/i.test(Y),U=Wt({evalCase:f,scope:ce,model:$,screenshotPath:T,chromeDevtoolsAvailable:D}),M=(await R.createThread(I,[])).id;G.set(M,"run_eval");let oe={timestamp:new Date().toISOString(),url:ce.url,viewport:ce.viewport,scrollPosition:{x:typeof h.scrollX=="number"?h.scrollX:0,y:typeof h.scrollY=="number"?h.scrollY:0},annotations:[],styleModifications:[]};await R.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:I,screenshotPath:T,feedbackSummary:`Run eval \u2014 ${f.title}`,feedbackContext:[`Eval: ${f.title}`,"Scope: current page",`URL: ${ce.url||"unknown"}`,"Assertions:",...f.assertions.map(Xn=>`- ${Xn}`)].join(`
358
- `)});let de={id:I,status:"queued",screenshotPath:T,feedback:oe,createdAt:Date.now(),color:"#111827",threadId:M,kind:"run_eval",evalId:d,evalRunId:L,provider:j,model:F||void 0,sourceId:q||void 0};de._replyPrompt=U,de._evalRunScope=ce,de._evalScreenshotPath=se;let nt=N.enqueue(de);y(p,200,{jobId:I,runId:L,position:nt,threadId:M,screenshotPath:se})}async function An(r,l,p){let d=decodeURIComponent(r),f={},u,g,O;try{let q=[];for await(let h of l)q.push(typeof h=="string"?Buffer.from(h):h);let j=JSON.parse(Buffer.concat(q).toString());u=j.status,g=j.title,O=j.assertions}catch{y(p,400,{error:"Invalid JSON"});return}if(u!==void 0&&u!=="pending"&&u!=="approved"&&u!=="rejected"){y(p,400,{error:"Invalid status"});return}if(u&&(f.status=u),g!==void 0){if(typeof g!="string"||g.trim().length===0){y(p,400,{error:"Invalid title"});return}f.title=g.trim()}if(O!==void 0){if(!Array.isArray(O)){y(p,400,{error:"Invalid assertions"});return}let q=O.filter(j=>typeof j=="string").map(j=>j.trim()).filter(Boolean);if(q.length===0){y(p,400,{error:"Invalid assertions"});return}f.assertions=q}if(!f.status&&!f.title&&!f.assertions){y(p,400,{error:"No eval changes provided"});return}let F=await w.updateCase(d,f);if(!F){y(p,404,{error:"Eval not found"});return}y(p,200,{eval:F})}async function Dn(r){let l=G.get(r);if(l)return l;let f=(await R.getThread(r))?.messages.find(u=>u.role==="human")?.feedbackSummary??"";if(f.startsWith("Synthesize evals"))return G.set(r,"synthesize_evals"),"synthesize_evals";if(f.startsWith("Synthesize rules"))return G.set(r,"synthesize"),"synthesize";if(f.startsWith("Run eval"))return G.set(r,"run_eval"),"run_eval"}async function Nn(r,l){let p=[];for await(let F of r)p.push(typeof F=="string"?Buffer.from(F):F);let d;if(p.length>0)try{d=JSON.parse(Buffer.concat(p).toString("utf-8")).serverUrl}catch{}let f=[];S.claude?.available&&S.claude.mcp&&!S.claude.mcp.found&&f.push(await rn(d)),S.codex?.available&&S.codex.mcp&&!S.codex.mcp.found&&f.push(await an(d)),S.copilot?.available&&S.copilot.mcp&&!S.copilot.mcp.found&&f.push(await cn(d,S.copilot.path??v));let[u,g,O]=await Promise.all([dt(n),ut(n),pt(n,S.copilot?.path??v)]);S.claude&&(S.claude.mcp=u),S.codex&&(S.codex.mcp=g),S.copilot&&(S.copilot.mcp=O),y(l,200,{results:f,capabilities:{providers:S}})}async function Jn(r,l){let p=[];for await(let u of r)p.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(l,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){y(l,400,{error:"Missing or invalid name"});return}let f=await C.addComponent(d.name);y(l,200,f)}async function Bn(r,l){let p=[];for await(let u of r)p.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(l,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){y(l,400,{error:"Missing or invalid name"});return}let f=await C.removeComponent(d.name);y(l,200,f)}async function Fn(r,l){let p=[];for await(let u of r)p.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(l,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"||typeof d.value!="string"){y(l,400,{error:"Missing or invalid path/value"});return}let f=await C.updateToken(d.path,d.value);y(l,200,f)}async function jn(r,l){let p=[];for await(let u of r)p.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(l,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"){y(l,400,{error:"Missing or invalid path"});return}let f=await C.removeToken(d.path);y(l,200,f)}function Un(r,l){let p=o??"http://localhost:3000";if(!o){let f=r.headers.referer||r.headers.origin;if(f)try{let u=new URL(typeof f=="string"?f:f[0]||"");(u.hostname==="localhost"||u.hostname==="127.0.0.1")&&(p=u.origin)}catch{}}let d=bt(W,p);l.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),l.end(d)}async function zn(r){let l=Date.now();if(E&&l<E.expires){y(r,200,E.data);return}try{let{scanForComponents:p}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:d}=await import("./render-generator-EANIDD2E.mjs"),f=await p(n);E={data:f,expires:l+5e3},d(f,n,ie).then(u=>{ie=u}).catch(u=>console.warn("[Bridge] Render generation failed:",u)),y(r,200,f)}catch(p){console.error("[Bridge] Scanner error:",p),y(r,500,{error:"Failed to scan components"})}}async function Ln(r){let l=[me(n,"node_modules","@popmelt.com","core","dist","canvas.mjs"),me(n,"packages","popmelt","dist","canvas.mjs")];try{let p=Ro(import.meta.url);l.unshift(me(Eo(p),"canvas.mjs"))}catch{}for(let p of l)try{let d=await bn(p,"utf-8");r.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),r.end(d);return}catch{}console.error("[Bridge] Canvas bundle not found in:",l),y(r,404,{error:"Canvas bundle not found"})}async function Wn(r,l){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){y(l,400,{error:"Invalid filename"});return}try{let p=await bn(me(i,r)),d=r.split(".").pop()?.toLowerCase(),f=d==="png"?"image/png":d==="webp"?"image/webp":d==="jpg"||d==="jpeg"?"image/jpeg":"application/octet-stream";l.writeHead(200,{"Content-Type":f,"Cache-Control":"public, max-age=3600"}),l.end(p)}catch{y(l,404,{error:"File not found"})}}function Je(r){return`/files/${gt(r)}`}async function Hn(r,l){let p=await R.getThread(r);if(!p){y(l,404,{error:"Thread not found"});return}let d=(await w.loadRuns()).runs.filter(g=>g.threadId===r).sort((g,O)=>O.completedAt-g.completedAt)[0],f=d?await w.findCase(d.evalId):null,u=p.messages.map(({screenshotPath:g,screenshotPaths:O,imagePaths:F,replyImagePaths:q,...j})=>({...j,...j.role==="assistant"&&d?{evalRun:{...d,title:f?.title}}:{},...g?{screenshotUrl:Je(g)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([h,L])=>[h,Je(L)]))}:{},...F?{imageUrls:Object.fromEntries(Object.entries(F).map(([h,L])=>[h,L.map(Je)]))}:{},...q?{replyImageUrls:q.map(Je)}:{}}));y(l,200,{id:p.id,createdAt:p.createdAt,messages:u})}let wt=9,St=!1;for(let r=t;r<t+wt;r++)try{await No(re,r),W=r,St=!0,console.log(`[\u22B9 is watching :${W}]`);break}catch(l){if(l.code==="EADDRINUSE"){let p=await Do(r);if(p&&p.projectId===e)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:e,close:async()=>{}};continue}throw l}if(!St)throw new Error(`[Bridge] All ports ${t}\u2013${t+wt-1} in use`);for(let[r,l]of Object.entries(S))!l.available||!l.path||H(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 d of _)vt(d,{type:"capabilities_changed",data:{}})}});let Gn=setInterval(()=>{kn(i).catch(()=>{})},Mo);return{port:W,projectId:e,close:async()=>{clearInterval(Gn),await N.destroyAsync();for(let r of _)try{r.res.end()}catch{}return _.clear(),new Promise(r=>{re.close(()=>r())})}}}async function kn(s){try{let t=await So(s),n=Date.now();for(let e of t){let o=me(s,e);try{let i=await bo(o);n-i.mtimeMs>Co&&await xo(o)}catch{}}}catch{}}var fe="\x1B[35m[popmelt]\x1B[0m";async function Uo(){let s=process.argv.slice(2);if(s[0]==="wrap"){let t=s.indexOf("--");(t===-1||t===s.length-1)&&(console.error(`${fe} Usage: popmelt wrap -- <dev command>`),console.error(`${fe} Example: popmelt wrap -- next dev`),console.error(`${fe} Example: popmelt wrap -- astro dev`),process.exit(1));let n=s.slice(t+1);await Wo(n);return}if(s[0]==="bridge"){await zo();return}if(s[0]==="stop"){await Lo();return}console.log(`${fe} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}async function zo(){let s=await yt({projectRoot:process.cwd()});console.log(`${fe} Bridge running on http://localhost:${s.port}`),await new Promise(t=>{let n=async()=>{console.log(`
359
- ${fe} Shutting down bridge...`),await s.close(),t()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function Lo(){let s=jo(process.cwd(),".popmelt","bridge.lock"),t;try{t=JSON.parse(await Bo(s,"utf8"))}catch{console.log(`${fe} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(t.pid,"SIGTERM"),console.log(`${fe} Sent SIGTERM to bridge (pid ${t.pid}, port ${t.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${fe} Bridge process ${t.pid} already dead`);else throw n}try{await Fo(s)}catch{}}async function Wo(s){let t=await yt({projectRoot:process.cwd()});console.log(`${fe} Bridge running on http://localhost:${t.port}`);let[n,...e]=s;console.log(`${fe} Starting: ${s.join(" ")}`);let o=Jo(n,e,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${t.port}`,POPMELT_PROJECT_ID:t.projectId}}),i=a=>{o.kill(a)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),o.on("exit",async(a,c)=>{await t.close(),c?process.kill(process.pid,c):process.exit(a??0)})}Uo().catch(s=>{console.error(`${fe} Fatal:`,s),process.exit(1)});
410
+ `);let u=new URL(r.url||"/",`http://127.0.0.1:${z}`).searchParams.get("sourceId")||void 0,h={id:we().slice(0,8),res:c,sourceId:u};P.add(h),r.on("close",()=>{P.delete(h)})}async function zn(r,c){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:Tn,restartMode:G,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: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 jn(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 Bn(r,c){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(c,200,{cancelled:I})}async function It(r){let c=we().slice(0,8),p=r.threadId,u=!p;p||(p=(await m.createThread(c,[])).id,V.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=J.enqueue(h);return{jobId:c,position:d,threadId:p}}async function Fn(r,c){if(J.isRunning){y(c,200,{skipped:!0,reason:"Already running"});return}let{provider:p,model:u}=await je(r);if(p==="copilot"){y(c,400,{error:"Materialization is not available for Copilot yet."});return}let h=await g.getUnmaterializedPatternDecisions();if(h.length===0){y(c,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}let d=await It({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(I=>I.id),...d})}async function Un(r,c){let p=decodeURIComponent(r),u=await g.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.
411
+
412
+ ${u.title}
413
+ ${u.summary}`}),y(c,200,{proposal:u})}async function Ln(r,c){let p=decodeURIComponent(r),u=await g.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 Wn(r,c,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 je(c),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 $.loadSuite(),U=Vt({proposal:h,currentModel:j,existingSuite:Q}),v=we().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(`
416
+ `)});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 je(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:ze(typeof p.provider=="string"?p.provider:void 0),model:typeof p.model=="string"&&p.model?p.model:void 0}}catch{return{}}}async function Hn(r,c){let p=await g.loadModel();if(!p){y(c,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(c,400,{error:"Rule synthesis is not available for Copilot yet."});return}let d=sn(p),I=we().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:ze(u),model:h||void 0};Q._replyPrompt=d;let U=k.enqueue(Q);y(c,200,{jobId:I,position:U,threadId:j})}async function Gn(r,c){let{provider:p,model:u}=await je(r);if(p==="copilot"){y(c,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 $.loadSuite(),Q=Yt({decisions:d,threads:I,model:S,existingSuite:j}),U=we().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(c,200,{jobId:U,position:X,threadId:E})}async function qn(r,c,p){let u=decodeURIComponent(r),h=await $.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 Ze(c),U=ze(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=we().slice(0,8),C=we().slice(0,8),X=me(a,`eval-run-${E}.webp`);await Je(X,d);let ce=await $.writeRunScreenshot(E,d),se=v.viewport,ae=se&&typeof se=="object"?se:{},le={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,B=U==="codex"?K.length>0:typeof Z=="string"&&/chrome|devtools/i.test(Z),H=Kt({evalCase:h,scope:le,model:N,screenshotPath:X,chromeDevtoolsAvailable:B}),_=(await m.createThread(C,[])).id;V.set(_,"run_eval");let re={timestamp:new Date().toISOString(),url:le.url,viewport:le.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: ${le.url||"unknown"}`,"Assertions:",...h.assertions.map(as=>`- ${as}`)].join(`
417
+ `)});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=le,de._evalScreenshotPath=ce;let ct=k.enqueue(de);y(p,200,{jobId:C,runId:E,position:ct,threadId:_,screenshotPath:ce})}async function Qn(r,c,p){let u=decodeURIComponent(r),h={},d,I,S;try{let Q=[];for await(let v of c)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 $.updateCase(u,h);if(!j){y(p,404,{error:"Eval not found"});return}y(p,200,{eval:j})}async function Xn(r){let c=V.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 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 Yn(r,c){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 mn(u)),w.codex?.available&&w.codex.mcp&&!w.codex.mcp.found&&h.push(await gn(u)),w.copilot?.available&&w.copilot.mcp&&!w.copilot.mcp.found&&h.push(await vn(u,w.copilot.path??M));let[d,I,S]=await Promise.all([yt(t),wt(t),St(t,w.copilot?.path??M)]);w.claude&&(w.claude.mcp=d),w.codex&&(w.codex.mcp=I),w.copilot&&(w.copilot.mcp=S),y(c,200,{results:h,capabilities:{providers:w}})}async function Kn(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 g.addComponent(u.name);y(c,200,h)}async function Vn(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 g.removeComponent(u.name);y(c,200,h)}async function Zn(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 g.updateToken(u.path,u.value);y(c,200,h)}async function es(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 g.removeToken(u.path);y(c,200,h)}function ts(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(z,p);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(u)}async function ns(r){let c=Date.now();if(ne&&c<ne.expires){y(r,200,ne.data);return}try{let{scanForComponents:p}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:u}=await import("./render-generator-EANIDD2E.mjs"),h=await p(t);ne={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 ss(r){let c=[me(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),me(t,"packages","popmelt","dist","canvas.mjs")];try{let p=Ko(import.meta.url);c.unshift(me(Yo(p),"canvas.mjs"))}catch{}for(let p of c)try{let u=await $n(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 os(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){y(c,400,{error:"Invalid filename"});return}try{let p=await $n(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 rs(r,c){let p=await m.getThread(r);if(!p){y(c,404,{error:"Thread not found"});return}let u=(await $.loadRuns()).runs.filter(S=>S.threadId===r).sort((S,j)=>j.completedAt-S.completedAt)[0],h=u?await $.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:Be(S)}:{},...j?{screenshotUrls:Object.fromEntries(Object.entries(j).map(([E,C])=>[E,Be(C)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([E,C])=>[E,C.map(Be)]))}:{},...U?{replyImageUrls:U.map(Be)}:{}}));y(c,200,{id:p.id,createdAt:p.createdAt,messages:I,modelProposal:d})}let Mt=9,Et=!1;for(let r=e;r<e+Mt;r++)try{await lr(lt,r),z=r,Et=!0,console.log(`[\u22B9 is watching :${z}]`);break}catch(c){if(c.code==="EADDRINUSE"){let p=await ar(r);if(p&&p.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!Et)throw new Error(`[Bridge] All ports ${e}\u2013${e+Mt-1} in use`);for(let[r,c]of Object.entries(w))!c.available||!c.path||Y(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 P)it(u,{type:"capabilities_changed",data:{}})}});let is=setInterval(()=>{_n(a).catch(()=>{})},er);return{port:z,projectId:o,close:async()=>{clearInterval(is),await k.destroyAsync();for(let r of P)try{r.res.end()}catch{}return P.clear(),new Promise(r=>{lt.close(()=>r())})}}}async function _n(s){try{let e=await Wo(s),n=Date.now();for(let t of e){let o=me(s,t);try{let i=await Go(o);n-i.mtimeMs>tr&&await qo(o)}catch{}}}catch{}}var he="\x1B[35m[popmelt]\x1B[0m";async function hr(){let s=process.argv.slice(2);if(s[0]==="wrap"){let e=s.indexOf("--");(e===-1||e===s.length-1)&&(console.error(`${he} Usage: popmelt wrap -- <dev command>`),console.error(`${he} Example: popmelt wrap -- next dev`),console.error(`${he} Example: popmelt wrap -- astro dev`),process.exit(1));let n=s.slice(e+1);await gr(n);return}if(s[0]==="bridge"){await fr();return}if(s[0]==="stop"){await mr();return}console.log(`${he} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}async function fr(){let s=await kt({projectRoot:process.cwd()});console.log(`${he} Bridge running on http://localhost:${s.port}`),await new Promise(e=>{let n=async()=>{console.log(`
418
+ ${he} Shutting down bridge...`),await s.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function mr(){let s=pr(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await dr(s,"utf8"))}catch{console.log(`${he} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${he} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${he} Bridge process ${e.pid} already dead`);else throw n}try{await ur(s)}catch{}}async function gr(s){let e=await kt({projectRoot:process.cwd()});console.log(`${he} Bridge running on http://localhost:${e.port}`);let[n,...t]=s;console.log(`${he} Starting: ${s.join(" ")}`);let o=cr(n,t,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_PROJECT_ID:e.projectId}}),i=a=>{o.kill(a)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),o.on("exit",async(a,l)=>{await e.close(),l?process.kill(process.pid,l):process.exit(a??0)})}hr().catch(s=>{console.error(`${he} Fatal:`,s),process.exit(1)});