@popmelt.com/core 0.8.1 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge-entry.mjs +49 -49
- package/dist/cli.mjs +42 -42
- package/dist/index.mjs +52 -24
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/{server-AGXQFGSU.mjs → server-HJ37BEU5.mjs} +34 -34
- package/dist/server.mjs +34 -34
- package/package.json +3 -3
package/dist/bridge-entry.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdir as Ir,unlink as kr,writeFile as Mr}from"fs/promises";import{join as Jn}from"path";import{execFileSync as at,spawn as Tn}from"child_process";import{createHash as nr,randomUUID as we}from"crypto";import{mkdir as sr,readFile as
|
|
1
|
+
import{mkdir as Ir,unlink as kr,writeFile as Mr}from"fs/promises";import{join as Jn}from"path";import{execFileSync as at,spawn as Tn}from"child_process";import{createHash as nr,randomUUID as we}from"crypto";import{mkdir as sr,readFile as An,readdir as or,realpath as rr,stat as ir,unlink as ar,writeFile as Be}from"fs/promises";import{createServer as lr}from"http";import{tmpdir as cr}from"os";import{basename as rt,dirname as dr,join as me}from"path";import{fileURLToPath as ur}from"url";function Rt(s,e){return`<!DOCTYPE html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -26,11 +26,11 @@ import{mkdir as Ir,unlink as kr,writeFile as Mr}from"fs/promises";import{join as
|
|
|
26
26
|
</script>
|
|
27
27
|
</body>
|
|
28
28
|
</html>`}import{spawn as ys}from"child_process";import{createInterface as vs}from"readline";var ws=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),Et=1e5;function Ss(s){let e=s.input?.file_path||s.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!ws.has(n))return;let t;if(s.name==="Write"&&typeof s.input?.content=="string"?t=s.input.content:s.name==="Edit"&&typeof s.input?.new_string=="string"&&(t=s.input.new_string),!!t)return t.length>Et?t.slice(0,Et)+`
|
|
29
|
-
\u2026[truncated]`:t}function je(s,e){let{prompt:n,projectRoot:t,maxTurns:o=40,maxBudgetUsd:i=1,allowedTools:
|
|
30
|
-
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let o=t.split(" -> ");for(let i of o)i&&e.add(i)}return[...e]}function _t(s){let e=$t(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=$t(s,["diff","--no-ext-diff","HEAD","--"])??"",t=dt(n,Nt);return{status:e,changedFiles:_s(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Os(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function Ds(s,e){if(!Jt(e))return;let n=zt(s,e);if(!n)return;let t=Dt(s,n);if(t===""||t.startsWith(".."))return;let o=Ot("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:ct+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",
|
|
31
|
-
`)[0].slice(0,80)}`:"Bash";
|
|
32
|
-
`)}`)),
|
|
33
|
-
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let i=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function Ls(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"&&Ee(s).toLowerCase().includes("error"))return s.message}function Re(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(
|
|
29
|
+
\u2026[truncated]`:t}function je(s,e){let{prompt:n,projectRoot:t,maxTurns:o=40,maxBudgetUsd:i=1,allowedTools:l=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:a="claude",resumeSessionId:m,model:M,timeoutMs:x=3e5,onEvent:T}=e,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)),M&&z.push("--model",M);for(let j of l)z.push("--allowedTools",j);let J=ys(a,z,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),q=new Promise(j=>{let w,U=[],V=[],W=[],Q=!1,B="",Z,I,D=!1,R=setTimeout(()=>{D=!0,J.kill("SIGTERM"),setTimeout(()=>{try{J.kill("SIGKILL")}catch{}},5e3)},x),f=vs({input:J.stdout}),G=new Set;f.on("line",y=>{if(y.trim())try{let $=JSON.parse(y);$.session_id&&!w&&(w=$.session_id);let ne=$.type??($.event?.type?`event.${$.event.type}`:"unknown");if(G.add(ne),$.type==="result"&&$.result&&U.length===0){let C=typeof $.result=="string"?$.result:"";C&&(U.push(C),T?.({type:"delta",jobId:s,text:C},s))}if($.type==="assistant"&&Array.isArray($.message?.content)){typeof $.error=="string"&&(Z=$.error);for(let C of $.message.content){if(C.type==="text"&&C.text&&(U.push(C.text),T?.({type:"delta",jobId:s,text:C.text},s)),C.type==="tool_use"&&C.name){let ie=C.input?.file_path||C.input?.path||void 0,ee=Ss(C);if(T?.({type:"tool_use",jobId:s,tool:C.name,...ie?{file:ie}:{},...ee?{content:ee}:{}},s),C.name==="Edit"&&C.input?.file_path){let oe={tool:"Edit",file_path:C.input.file_path,old_string:C.input.old_string,new_string:C.input.new_string,replace_all:C.input.replace_all};V.push(oe),W.push({sequence:W.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:oe.file_path,oldString:typeof oe.old_string=="string"?oe.old_string:void 0,newString:typeof oe.new_string=="string"?oe.new_string:void 0,replaceAll:typeof oe.replace_all=="boolean"?oe.replace_all:void 0})}else C.name==="Write"&&C.input?.file_path&&(V.push({tool:"Write",file_path:C.input.file_path,content:C.input.content}),W.push({sequence:W.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:C.input.file_path,content:typeof C.input.content=="string"?C.input.content:void 0}))}C.type==="thinking"&&C.thinking&&T?.({type:"thinking",jobId:s,text:C.thinking},s)}}$.type==="result"&&$.is_error===!0&&(Q=!0,typeof $.error=="string"&&(Z=$.error),typeof $.result=="string"&&(I=$.result)),$.type==="user"&&$.tool_use_result?.file?.filePath&&T?.({type:"tool_use",jobId:s,tool:"Read",file:$.tool_use_result.file.filePath},s)}catch{}});let O=[];J.stderr?.on("data",y=>{O.push(y.toString())}),J.on("close",y=>{if(clearTimeout(R),f.close(),U.length===0&&G.size>0&&console.warn(`[Claude:${s}] No text captured. Event types seen: ${[...G].join(", ")}`),D)Q=!0,B=`Timed out after ${Math.round(x/6e4)} minutes`;else if(y!==0&&y!==null){Q=!0;let ne=O.join("").trim(),C=U.join("").trim(),ie=U.length===0&&G.size>0?` (no text captured, event types: ${[...G].join(", ")})`:"";B=ne||I||C||`Claude process exited with code ${y}${ie}`}Q&&!B&&I&&(B=I);let $=bs(B,Z);j({sessionId:w,text:U.join(""),success:!Q,error:Q?$.message:void 0,errorCode:Q?$.code:void 0,recoverableError:Q?$.recoverable:void 0,fileEdits:V.length>0?V:void 0,editEvents:W.length>0?W:void 0})}),J.on("error",y=>{clearTimeout(R),Q=!0,B=y.message,j({sessionId:w,text:U.join(""),success:!1,error:B,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:V.length>0?V:void 0,editEvents:W.length>0?W:void 0})})});return{process:J,result:q}}function bs(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 xs,spawnSync as Ot}from"child_process";import{readFileSync as Ps,statSync as Is}from"fs";import{basename as ks,extname as Ms,isAbsolute as Rs,relative as Dt,resolve as Es}from"path";import{createInterface as Ts}from"readline";function Tt(s){let e=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var At=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),ct=2e5,As=1e5,Nt=2e5;function Jt(s){let e=ks(s).toLowerCase(),n=Ms(s).toLowerCase();return At.has(n)||At.has(e)}function zt(s,e){let n=Rs(e)?e:Es(s,e),t=Dt(s,n);return t===""||t.startsWith("..")?null:n}function Ue(s,e){if(!Jt(e))return;let n=zt(s,e);if(n)try{let t=Is(n);return t.isFile()?t.size>ct?{exists:!0,truncated:!0}:{exists:!0,content:Ps(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Cs(s,e){for(let n of e){let t=s[n];if(typeof t=="string")return t}}function $s(s){let e=s?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function Ct(s){return Cs(s,["patch","diff","unifiedDiff","unified_diff"])}function dt(s,e){return s.length<=e?{text:s}:{text:s.slice(0,e),truncated:!0}}function $t(s,e){let n=Ot("git",e,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:Nt+65536});return n.status!==0?null:n.stdout??""}function _s(s){let e=new Set;for(let n of s.split(`
|
|
30
|
+
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let o=t.split(" -> ");for(let i of o)i&&e.add(i)}return[...e]}function _t(s){let e=$t(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=$t(s,["diff","--no-ext-diff","HEAD","--"])??"",t=dt(n,Nt);return{status:e,changedFiles:_s(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Os(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function Ds(s,e){if(!Jt(e))return;let n=zt(s,e);if(!n)return;let t=Dt(s,n);if(t===""||t.startsWith(".."))return;let o=Ot("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:ct+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",l=dt(i,ct);return{exists:!0,content:l.text,...l.truncated?{truncated:!0}:{}}}function Ns(s,e,n){return e.map(t=>{let o=n.has(t)?n.get(t):Ds(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:l,onEvent:a,sandboxMode:m="workspace-write",configOverrides:M=[]}=e,x=[];if(i){x.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${m}"`);for(let J of M)x.push("-c",J);l&&x.push("-m",l),x.push(i),x.push(n),o&&x.push("--image",o)}else{x.push("exec","--skip-git-repo-check","--json","--sandbox",m);for(let J of M)x.push("-c",J);l&&x.push("-m",l),x.push(n),o&&x.push("--image",o)}let T=xs("codex",x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),z=new Promise(J=>{let q,j=[],w=[],U=[],V=new Map,W=new Map,Q=!1,B="",Z=Ts({input:T.stdout}),I=new Set;Z.on("line",R=>{if(R.trim())try{let f=JSON.parse(R),G=f.type??"unknown";if(I.add(G),G==="thread.started"&&f.thread_id&&!q&&(q=f.thread_id),(G==="item.agentMessage.delta"||G==="item/agentMessage/delta")&&f.delta?.text&&(j.push(f.delta.text),a?.({type:"delta",jobId:s,text:f.delta.text},s)),(G==="item.reasoning.delta"||G==="item/reasoning/delta")&&f.delta?.text&&a?.({type:"thinking",jobId:s,text:f.delta.text},s),(G==="item.started"||G==="item/started")&&f.item){let O=f.item.type;if(O==="command_execution"){let y=f.item.command,$=y?Tt(y):void 0,ne=_t(t),C=new Map;for(let ee of ne?.changedFiles??[])C.set(ee,Ue(t,ee));typeof f.item.id=="string"&&W.set(f.item.id,{...y?{rawCommand:y}:{},...$?{command:$}:{},...ne?{beforeWorktree:ne}:{},beforeSnapshots:C});let ie=$?`Bash: ${$.split(`
|
|
31
|
+
`)[0].slice(0,80)}`:"Bash";w.push(ie),a?.({type:"tool_use",jobId:s,tool:"Bash",...$?{content:$}:{}},s)}else if(O==="file_change"){let y=f.item.filename||f.item.path;y&&!V.has(y)&&V.set(y,Ue(t,y)),w.push(y?`Edit ${y.split("/").pop()}`:"Edit"),a?.({type:"tool_use",jobId:s,tool:"Edit",...y?{file:y}:{}},s)}else if(O==="file_read"){let y=f.item.filename||f.item.path;w.push(y?`Read ${y.split("/").pop()}`:"Read"),a?.({type:"tool_use",jobId:s,tool:"Read",...y?{file:y}:{}},s)}else if(O==="web_search")w.push("WebSearch"),a?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if(O==="mcp_tool_call"){let y=f.item.tool_name||f.item.name||"MCP";w.push(y),a?.({type:"tool_use",jobId:s,tool:y},s)}}if((G==="item.completed"||G==="item/completed")&&f.item){if(f.item.type==="agent_message"){let O=f.item.text;typeof O=="string"&&O&&(j.push(O),a?.({type:"delta",jobId:s,text:O},s))}else if(f.item.type==="reasoning"){let O=f.item.text;typeof O=="string"&&O&&a?.({type:"thinking",jobId:s,text:O},s)}else if(f.item.type==="file_change"&&Array.isArray(f.item.changes))for(let O of f.item.changes){let y=O.path||O.filename,$=O.kind==="add"?"Write":"Edit";if(y){w.push(`${$} ${y.split("/").pop()}`),a?.({type:"tool_use",jobId:s,tool:$,file:y},s);let ne=O,C=typeof ne.kind=="string"?ne.kind:void 0,ie=$s(C),ee=V.get(y),oe=Ue(t,y);U.push({sequence:U.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:ie,filePath:y,...ee?{before:ee}:{},...oe?{after:oe}:{},...Ct(ne)?{patch:Ct(ne)}:{},...C?{rawKind:C}:{}}),V.set(y,oe)}}else if(f.item.type==="command_execution"){let O=typeof f.item.id=="string"?f.item.id:void 0,y=O?W.get(O):void 0,$=typeof f.item.command=="string"?f.item.command:y?.rawCommand,ne=$?Tt($):y?.command,C=_t(t);if(Os(y?.beforeWorktree,C)){let ie=[...new Set([...y?.beforeWorktree?.changedFiles??[],...C?.changedFiles??[]])],ee=typeof f.item.aggregated_output=="string"?dt(f.item.aggregated_output,As):void 0,oe=typeof f.item.exit_code=="number"?f.item.exit_code:f.item.exit_code===null?null:void 0,ke=typeof f.item.status=="string"?f.item.status:void 0;U.push({sequence:U.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...$?{rawCommand:$}:{},...ne?{command:ne}:{},...oe!==void 0?{exitCode:oe}:{},...ke?{status:ke}:{},...ee?{output:ee.text}:{},...ee?.truncated?{outputTruncated:!0}:{},...y?.beforeWorktree?{beforeWorktree:y.beforeWorktree}:{},...C?{afterWorktree:C}:{},...ie.length>0?{touchedFiles:Ns(t,ie,y?.beforeSnapshots??new Map)}:{}})}O&&W.delete(O)}}G==="turn.failed"&&(Q=!0,B=f.error?.message||f.message||"Turn failed")}catch{}});let D=[];T.stderr?.on("data",R=>{D.push(R.toString())}),T.on("close",R=>{Z.close(),j.length===0&&I.size>0&&console.warn(`[Codex:${s}] No text captured. Event types seen: ${[...I].join(", ")}`),R!==0&&R!==null&&(Q=!0,B=D.join("")||`Codex process exited with code ${R}`),J({sessionId:q,text:j.join(""),success:!Q,error:Q?B:void 0,editEvents:U.length>0?U:void 0,toolsUsed:w.length>0?w:void 0})}),T.on("error",R=>{Q=!0,B=R.message,J({sessionId:q,text:j.join(""),success:!1,error:B,editEvents:U.length>0?U:void 0,toolsUsed:w.length>0?w:void 0})})});return{process:T,result:z}}import{spawn as Js}from"child_process";import{createInterface as zs}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:l=3e5,onEvent:a,copilotPath:m="copilot"}=e,M=["--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&&M.push(`--resume=${o}`),i&&M.push("--model",i),M.push("-p",n);let x=Js(m,M,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),T=new Promise(z=>{let J,q=[],j=[],w=!1,U="",V=!1,W=setTimeout(()=>{V=!0,x.kill("SIGTERM"),setTimeout(()=>{try{x.kill("SIGKILL")}catch{}},5e3)},l),Q=zs({input:x.stdout}),B=new Set,Z=[];Q.on("line",D=>{if(D.trim())try{let R=JSON.parse(D),f=Ee(R);B.add(f),Z.length<5&&Fs(f)&&Z.push(D.slice(0,800));let G=Re(R,["sessionId","session_id","id"],["session","conversation","thread"]);G&&!J&&(J=G);let O=Bs(R,q.length===0);O&&(q.push(O),a?.({type:"delta",jobId:s,text:O},s));let y=js(R);y&&a?.({type:"thinking",jobId:s,text:y},s);let $=Us(R);$&&(j.push($.label),a?.({type:"tool_use",jobId:s,tool:$.tool,...$.file?{file:$.file}:{},...$.content?{content:$.content}:{}},s));let ne=Ls(R);ne&&(w=!0,U=ne)}catch{}});let I=[];x.stderr?.on("data",D=>{I.push(D.toString())}),x.on("close",D=>{clearTimeout(W),Q.close(),q.length===0&&B.size>0&&(console.warn(`[Copilot:${s}] No text captured. Event types seen: ${[...B].join(", ")}`),Z.length>0&&console.warn(`[Copilot:${s}] Sample text-bearing candidates: ${Z.join(`
|
|
32
|
+
`)}`)),V?(w=!0,U=`Timed out after ${Math.round(l/6e4)} minutes`):D!==0&&D!==null&&(w=!0,U=I.join("").trim()||U||`Copilot process exited with code ${D}`);let R=w?Bt(U,i):null;z({sessionId:J,text:q.join(""),success:!w,error:R?.message,errorCode:R?.code,recoverableError:R?.recoverable,provider:"copilot",toolsUsed:j.length>0?j:void 0})}),x.on("error",D=>{clearTimeout(W);let R=Bt(D.message,i);z({sessionId:J,text:q.join(""),success:!1,error:R.message,errorCode:R.code,recoverableError:R.recoverable,provider:"copilot",toolsUsed:j.length>0?j:void 0})})});return{process:x,result:T}}function Ee(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 Bs(s,e=!1){let n=Ee(s).toLowerCase(),t=s.update,o=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&o?.type==="text"&&typeof o.text=="string")return o.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return he(s.delta)??he(s.content)??he(s.message);if(n==="assistant.message"&&e)return he(s.message)??he(s.content)??he(s);if(n==="result"&&e)return he(s.result)??he(s.output)??he(s.message)??he(s);let i=s.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof s.text=="string"&&ut(s))return s.text;if(typeof s.message=="string"&&ut(s))return s.message;if(typeof s.delta=="string"&&ut(s))return s.delta}function he(s){if(typeof s=="string")return s;if(!s)return;if(Array.isArray(s)){let n=s.map(he).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof s!="object")return;let e=s;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=he(e[n]);if(t)return t}}function Fs(s){let e=s.toLowerCase();return e.includes("assistant.message")||e==="result"}function js(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 Us(s){let e=Re(s,["tool","toolName","tool_name","name"]),n=Re(s,["command","cmd"]),t=Re(s,["file","path","filename","filePath"]),o=Ee(s);if(n||o.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
|
|
33
|
+
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let i=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function Ls(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"&&Ee(s).toLowerCase().includes("error"))return s.message}function Re(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(l=>t.toLowerCase().includes(l)))continue;let i=Re(o,e);if(i)return i}}function ut(s){let e=Ee(s).toLowerCase();return(typeof s.role=="string"?s.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{execFile as Ws}from"child_process";import{copyFile as jt,mkdir as Ut,readdir as Hs,readFile as Gs,writeFile as qs}from"fs/promises";import{join as Se}from"path";var We=class{constructor(e){this.projectRoot=e;let n=Se(e,".popmelt");this.decisionsDir=Se(n,"decisions"),this.screenshotsDir=Se(n,"screenshots")}async persist(e,n,t){try{await Ut(this.decisionsDir,{recursive:!0}),await Ut(this.screenshotsDir,{recursive:!0});try{await jt(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 jt(t[o],Se(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await qs(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 Hs(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 Gs(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=>{Ws("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(t,o)=>{if(t){n(null);return}n(o||null)})})}};import{mkdir as Te,readFile as Lt,writeFile as Ae}from"fs/promises";import{join as Ce}from"path";var Qs=80,Xs=24,Wt=1e3,He=class{constructor(e){this.evalsDir=Ce(e,".popmelt","evals"),this.suitePath=Ce(this.evalsDir,"evals.json"),this.runsPath=Ce(this.evalsDir,"runs.json"),this.screenshotsDir=Ce(this.evalsDir,"screenshots")}async loadSuite(){try{let e=await Lt(this.suitePath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.cases))return n}catch{}return{version:1,updatedAt:0,cases:[]}}async loadRuns(){try{let e=await Lt(this.runsPath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.runs))return n}catch{}return{version:1,updatedAt:0,runs:[]}}async loadSuiteWithRuns(){let[e,n]=await Promise.all([this.loadSuite(),this.loadRuns()]);return{...e,runs:n.runs}}async loadSuiteWithCurrentRuns(e){let n=await this.loadSuiteWithRuns();return e?{...n,runs:n.runs.filter(t=>t.codeFingerprint===e)}:n}async writeSynthesized(e){let n=await this.loadSuite(),t=new Map(n.cases.map(l=>[l.id,l])),o=new Set;for(let l of e){let a=t.get(l.id);a&&(a.title!==l.title||a.prompt!==l.prompt||JSON.stringify(a.assertions)!==JSON.stringify(l.assertions))&&o.add(l.id),t.set(l.id,l)}let i={version:1,updatedAt:Date.now(),cases:[...t.values()]};return await Te(this.evalsDir,{recursive:!0}),await Ae(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(a=>a.id===e?{...a,...n.status?{status:n.status}:{},...n.title?{title:n.title}:{},...n.assertions?{assertions:n.assertions}:{}}:a),l=i.find(a=>a.id===e)??null;return l?(await Te(this.evalsDir,{recursive:!0}),await Ae(this.suitePath,JSON.stringify({version:1,updatedAt:Date.now(),cases:i},null,2)),o&&await this.invalidateRunsForEvals(new Set([e])),l):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 Te(this.evalsDir,{recursive:!0}),await Ae(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 Te(this.evalsDir,{recursive:!0}),await Ae(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(e,n){return await Te(this.screenshotsDir,{recursive:!0}),await Ae(Ce(this.screenshotsDir,`eval-${e}.webp`),n),`evals/screenshots/eval-${e}.webp`}async findCase(e){return(await this.loadSuite()).cases.find(t=>t.id===e)??null}};function Ht(s){let e=s.match(/<evals>\s*([\s\S]*?)\s*<\/evals>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return t?Qt(t):null}catch{return null}}function Gt(s){let e=s.match(/<eval_proposals>\s*([\s\S]*?)\s*<\/eval_proposals>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return t?Qt(t,"pending"):null}catch{return null}}function qt(s,e){let n=s.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let t=JSON.parse(n[1]),o=to(t.assertionResults,e),i=no(o);return{status:i,summary:fe(t.summary)||Kt(i),assertionResults:o,tooling:so(t.tooling)}}catch{}return{status:"needs_review",summary:Ge(s.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:e.map(t=>({assertion:t,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function Qt(s,e="approved"){let n=[];return s.forEach((t,o)=>{if(!t||typeof t!="object")return;let i=t,l=fe(i.title),a=fe(i.prompt),m=fe(i.rationale),M=xe(i.assertions);if(!l||!a||M.length===0)return;let x=Ks(i.category),T=oo(fe(i.id))||`eval-${Zt(l).slice(0,32)||o+1}`,z=Zs(i.status)??e;n.push({id:T,title:l,status:z,category:x,prompt:a,assertions:M,rationale:m||"Inferred from Popmelt design history.",sourceDecisionIds:xe(i.sourceDecisionIds),sourceThreadIds:xe(i.sourceThreadIds)})}),n}function Xt(s){let e=[...s.decisions].sort((t,o)=>o.createdAt-t.createdAt).slice(0,Qs),n=Object.values(s.threads.threads).sort((t,o)=>o.updatedAt-t.updatedAt).slice(0,Xs);return`You are helping a designer turn organic Popmelt annotation history into a project eval suite.
|
|
34
34
|
|
|
35
35
|
The designer does NOT work eval-first. They use annotations and conversation threads to zhuzh the UI over time. Your job is to infer useful eval proposals from that trail. The developer will reject, refine, or approve proposals in this thread. Do not write files or run commands.
|
|
36
36
|
|
|
@@ -50,7 +50,7 @@ ${e.map(Ys).join(`
|
|
|
50
50
|
`)||"No decisions found."}
|
|
51
51
|
|
|
52
52
|
## Recent Threads
|
|
53
|
-
${n.map(
|
|
53
|
+
${n.map(Vs).join(`
|
|
54
54
|
|
|
55
55
|
`)||"No threads found."}
|
|
56
56
|
|
|
@@ -141,7 +141,7 @@ The block must be valid JSON with this shape:
|
|
|
141
141
|
\`\`\`
|
|
142
142
|
|
|
143
143
|
Allowed statuses: pass, fail, needs_review.
|
|
144
|
-
Allowed chromeDevtools values: available, unavailable, unknown.`}function
|
|
144
|
+
Allowed chromeDevtools values: available, unavailable, unknown.`}function Vt(s){return`You are turning an approved Popmelt taste-model update into draft evals.
|
|
145
145
|
|
|
146
146
|
The model is the source of truth. Evals are executable projections of model properties and values. Your job is to translate the approved model proposal into concrete, falsifiable eval proposals that a designer can review in the Eval panel.
|
|
147
147
|
|
|
@@ -190,9 +190,9 @@ Allowed categories: component, layout, copy, interaction, visual, workflow.
|
|
|
190
190
|
|
|
191
191
|
<eval_proposals>
|
|
192
192
|
[]
|
|
193
|
-
</eval_proposals>`}function Ys(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(
|
|
194
|
-
`),i=n.map(
|
|
195
|
-
`),
|
|
193
|
+
</eval_proposals>`}function Ys(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(a=>a.instruction).filter(Boolean).join(`
|
|
194
|
+
`),i=n.map(a=>{let m=a.finalScope??a.inferredScope??a.declaredScope;return`- ${a.status}: ${a.summary}${m?` [${m.breadth}/${m.target}]`:""}`}).join(`
|
|
195
|
+
`),l=[...new Set([...n.flatMap(a=>a.filesModified??[]),...t.map(a=>a.filePath).filter(a=>!!a)])].slice(0,12);return`### Decision ${s.id}
|
|
196
196
|
Thread: ${s.threadId??"none"}
|
|
197
197
|
Created: ${new Date(s.createdAt).toISOString()}
|
|
198
198
|
URL: ${s.url||"unknown"}
|
|
@@ -200,20 +200,20 @@ Instructions:
|
|
|
200
200
|
${Ge(o||"(none)",Wt)}
|
|
201
201
|
Resolutions:
|
|
202
202
|
${Ge(i||"(none)",Wt)}
|
|
203
|
-
Files: ${
|
|
203
|
+
Files: ${l.length>0?l.join(", "):"none"}`}function Vs(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(l=>`${l.status}: ${l.summary}`).join("; ")??"";return`- ${t.role}: ${Ge(o||i||"(no text)",500)}`}).join(`
|
|
204
204
|
`);return`### Thread ${s.id}
|
|
205
205
|
Messages: ${s.messages.length}
|
|
206
206
|
Updated: ${new Date(s.updatedAt).toISOString()}
|
|
207
|
-
${n}`}function fe(s){return typeof s=="string"?s.trim():""}function be(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Vs(s){let e=fe(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function Zs(s){let e=fe(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function eo(s){let e=fe(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function to(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:eo(i.status)??"needs_review",summary:fe(i.summary)||Vt("needs_review"),evidence:be(i.evidence)}:null}).filter(o=>o!==null);return t.length>0?t:e.map(o=>({assertion:o,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function no(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function so(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:be(e.evidenceTypes).length>0?be(e.evidenceTypes):["screenshot"]}}function Vt(s){return s==="pass"?"The current page appears to satisfy this eval.":s==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function oo(s){return Zt(s).slice(0,48)}function Zt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ge(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as en}from"crypto";import{mkdir as pt,readFile as qe,writeFile as ve}from"fs/promises";import{dirname as ht,join as $e}from"path";var se="[Materializer]",tn={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},ro={version:1,runs:[]},io={version:1,updatedAt:0,proposals:[]},ao=12;function lo(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(`${se} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${se} Rule count ${e.length} exceeds cap of 30`),e}function co(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function uo(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 m=l.sources;if(Array.isArray(m))for(let k of m)typeof k=="string"&&n.has(k)&&t.add(k)}let i=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?s.tokens:{},a=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?s.components:{};return{ruleCount:o.length,tokenSectionCount:Object.keys(i).length,componentCount:Object.keys(a).length,coveredDecisionIds:[...t],uncoveredDecisionIds:e.filter(l=>!t.has(l))}}function po(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function ho(s,e,n){let t=s[e];if(t&&typeof t=="object")return t;let o=typeof n=="number"?[]:{};return s[String(e)]=o,o}function fo(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=ho(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=po(n)}function mo(s,e){let n=s;for(let o=0;o<e.length-1;o++){let i=n[String(e[o])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}var Qe=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=$e(e,".popmelt");this.indexPath=$e(o,"materialized.json"),this.runsPath=$e(o,"materialization-runs.json"),this.proposalsPath=$e(o,"model-proposals.json"),this.modelPath=$e(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=lo(n.rules)),n}catch{return null}}async addComponent(e){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let t=n.components;return t[e]?{added:!1,alreadyExists:!0}:(t[e]={description:""},await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${se} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]});let o=e.split("."),i=t;for(let m=0;m<o.length-1;m++){let k=o[m];(!i[k]||typeof i[k]!="object")&&(i[k]={}),i=i[k]}let a=o[o.length-1],l;try{l=JSON.parse(n)}catch{l=null}if(l&&typeof l=="object"&&l!==null&&"value"in l)i[a]=l;else{let 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(t,null,2)),console.log(`${se} Updated token "${e}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=e.split("."),o=n;for(let a=0;a<t.length-1;a++){let l=t[a];if(!o[l]||typeof o[l]!="object")return{removed:!1};o=o[l]}let i=t[t.length-1];return i in o?(delete o[i],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${se} Removed token "${e}" from model`),{removed:!0}):{removed:!1}}async removeComponent(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=n.components;return!t||!t[e]?{removed:!1}:(delete t[e],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${se} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){return(await this.selectUnmaterializedPatternDecisions()).decisions}async selectUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=(await this.decisionStore.listDecisionIds()).filter(l=>{let m=e.decisions[l];return m?m.status==="applied"||m.status==="merged"||m.status==="rejected"||m.status==="running"||m.status==="queued"||m.status==="proposed"?!1:m.attemptCount<3:!0});if(t.length===0)return{decisions:[],totalCandidateDecisionCount:0};let i=(await this.decisionStore.loadDecisions(t)).filter(l=>l.resolutions.some(m=>(m.finalScope??m.inferredScope)?.breadth==="pattern")),a=i.sort((l,m)=>m.createdAt-l.createdAt).slice(0,ao);return i.length>a.length&&console.log(`${se} Selected ${a.length}/${i.length} pattern decision(s); remaining decisions stay pending for later runs.`),{decisions:a,totalCandidateDecisionCount:i.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnmaterializedPatternDecisions(),o=t.decisions;if(o.length===0)return{processedIds:[],success:!0};let i=o.map(B=>B.id);console.log(`${se} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let a=await this.loadModel(),l=vo(o,a),m=co(o,t.totalCandidateDecisionCount,l);n=en().slice(0,8);let k={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,decisionIds:i,startedAt:Date.now(),promptStats:m};await this.persistRun(k),await this.updateDecisionStates(i,"running",n);let b=!0,E,O,$;try{let B=`mat-${Date.now()}`,{provider:S,result:j}=this.spawnModelAgent(B,l,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});k={...k,provider:S},await this.persistRun(k);let K=await j;if(!K.success)b=!1,E=K.error,console.error(`${se} ${S} spawn error:`,E);else{let L=Xe(K.text);if(L){Array.isArray(L.rules)&&(L.rules=_e(L.rules)),O=uo(L,i);let X=await this.createModelProposal({decisionIds:i,proposedModel:L,runId:n,threadId:e.threadId,provider:S,model:e.model??this.options.model});$=X.id,console.log(`${se} Created model proposal ${X.id} for ${i.length} decision(s)`)}else b=!1,E="No <model> block found in response",console.error(`${se} ${E}`)}}catch(B){b=!1,E=B instanceof Error?B.message:String(B),console.error(`${se} Error:`,E)}let q=await this.loadIndex();return q.lastRunAt=Date.now(),q.lastRunDecisionIds=i,q.lastRunError=E??null,await this.persistIndex(q),await this.updateDecisionStates(i,b?"proposed":"failed",n,E),await this.persistRun({...k,status:b?"proposed":"failed",completedAt:Date.now(),error:E,outputStats:O,proposalId:$}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:b,error:E}),{processedIds:i,success:b,error:E,runId:n,proposalId:$}}finally{this.running=!1}}async consolidate(e={}){if(this.running)return{success:!1,error:"Already running"};this.running=!0;try{let n=await this.loadModel();if(!n)return{success:!1,error:"No model exists"};let t=wo(n),{provider:o,result:i}=this.spawnModelAgent(`consolidate-${Date.now()}`,t,e,{maxTurns:this.options.maxTurns??3,maxBudgetUsd:this.options.maxBudgetUsd??.3,allowedTools:[]}),a=await i;if(!a.success)return console.error(`${se} ${o} consolidation spawn error:`,a.error),{success:!1,error:a.error};let l=Xe(a.text);return l?(Array.isArray(l.rules)&&(l.rules=_e(l.rules)),!l.tokens&&n.tokens&&(l.tokens=n.tokens),!l.components&&n.components&&(l.components=n.components),await ve(this.modelPath,JSON.stringify(l,null,2)),console.log(`${se} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${se} No <model> block in consolidation response`),{success:!1,error:"No <model> block found"})}catch(n){let t=n instanceof Error?n.message:String(n);return console.error(`${se} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=_e(e.rules)),await ve(this.modelPath,JSON.stringify(e,null,2)),console.log(`${se} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await qe(this.indexPath,"utf-8"),n=JSON.parse(e);if(n.version===2&&n.decisions)return this.cachedIndex=n,this.cachedIndex;if(n.version===1&&Array.isArray(n.materializedIds)){let t=Date.now(),o=Object.fromEntries(n.materializedIds.map(i=>[i,{status:"applied",runIds:[],attemptCount:1,updatedAt:t}]));return this.cachedIndex={version:2,decisions:o,lastRunAt:n.lastRunAt??null,lastRunDecisionIds:n.lastRunDecisionIds??[],lastRunError:n.lastRunError??null,materializedIds:n.materializedIds},this.cachedIndex}}catch{return this.cachedIndex={...tn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...tn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}async persistIndex(e){e.materializedIds=Object.entries(e.decisions).filter(([,n])=>n.status==="applied"||n.status==="merged").map(([n])=>n),this.cachedIndex=e;try{await pt(ht(this.indexPath),{recursive:!0}),await ve(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${se} Failed to write index:`,n)}}async loadRuns(){try{let e=await qe(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...ro,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{...io,proposals:[]}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,o)=>o.updatedAt-t.updatedAt)[0]??null}async applyModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;if(n.status==="dismissed")return n;await this.writeModel(n.proposedModel);let t=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0});return await this.updateDecisionStates(n.decisionIds,"applied",n.runId??e),t}async applySelectedModelProposal(e,n){let t=await this.findModelProposal(e);if(!t)return null;if(t.status==="dismissed")return t;let o=await this.loadModel()??{};for(let a of n)!Array.isArray(a.path)||a.path.length===0||(a.remove?mo(o,a.path):fo(o,a.path,a.value));await this.writeModel(o);let i=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0});return await this.updateDecisionStates(t.decisionIds,"applied",t.runId??e),i}async dismissModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;let t=await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()});return await this.updateDecisionStates(n.decisionIds,"rejected",n.runId??e),t}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let o=new Set(t.generatedEvalIds??[]);for(let i of n)o.add(i);return this.updateModelProposal(e,{generatedEvalIds:[...o]})}async createModelProposal(e){let n={id:en().slice(0,8),status:"pending",title:go(e.proposedModel),summary:yo(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,provider:e.provider,model:e.model,proposedModel:e.proposedModel,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(o=>o.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),o=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(o={...i,...n,updatedAt:Date.now()},o)),o?(t.updatedAt=Date.now(),await this.persistModelProposals(t),o):null}async persistModelProposals(e){try{await pt(ht(this.proposalsPath),{recursive:!0}),await ve(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${se} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(o=>o.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await pt(ht(this.runsPath),{recursive:!0}),await ve(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${se} Failed to write materialization run:`,n)}}async updateDecisionStates(e,n,t,o){let i=await this.loadIndex(),a=Date.now();for(let l of e){let m=i.decisions[l],k=m?.runIds.includes(t)?m.runIds:[...m?.runIds??[],t];i.decisions[l]={status:n,runIds:k,error:o,attemptCount:n==="running"?m?.attemptCount??0:(m?.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,m)=>this.options.onEvent?.(l):void 0;return i==="codex"?{provider:"codex",...Le(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:a})}:(i==="copilot"&&console.warn(`${se} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...je(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 go(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 yo(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 vo(s,e){let n=s.map(i=>{let l=i.resolutions.filter(b=>(b.finalScope??b.inferredScope)?.breadth==="pattern").map(b=>{let O=(b.finalScope??b.inferredScope)?.target??"unknown",$=b.filesModified?.join(", ")??"none";return`- **${b.summary}** [scope: pattern/${O}]
|
|
208
|
-
Files modified: ${
|
|
209
|
-
`),m=i.annotations.map(
|
|
210
|
-
`),
|
|
207
|
+
${n}`}function fe(s){return typeof s=="string"?s.trim():""}function xe(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Ks(s){let e=fe(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function Zs(s){let e=fe(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function eo(s){let e=fe(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function to(s,e){let t=(Array.isArray(s)?s:[]).map(o=>{if(!o||typeof o!="object")return null;let i=o,l=fe(i.assertion);return l?{assertion:l,status:eo(i.status)??"needs_review",summary:fe(i.summary)||Kt("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 no(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function so(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 Kt(s){return s==="pass"?"The current page appears to satisfy this eval.":s==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function oo(s){return Zt(s).slice(0,48)}function Zt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ge(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as en}from"crypto";import{mkdir as pt,readFile as qe,writeFile as ve}from"fs/promises";import{dirname as ht,join as $e}from"path";var se="[Materializer]",tn={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},ro={version:1,runs:[]},io={version:1,updatedAt:0,proposals:[]},ao=12;function lo(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(`${se} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${se} Rule count ${e.length} exceeds cap of 30`),e}function co(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function uo(s,e){let n=new Set(e),t=new Set,o=Array.isArray(s.rules)?s.rules:[];for(let a of o){if(!a||typeof a!="object")continue;let m=a.sources;if(Array.isArray(m))for(let M of m)typeof M=="string"&&n.has(M)&&t.add(M)}let i=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?s.tokens:{},l=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?s.components:{};return{ruleCount:o.length,tokenSectionCount:Object.keys(i).length,componentCount:Object.keys(l).length,coveredDecisionIds:[...t],uncoveredDecisionIds:e.filter(a=>!t.has(a))}}function po(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function ho(s,e,n){let t=s[e];if(t&&typeof t=="object")return t;let o=typeof n=="number"?[]:{};return s[String(e)]=o,o}function fo(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=ho(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=po(n)}function mo(s,e){let n=s;for(let o=0;o<e.length-1;o++){let i=n[String(e[o])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}var Qe=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=$e(e,".popmelt");this.indexPath=$e(o,"materialized.json"),this.runsPath=$e(o,"materialization-runs.json"),this.proposalsPath=$e(o,"model-proposals.json"),this.modelPath=$e(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=lo(n.rules)),n}catch{return null}}async addComponent(e){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let t=n.components;return t[e]?{added:!1,alreadyExists:!0}:(t[e]={description:""},await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${se} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]});let o=e.split("."),i=t;for(let m=0;m<o.length-1;m++){let M=o[m];(!i[M]||typeof i[M]!="object")&&(i[M]={}),i=i[M]}let l=o[o.length-1],a;try{a=JSON.parse(n)}catch{a=null}if(a&&typeof a=="object"&&a!==null&&"value"in a)i[l]=a;else{let m=i[l];m&&typeof m=="object"&&m!==null&&"value"in m?m.value=n:i[l]=n}return await ve(this.modelPath,JSON.stringify(t,null,2)),console.log(`${se} Updated token "${e}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=e.split("."),o=n;for(let l=0;l<t.length-1;l++){let a=t[l];if(!o[a]||typeof o[a]!="object")return{removed:!1};o=o[a]}let i=t[t.length-1];return i in o?(delete o[i],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${se} Removed token "${e}" from model`),{removed:!0}):{removed:!1}}async removeComponent(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=n.components;return!t||!t[e]?{removed:!1}:(delete t[e],await ve(this.modelPath,JSON.stringify(n,null,2)),console.log(`${se} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){return(await this.selectUnmaterializedPatternDecisions()).decisions}async selectUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=(await this.decisionStore.listDecisionIds()).filter(a=>{let m=e.decisions[a];return m?m.status==="applied"||m.status==="merged"||m.status==="rejected"||m.status==="running"||m.status==="queued"||m.status==="proposed"?!1:m.attemptCount<3:!0});if(t.length===0)return{decisions:[],totalCandidateDecisionCount:0};let i=(await this.decisionStore.loadDecisions(t)).filter(a=>a.resolutions.some(m=>(m.finalScope??m.inferredScope)?.breadth==="pattern")),l=i.sort((a,m)=>m.createdAt-a.createdAt).slice(0,ao);return i.length>l.length&&console.log(`${se} Selected ${l.length}/${i.length} pattern decision(s); remaining decisions stay pending for later runs.`),{decisions:l,totalCandidateDecisionCount:i.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnmaterializedPatternDecisions(),o=t.decisions;if(o.length===0)return{processedIds:[],success:!0};let i=o.map(j=>j.id);console.log(`${se} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let l=await this.loadModel(),a=vo(o,l),m=co(o,t.totalCandidateDecisionCount,a);n=en().slice(0,8);let M={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:m};await this.persistRun(M),await this.updateDecisionStates(i,"running",n);let x=!0,T,z,J;try{let j=`mat-${Date.now()}`,{provider:w,result:U}=this.spawnModelAgent(j,a,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});M={...M,provider:w},await this.persistRun(M);let V=await U;if(!V.success)x=!1,T=V.error,console.error(`${se} ${w} spawn error:`,T);else{let W=Xe(V.text);if(W){Array.isArray(W.rules)&&(W.rules=_e(W.rules)),z=uo(W,i);let Q=await this.createModelProposal({decisionIds:i,proposedModel:W,runId:n,threadId:e.threadId,provider:w,model:e.model??this.options.model});J=Q.id,console.log(`${se} Created model proposal ${Q.id} for ${i.length} decision(s)`)}else x=!1,T="No <model> block found in response",console.error(`${se} ${T}`)}}catch(j){x=!1,T=j instanceof Error?j.message:String(j),console.error(`${se} Error:`,T)}let q=await this.loadIndex();return q.lastRunAt=Date.now(),q.lastRunDecisionIds=i,q.lastRunError=T??null,await this.persistIndex(q),await this.updateDecisionStates(i,x?"proposed":"failed",n,T),await this.persistRun({...M,status:x?"proposed":"failed",completedAt:Date.now(),error:T,outputStats:z,proposalId:J}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:x,error:T}),{processedIds:i,success:x,error:T,runId:n,proposalId:J}}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=wo(n),{provider:o,result:i}=this.spawnModelAgent(`consolidate-${Date.now()}`,t,e,{maxTurns:this.options.maxTurns??3,maxBudgetUsd:this.options.maxBudgetUsd??.3,allowedTools:[]}),l=await i;if(!l.success)return console.error(`${se} ${o} consolidation spawn error:`,l.error),{success:!1,error:l.error};let a=Xe(l.text);return a?(Array.isArray(a.rules)&&(a.rules=_e(a.rules)),!a.tokens&&n.tokens&&(a.tokens=n.tokens),!a.components&&n.components&&(a.components=n.components),await ve(this.modelPath,JSON.stringify(a,null,2)),console.log(`${se} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${se} No <model> block in consolidation response`),{success:!1,error:"No <model> block found"})}catch(n){let t=n instanceof Error?n.message:String(n);return console.error(`${se} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=_e(e.rules)),await ve(this.modelPath,JSON.stringify(e,null,2)),console.log(`${se} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await qe(this.indexPath,"utf-8"),n=JSON.parse(e);if(n.version===2&&n.decisions)return this.cachedIndex=n,this.cachedIndex;if(n.version===1&&Array.isArray(n.materializedIds)){let t=Date.now(),o=Object.fromEntries(n.materializedIds.map(i=>[i,{status:"applied",runIds:[],attemptCount:1,updatedAt:t}]));return this.cachedIndex={version:2,decisions:o,lastRunAt:n.lastRunAt??null,lastRunDecisionIds:n.lastRunDecisionIds??[],lastRunError:n.lastRunError??null,materializedIds:n.materializedIds},this.cachedIndex}}catch{return this.cachedIndex={...tn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...tn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}async persistIndex(e){e.materializedIds=Object.entries(e.decisions).filter(([,n])=>n.status==="applied"||n.status==="merged").map(([n])=>n),this.cachedIndex=e;try{await pt(ht(this.indexPath),{recursive:!0}),await ve(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${se} Failed to write index:`,n)}}async loadRuns(){try{let e=await qe(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...ro,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{...io,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 findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,o)=>t.createdAt-o.createdAt||t.updatedAt-o.updatedAt)}async applyModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;if(n.status==="dismissed")return n;await this.writeModel(n.proposedModel);let t=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0});return await this.updateDecisionStates(n.decisionIds,"applied",n.runId??e),t}async applySelectedModelProposal(e,n,t){let o=await this.findModelProposal(e);if(!o)return null;if(o.status==="dismissed")return o;let i=await this.loadModel()??{};for(let a of n)!Array.isArray(a.path)||a.path.length===0||(a.remove?mo(i,a.path):fo(i,a.path,a.value));await this.writeModel(i);let l=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0,selectedChanges:t});return await this.updateDecisionStates(o.decisionIds,"applied",o.runId??e),l}async dismissModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;let t=await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()});return await this.updateDecisionStates(n.decisionIds,"rejected",n.runId??e),t}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let o=new Set(t.generatedEvalIds??[]);for(let i of n)o.add(i);return this.updateModelProposal(e,{generatedEvalIds:[...o]})}async createModelProposal(e){let n={id:en().slice(0,8),status:"pending",title:go(e.proposedModel),summary:yo(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,provider:e.provider,model:e.model,proposedModel:e.proposedModel,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(o=>o.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),o=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(o={...i,...n,updatedAt:Date.now()},o)),o?(t.updatedAt=Date.now(),await this.persistModelProposals(t),o):null}async persistModelProposals(e){try{await pt(ht(this.proposalsPath),{recursive:!0}),await ve(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${se} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(o=>o.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await pt(ht(this.runsPath),{recursive:!0}),await ve(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${se} Failed to write materialization run:`,n)}}async updateDecisionStates(e,n,t,o){let i=await this.loadIndex(),l=Date.now();for(let a of e){let m=i.decisions[a],M=m?.runIds.includes(t)?m.runIds:[...m?.runIds??[],t];i.decisions[a]={status:n,runIds:M,error:o,attemptCount:n==="running"?m?.attemptCount??0:(m?.attemptCount??0)+1,updatedAt:l}}await this.persistIndex(i)}spawnModelAgent(e,n,t,o){let i=t.provider??this.options.provider??"claude",l=this.options.onEvent?(a,m)=>this.options.onEvent?.(a):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:l})}:(i==="copilot"&&console.warn(`${se} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...je(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:l})})}};function go(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 yo(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 vo(s,e){let n=s.map(i=>{let a=i.resolutions.filter(x=>(x.finalScope??x.inferredScope)?.breadth==="pattern").map(x=>{let z=(x.finalScope??x.inferredScope)?.target??"unknown",J=x.filesModified?.join(", ")??"none";return`- **${x.summary}** [scope: pattern/${z}]
|
|
208
|
+
Files modified: ${J}`}).join(`
|
|
209
|
+
`),m=i.annotations.map(x=>x.instruction).filter(Boolean).join(`
|
|
210
|
+
`),M=i.gitDiff?`
|
|
211
211
|
\`\`\`diff
|
|
212
212
|
${i.gitDiff.slice(0,2e3)}
|
|
213
213
|
\`\`\``:"";return`### Decision ${i.id} (${new Date(i.createdAt).toISOString()})
|
|
214
214
|
Page: ${i.url}
|
|
215
|
-
${
|
|
216
|
-
${
|
|
215
|
+
${a}
|
|
216
|
+
${M}
|
|
217
217
|
${m?`
|
|
218
218
|
Original instructions:
|
|
219
219
|
${m}`:""}`}).join(`
|
|
@@ -362,61 +362,61 @@ These are my proposed rule changes. Would you like to approve all of them, adjus
|
|
|
362
362
|
</question>
|
|
363
363
|
|
|
364
364
|
## After approval
|
|
365
|
-
When the developer approves (says "yes", "looks good", "go ahead", etc.), output the complete updated model inside <model> tags \u2014 the full JSON with tokens, components, and the revised rules array. Do NOT output partial models. Preserve tokens and components as-is unless the developer asks to change them.`}var 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:e.standalone===!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
|
|
366
|
-
`),n=[],t=null;for(let o of e){let i=o.match(
|
|
365
|
+
When the developer approves (says "yes", "looks good", "go ahead", etc.), output the complete updated model inside <model> tags \u2014 the full JSON with tokens, components, and the revised rules array. Do NOT output partial models. Preserve tokens and components as-is unless the developer asks to change them.`}var Ye=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let o of this.listeners)o(e,n,t)}cancelJob(e){let n=this.queue.findIndex(o=>o.id===e);if(n>=0){let[o]=this.queue.splice(n,1);return o?(o.status="cancelled",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:o.error,cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),o):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}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:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(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?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as So}from"child_process";import{readFile as mt}from"fs/promises";import{homedir as Ke}from"os";import{join as de}from"path";var gt=/popmelt/i,bo=/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 Oe(s){for(let e of Object.keys(s))if(gt.test(e))return e;return null}async function Ve(s){try{let e=await mt(s,"utf-8");return JSON.parse(e)}catch{return null}}async function yt(s){let e=Ke(),n=await Ve(de(e,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=Oe(o.mcpServers);if(i)return Pe(i,"user")}if(o.projects&&typeof o.projects=="object"){let l=o.projects[s];if(l&&typeof l=="object"){let a=l;if(a.mcpServers&&typeof a.mcpServers=="object"){let m=Oe(a.mcpServers);if(m){let M=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(x=>gt.test(x));return Pe(m,"project",M)}}}}}let t=await Ve(de(s,".mcp.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let l=Oe(o.mcpServers);if(l){let a=await sn(s,l);return Pe(l,"mcp.json",a)}}let i=Oe(o);if(i&&i!=="mcpServers"){let l=await sn(s,i);return Pe(i,"mcp.json",l)}}return be()}async function sn(s,e){let n=de(s,".claude","settings.local.json"),t=await Ve(n);if(t&&typeof t=="object"){let o=t;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var xo=/^\[mcp_servers\.([^\]]+)\]/;function Po(s){return s.replace(/^"(.+)"$/,"$1")}function Io(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function rn(s){let e=s.split(`
|
|
366
|
+
`),n=[],t=null;for(let o of e){let i=o.match(xo);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
367
367
|
`)}),t={name:i[1],bodyLines:[]}):o.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
|
|
368
368
|
`)}),t=null):t&&t.bodyLines.push(o)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
369
|
-
`)}),n}function an(s){return/enabled\s*=\s*false/i.test(s)}async function vt(s){let e=process.env.CODEX_HOME||de(
|
|
370
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function mn(s=
|
|
369
|
+
`)}),n}function an(s){return/enabled\s*=\s*false/i.test(s)}async function vt(s){let e=process.env.CODEX_HOME||de(Ke(),".codex"),n=await on(de(e,"config.toml"),"user");if(n.found)return n;let t=await on(de(s,".codex","config.toml"),"project");return t.found?t:be()}async function ko(s,e){let n=process.env.CODEX_HOME||de(Ke(),".codex"),t=new Set;for(let o of[de(n,"config.toml"),de(s,".codex","config.toml")])try{let i=await mt(o,"utf-8");for(let l of rn(i)){if(Io(l.name)||an(l.body))continue;let a=Po(l.name);e.test(a)&&t.add(a)}}catch{}return[...t]}async function ln(s){return ko(s,bo)}async function wt(s,e="copilot"){let n=await Mo(e);if(n.found)return n;let t=process.env.COPILOT_HOME||de(Ke(),".copilot"),o=await ft(de(t,"mcp-config.json"),"user");if(o.found)return o;let i=await ft(de(s,".mcp.json"),"mcp.json");if(i.found)return i;let l=await ft(de(s,".github","mcp.json"),"mcp.json");return l.found?l:be()}async function Mo(s){try{let e=await new Promise((n,t)=>{So(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return cn(JSON.parse(e),"user")}catch{return be()}}async function ft(s,e){let n=await Ve(s);return cn(n,e)}function cn(s,e){if(!s||typeof s!="object")return be();let n=s,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=Oe(t);return o?Pe(o,e):be()}async function on(s,e){try{let n=await mt(s,"utf-8"),t=rn(n);for(let o of t)if(gt.test(o.name)){let i=an(o.body);return Pe(o.name,e,i)}}catch{}return be()}import{execFile as dn}from"child_process";import{mkdir as Ro,readFile as un,writeFile as pn}from"fs/promises";import{homedir as hn}from"os";import{dirname as Eo,join as St}from"path";var bt="https://mcp.popmelt.com/mcp";async function fn(s=bt){let e=St(hn(),".claude.json"),n;try{let o=await un(e,"utf-8");n=JSON.parse(o)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let o of Object.keys(t))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:s},await pn(e,JSON.stringify(n,null,2)+`
|
|
370
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function mn(s=bt){let e=process.env.CODEX_HOME||St(hn(),".codex"),n=St(e,"config.toml"),t;try{t=await un(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Ro(Eo(n),{recursive:!0});let o=`
|
|
371
371
|
[mcp_servers.popmelt]
|
|
372
372
|
url = "${s}"
|
|
373
|
-
`;return await pn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function gn(s=
|
|
373
|
+
`;return await pn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function gn(s=bt,e="copilot"){let n=await To(e);if(Ao(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{dn(e,["mcp","add","--transport","http","--json","popmelt",s],{encoding:"utf-8",timeout:1e4},i=>{if(i){o(i);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function To(s){try{let e=await new Promise((n,t)=>{dn(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return JSON.parse(e)}catch{return null}}function Ao(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 Co(s),i=Buffer.from(`--${t}`),l=Buffer.from(`--${t}--`),a,m,M,x,T,z,J,q,j,w,U,V,W=[],Q=[],B=0,Z=[];for(;B<o.length;){let I=o.indexOf(i,B);if(I===-1)break;let D=I+i.length;if(o.slice(I,I+l.length).equals(l))break;let R=D;o[R]===13&&o[R+1]===10&&(R+=2);let f=o.indexOf(`\r
|
|
374
374
|
\r
|
|
375
|
-
`,
|
|
375
|
+
`,R);if(f===-1)break;let G=o.slice(R,f).toString("utf-8"),O=f+4,y=o.indexOf(i,O),$=y!==-1?y-2:o.length;Z.push({headers:G,body:o.slice(O,$)}),B=y!==-1?y:o.length}for(let I of Z){let D=I.headers.match(/name="([^"]+)"/);if(!D)continue;let R=D[1];if(R==="screenshot")a=I.body;else if(R==="feedback")m=I.body.toString("utf-8");else if(R==="color")M=I.body.toString("utf-8");else if(R==="provider")x=I.body.toString("utf-8");else if(R==="model")T=I.body.toString("utf-8");else if(R==="goal")z=I.body.toString("utf-8");else if(R==="pageUrl")J=I.body.toString("utf-8");else if(R==="viewport")q=I.body.toString("utf-8");else if(R==="planId")j=I.body.toString("utf-8");else if(R==="manifest")w=I.body.toString("utf-8");else if(R==="tasks")U=I.body.toString("utf-8");else if(R==="sourceId")V=I.body.toString("utf-8");else if(R.startsWith("screenshot-")){let f=R.slice(11);try{let G=decodeURIComponent(f);Q.push({pathname:G,data:I.body})}catch{}}else if(R.startsWith("image-")){let f=R.split("-"),G=parseInt(f[f.length-1],10),O=f.slice(1,-1).join("-");O&&!isNaN(G)&&W.push({annotationId:O,index:G,data:I.body})}}if(!a)throw new Error("Missing screenshot field");return m||(m=""),{screenshot:a,feedback:m,color:M,provider:x,model:T,goal:z,pageUrl:J,viewport:q,planId:j,manifest:w,tasks:U,sourceId:V,pastedImages:W,pageScreenshots:Q}}function Co(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 De(s,e){let n=[];if(s.annotations.length>0){n.push("## Annotations");for(let t of s.annotations){let o=t.elements.map(a=>{let m=[a.selector];return a.reactComponent&&m.push(`(${a.reactComponent})`),m.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${o||"none"}`);let l=e?.[t.id];if(l&&l.length>0)for(let a of l)n.push(` Attached image: use the Read tool to view ${a}`)}}if(s.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of s.styleModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${o}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if(s.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of s.spacingTokenChanges){n.push(`
|
|
376
376
|
### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let o of t.affectedElements){let i=o.reactComponent?` (${o.reactComponent})`:"";o.matchedClass&&o.suggestedClass?n.push(`- ${o.selector}${i}: \`${o.matchedClass}\` \u2192 \`${o.suggestedClass}\``):n.push(`- ${o.selector}${i}: ${o.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${o.className}"`)}}}if(s.inspectedElement){let t=s.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let o=[t.selector];t.reactComponent&&o.push(`(${t.reactComponent})`),t.context&&o.push(`in ${t.context}`),t.textContent&&o.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${o.join(" ")}`)}return n.join(`
|
|
377
|
-
`)}function yn(s,e,n){let t=[],i=new Set(e.annotations.map(
|
|
378
|
-
`)}function vn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function
|
|
377
|
+
`)}function yn(s,e,n){let t=[],i=new Set(e.annotations.map(l=>l.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 l=0;for(let a of n.threadHistory)if(a.role==="human")l++,a.replyToQuestion?(t.push(`### Round ${l} (human) \u2014 reply`),t.push(`"${a.replyToQuestion}"`)):(t.push(`### Round ${l} (human)`),a.feedbackSummary&&t.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&t.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)t.push(`### Round ${l} (assistant) \u2014 question`),t.push(`"${a.question}"`);else{if(t.push(`### Round ${l} (assistant)`),a.responseText&&t.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let m of a.resolutions){let M=m.finalScope??m.inferredScope,x=M?` [${M.breadth} ${M.target}]`:"";t.push(`- ${m.annotationId}: ${m.status}${x} \u2014 ${m.summary}`),m.filesModified&&m.filesModified.length>0&&t.push(` Files: ${m.filesModified.join(", ")}`)}a.toolsUsed&&a.toolsUsed.length>0&&t.push(`Tools used: ${a.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 l=n.designModel.rules;if(Array.isArray(l)&&l.length>0)if(t.push(""),t.push("Rules:"),l.length>0&&typeof l[0]=="object"&&l[0]!==null&&"scope"in l[0]){let x=new Map;for(let T of l)if(typeof T=="object"&&T!==null&&"text"in T){let z=T,J=z.scope||"general";x.has(J)||x.set(J,[]),x.get(J).push(z.text)}for(let[T,z]of x){t.push(`**${T.charAt(0).toUpperCase()+T.slice(1)}**`);for(let J of z)t.push(`- ${J}`)}}else for(let x of l)typeof x=="string"&&t.push(`- ${x}`);let a=n.designModel.tokens;a&&typeof a=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(a,null,2)),t.push("```"));let m=n.designModel.components;m&&typeof m=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(m,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 l=n?.screenshotPaths??{},a=new Map;for(let m of e.annotations){let M=m.pathname||new URL(e.url).pathname;a.has(M)||a.set(M,[]),a.get(M).push(m)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[m,M]of a){t.push(""),t.push(`## Page: ${m}`);let x=l[m];x&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${x}`):!x&&n?.provider!=="codex"&&(Object.keys(l).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 T={...e,annotations:M,styleModifications:e.styleModifications},z=De(T,n?.imagePaths);z&&(t.push(""),t.push(z))}}else{let l=De(e,n?.imagePaths);l&&(t.push(""),t.push(l))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
|
|
378
|
+
`)}function vn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function xt(s,e,n,t){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=e.find(l=>l.role==="human"&&l.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),e.length>0){o.push(""),o.push("## Conversation History");let l=0;for(let a of e)a.role==="human"?(l++,a.replyToQuestion?(o.push(`### Round ${l} (human) \u2014 reply`),o.push(`"${a.replyToQuestion}"`)):(o.push(`### Round ${l} (human)`),a.feedbackSummary&&o.push(`Annotations: ${a.feedbackSummary}`))):a.question?(o.push(`### Round ${l} (assistant) \u2014 question`),o.push(`"${a.question}"`)):(o.push(`### Round ${l} (assistant)`),a.responseText&&o.push(`Response: ${a.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 l of t)o.push(`Attached image: use the Read tool to view the image at: ${l}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output a resolution block listing what you did for each annotation:"),o.push("<resolution>"),o.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),o.push("</resolution>"),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
|
|
379
379
|
`)}function $o(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 _o(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&&!$o(e[n]))return!1;return!0}function wn(s){let e=s.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!e||!e[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(_o):[]}catch{return[]}}function Sn(s){let e=s.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let o=t;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}import{execFile as Oo}from"child_process";import{readdir as Do,readFile as No,stat as Jo}from"fs/promises";import{homedir as Ne}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"}],Je=[{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"}],ze={id:"",label:"Default",source:"cli"},zo=/^\s*-\s+"([^"]+)"/;function Bo(s){let e=[],n=!1;for(let t of s.split(`
|
|
380
|
-
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let o=t.match(zo);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:Pt(i),source:"cli"})}return nt([ze,...e])}function Fo(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,
|
|
381
|
-
`));return nt([...tt,...m])}function et(s,e,n=5e3){return new Promise((t,o)=>{Oo(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function In(s){return No(s,"utf-8")}async function Uo(s){let e=[ge(s,"projects"),ge(s,"telemetry")],n=[];for(let t of e)await kn(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function kn(s,e,n){if(n<0)return;let t;try{t=await Do(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=ge(s,o.name);if(o.isDirectory()){await kn(i,e,n-1);return}if(!(!o.isFile()||!Lo(o.name)))try{let a=await Jo(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function Lo(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 Wo(s){return[...new Set(s)]}function Ho(s){return s.charAt(0).toUpperCase()+s.slice(1)}var st=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let t=n>=0?n+1:0,o=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),o}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let o=this.bufferEvent(n,e);for(let i of this.listeners)i(o,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let o={...n,seq:t.nextSeq++};return t.events.push(o),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),o}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!t)return null;let a=n<0?t.events:t.events.filter(l=>l.seq>n);return{jobId:e,events:a,currentSeq:t.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(e,n,t){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(o=>{let i=!1,a=()=>{i||(i=!0,o())};t.on("exit",a),t.on("error",a),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(a,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="materialize_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{mkdir as Go,readFile as qo,writeFile as Qo}from"fs/promises";import{dirname as Xo,join as Yo}from"path";var Ko={version:1,threads:{}},ot=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=Yo(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await qo(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={...Ko,threads:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>t.has(a)))return o;return null}async createThread(e,n){let t=await this.load(),o={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=o,await this.persist(),o}async appendMessage(e,n){let o=(await this.load()).threads[e];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async appendMessageBeforeQueuedReplies(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=o.messages.findIndex(a=>a.role==="human"&&!!a.replyToQuestion&&a.queued);i>=0?o.messages.splice(i,0,n):o.messages.push(n),o.updatedAt=Date.now(),await this.persist()}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let a=i.messages.filter(l=>l.jobId===n);if(a.length===0)return!1;for(let l of a)Object.assign(l,t);return i.updatedAt=Date.now(),await this.persist(),!0}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 deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.persist(),!0):!1}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 Go(Xo(this.filePath),{recursive:!0}),await Qo(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function Mn(s){return Zo(s).slice(0,12)}var Vo=[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 Zo(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):er(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,m=2600822924,k=528734635,b=1541459225,E=new Array(64);for(let O=0;O<e.length;O+=64){for(let D=0;D<16;D++){let Z=O+D*4;E[D]=(e[Z]<<24|e[Z+1]<<16|e[Z+2]<<8|e[Z+3])>>>0}for(let D=16;D<64;D++){let Z=ye(E[D-15],7)^ye(E[D-15],18)^E[D-15]>>>3,I=ye(E[D-2],17)^ye(E[D-2],19)^E[D-2]>>>10;E[D]=E[D-16]+Z+E[D-7]+I>>>0}let $=t,q=o,B=i,S=a,j=l,K=m,L=k,X=b;for(let D=0;D<64;D++){let Z=ye(j,6)^ye(j,11)^ye(j,25),I=j&K^~j&L,N=X+Z+I+Vo[D]+E[D]>>>0,M=ye($,2)^ye($,13)^ye($,22),f=$&q^$&B^q&B,G=M+f>>>0;X=L,L=K,K=j,j=S+N>>>0,S=B,B=q,q=$,$=N+G>>>0}t=t+$>>>0,o=o+q>>>0,i=i+B>>>0,a=a+S>>>0,l=l+j>>>0,m=m+K>>>0,k=k+L>>>0,b=b+X>>>0}return[t,o,i,a,l,m,k,b].map(O=>O.toString(16).padStart(8,"0")).join("")}function ye(s,e){return s>>>e|s<<32-e}function er(s){let e=[];for(let n=0;n<s.length;n++){let t=s.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var Rn={name:"@popmelt.com/core",version:"0.8.1",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .",prepublishOnly:"pnpm run build",typecheck:"tsc --noEmit"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=0.400.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{},devDependencies:{"@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0","lucide-react":"^0.487.0",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3"}};var En=Rn.version;var pr=1111,hr=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],fr=1800*1e3,mr=3600*1e3;function An(s){return s.length<=1?s[0]??"":["The developer sent these queued steering messages while you were working:","",...s.map((e,n)=>`${n+1}. ${e}`)].join(`
|
|
382
|
-
`)}function Dn(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 gr(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,
|
|
383
|
-
`)[0].trim().slice(0,60):"Running command";break;case"Glob":
|
|
384
|
-
`)}function vr(s,e=96){let n=s.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function $n(s){let e=s.styleModifications.flatMap(i=>{let
|
|
380
|
+
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let o=t.match(zo);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:Pt(i),source:"cli"})}return nt([ze,...e])}function Fo(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,l=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-l}).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 jo(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":Ho(t[1]),l=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${i}${l}${t[4]?" Fast":""}`}let o=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let i=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${i}`:o[3]==="codex"?`Codex ${i}`:o[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function bn(s="copilot"){let e=await et(s,["help","config"]),n=Bo(e);return n.length>1?n:[ze]}async function xn(s="codex"){let e=await et(s,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||ge(Ne(),".codex");return In(ge(t,"models_cache.json"))}),n=Fo(e);return n.length>0?nt([...n,...Je]):Je}async function Pn(s="claude"){let e=ge(Ne(),".claude"),n=[ge(Ne(),".claude","stats-cache.json"),ge(Ne(),".claude","settings.json"),ge(Ne(),".claude.json"),ge(e,"cache","changelog.md")],[t,o,i]=await Promise.all([et(s,["--help"]).catch(()=>""),et(s,["--version"]).catch(()=>""),Uo(e).catch(()=>[])]),l=Wo([...n,...i]),a=await Promise.all(l.map(M=>In(M).catch(()=>""))),m=jo([t,o,...a].join(`
|
|
381
|
+
`));return nt([...tt,...m])}function et(s,e,n=5e3){return new Promise((t,o)=>{Oo(s,e,{encoding:"utf-8",timeout:n},(i,l)=>{if(i){o(i);return}t(l)})})}async function In(s){return No(s,"utf-8")}async function Uo(s){let e=[ge(s,"projects"),ge(s,"telemetry")],n=[];for(let t of e)await kn(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function kn(s,e,n){if(n<0)return;let t;try{t=await Do(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=ge(s,o.name);if(o.isDirectory()){await kn(i,e,n-1);return}if(!(!o.isFile()||!Lo(o.name)))try{let l=await Jo(i);if(l.size>2e6)return;e.push({path:i,mtimeMs:l.mtimeMs})}catch{}}))}function Lo(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 Wo(s){return[...new Set(s)]}function Ho(s){return s.charAt(0).toUpperCase()+s.slice(1)}var st=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let t=n>=0?n+1:0,o=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),o}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let o=this.bufferEvent(n,e);for(let i of this.listeners)i(o,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let o={...n,seq:t.nextSeq++};return t.events.push(o),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),o}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!t)return null;let l=n<0?t.events:t.events.filter(a=>a.seq>n);return{jobId:e,events:l,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,l=()=>{i||(i=!0,o())};t.on("exit",l),t.on("error",l),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(l,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 Go,readFile as qo,writeFile as Qo}from"fs/promises";import{dirname as Xo,join as Yo}from"path";var Vo={version:1,threads:{}},ot=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=Yo(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await qo(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={...Vo,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(l=>t.has(l)))return o;return null}async createThread(e,n){let t=await this.load(),o={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=o,await this.persist(),o}async appendMessage(e,n){let o=(await this.load()).threads[e];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async appendMessageBeforeQueuedReplies(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=o.messages.findIndex(l=>l.role==="human"&&!!l.replyToQuestion&&l.queued);i>=0?o.messages.splice(i,0,n):o.messages.push(n),o.updatedAt=Date.now(),await this.persist()}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let l=i.messages.filter(a=>a.jobId===n);if(l.length===0)return!1;for(let a of l)Object.assign(a,t);return i.updatedAt=Date.now(),await this.persist(),!0}async addElementIdentifiers(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=new Set(o.elementIdentifiers);for(let l of n)i.has(l)||o.elementIdentifiers.push(l);o.updatedAt=Date.now(),await this.persist()}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.persist(),!0):!1}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 l=o.messages.find(a=>a.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:l,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 Go(Xo(this.filePath),{recursive:!0}),await Qo(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function Mn(s){return Zo(s).slice(0,12)}var Ko=[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 Zo(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):er(s),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let z=7;z>=0;z--)e.push(n/Math.pow(2,z*8)&255);let t=1779033703,o=3144134277,i=1013904242,l=2773480762,a=1359893119,m=2600822924,M=528734635,x=1541459225,T=new Array(64);for(let z=0;z<e.length;z+=64){for(let B=0;B<16;B++){let Z=z+B*4;T[B]=(e[Z]<<24|e[Z+1]<<16|e[Z+2]<<8|e[Z+3])>>>0}for(let B=16;B<64;B++){let Z=ye(T[B-15],7)^ye(T[B-15],18)^T[B-15]>>>3,I=ye(T[B-2],17)^ye(T[B-2],19)^T[B-2]>>>10;T[B]=T[B-16]+Z+T[B-7]+I>>>0}let J=t,q=o,j=i,w=l,U=a,V=m,W=M,Q=x;for(let B=0;B<64;B++){let Z=ye(U,6)^ye(U,11)^ye(U,25),I=U&V^~U&W,D=Q+Z+I+Ko[B]+T[B]>>>0,R=ye(J,2)^ye(J,13)^ye(J,22),f=J&q^J&j^q&j,G=R+f>>>0;Q=W,W=V,V=U,U=w+D>>>0,w=j,j=q,q=J,J=D+G>>>0}t=t+J>>>0,o=o+q>>>0,i=i+j>>>0,l=l+w>>>0,a=a+U>>>0,m=m+V>>>0,M=M+W>>>0,x=x+Q>>>0}return[t,o,i,l,a,m,M,x].map(z=>z.toString(16).padStart(8,"0")).join("")}function ye(s,e){return s>>>e|s<<32-e}function er(s){let e=[];for(let n=0;n<s.length;n++){let t=s.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var Rn={name:"@popmelt.com/core",version:"0.8.2",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .",prepublishOnly:"pnpm run build",typecheck:"tsc --noEmit"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=1.23.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{},devDependencies:{"@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0","lucide-react":"^1.23.0",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3"}};var En=Rn.version;var pr=1111,hr=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],fr=1800*1e3,mr=3600*1e3;function Cn(s){return s.length<=1?s[0]??"":["The developer sent these queued steering messages while you were working:","",...s.map((e,n)=>`${n+1}. ${e}`)].join(`
|
|
382
|
+
`)}function Dn(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 gr(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,l=o?o.split("/").pop()??o:void 0,a;switch(t){case"Read":a=l?`Reading ${l}`:"Reading file";break;case"Edit":a=l?`Editing ${l}`:"Editing file";break;case"Write":a=l?`Writing ${l}`:"Writing file";break;case"Bash":a=i?i.split(`
|
|
383
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":a="Searching files";break;case"Grep":a="Searching code";break;case"WebFetch":a="Fetching page";break;case"WebSearch":a="Searching web";break;default:a=t?`Using ${t}`:"tool";break}let m=o??i??void 0,M=e[e.length-1];M&&M.kind==="tool_group"&&M.tool===t?M.items.push({label:a,detail:m}):e.push({kind:"tool_group",tool:t,items:[{label:a,detail:m}]})}return e}function yr(s,e){if(s.processedIds.length===0&&s.success)return"No unmaterialized pattern decisions were ready for model materialization.";let n=[];return s.success?n.push("Model suggestion ready."):n.push("Model materialization failed."),s.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),s.error&&(n.push(""),n.push(`Error: ${s.error}`),n.push("The selected decisions were not marked applied and remain visible in materialization history.")),n.join(`
|
|
384
|
+
`)}function vr(s,e=96){let n=s.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function $n(s){let e=s.styleModifications.flatMap(i=>{let l=i.element?.reactComponent||i.element?.tagName||i.selector;return i.changes.map(a=>`${l}: ${a.property} ${a.original||"unset"} -> ${a.modified||"unset"}`)}),n=(s.spacingTokenChanges??[]).map(i=>`${i.tokenName}: ${i.originalPx}px -> ${i.newPx}px`),t=s.annotations.map(i=>{let l=i.instruction?.trim();if(l)return l;if(i.imageCount&&i.imageCount>0)return`${i.imageCount} image${i.imageCount===1?"":"s"}`;let a=i.elements?.[0]?.reactComponent||i.elements?.[0]?.selector||i.linkedSelector||i.type;return`${i.type==="annotation"?"Annotation":`${i.type} annotation`} on ${a}`}),o=[...e,...n,...t].map(i=>vr(i)).filter(Boolean);return o.length===0?"Annotation":o.length<=3?o.join("; "):`${o.slice(0,3).join("; ")}; +${o.length-3} more`}function wr(s,e){let n=s.headers.origin;Dn(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 g(s,e,n){s.writeHead(e,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}function Sr(s,e){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function br(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
385
|
data: ${JSON.stringify(e)}
|
|
386
386
|
|
|
387
|
-
`)}catch{}}function Ie(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function
|
|
387
|
+
`)}catch{}}function Ie(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function xr(s){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),t=await fetch(`http://127.0.0.1:${s}/status`,{signal:e.signal});return clearTimeout(n),t.ok?await t.json():null}catch{return null}}function Pr(s,e){return new Promise((n,t)=>{let o=l=>{s.removeListener("listening",i),t(l)},i=()=>{s.removeListener("error",o),n()};s.once("error",o),s.once("listening",i),s.listen(e,"127.0.0.1")})}function _n(s){try{let e=at("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=at("git",["status","--porcelain","--untracked-files=all",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),o=at("git",["diff","HEAD",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return nr("sha256").update(`${e}
|
|
388
388
|
${t}
|
|
389
|
-
${o}`).digest("hex").slice(0,16)}catch{return}}async function Nn(s={}){let e=s.port??pr,n=s.projectRoot??process.cwd(),t=await rr(n).catch(()=>n),o=Mn(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),
|
|
389
|
+
${o}`).digest("hex").slice(0,16)}catch{return}}async function Nn(s={}){let e=s.port??pr,n=s.projectRoot??process.cwd(),t=await rr(n).catch(()=>n),o=Mn(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),l=s.tempDir??me(cr(),"popmelt-bridge"),a=s.maxTurns??40,m=s.maxBudgetUsd??1,M=[...s.allowedTools??hr],x=s.claudePath??"claude",T=s.copilotPath??"copilot",z=s.provider??"claude",J=s.timeoutMs,q=s.restartMode??"embedded",j=e,w={},U={claude:x,codex:"codex",copilot:T};for(let[r,c]of Object.entries(U))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 V(r,c){return new Promise(p=>{let u=Tn(c,["--version"],{stdio:["ignore","ignore","ignore"]}),h=!1,d=S=>{h||(h=!0,p(S))},b=setTimeout(()=>{u.kill("SIGTERM"),d(!0)},5e3);u.on("error",()=>{clearTimeout(b),d(!1)}),u.on("close",S=>{clearTimeout(b),d(S===0)})})}await Promise.all([(async()=>{w.claude&&(w.claude.models=w.claude.available&&w.claude.path?await Pn(w.claude.path).catch(()=>tt):tt)})(),(async()=>{w.codex&&(w.codex.models=w.codex.available&&w.codex.path?await xn(w.codex.path).catch(()=>Je):Je)})(),(async()=>{w.copilot&&(w.copilot.models=w.copilot.available&&w.copilot.path?await bn(w.copilot.path).catch(()=>[ze]):[ze])})()]);let[W,Q,B]=await Promise.all([yt(t),vt(t),wt(t,w.copilot?.path??T)]),Z=await ln(t);w.claude&&(w.claude.mcp=W),w.codex&&(w.codex.mcp=Q),w.copilot&&(w.copilot.mcp=B),W.found&&W.name&&M.push(`mcp__${W.name}__*`),await sr(l,{recursive:!0}),On(l).catch(()=>{});let I=new st(1),D=new Ye,R=new Set,f=new ot(t),G=new We(t),O=new He(t),y=new Qe(t,G,{claudePath:x,provider:z,timeoutMs:J,onEvent:r=>{for(let c of R)it(c,r)}}),$=20,ne=300*1e3,C=[];function ie(){let r=Date.now()-ne;for(;C.length>0&&(C[0].completedAt<r||C.length>$);)C.shift()}let ee=new Map,oe=null,ke;I.addListener((r,c,p)=>{for(let u of R)(!p||!u.sourceId||u.sourceId===p)&&it(u,r)}),D.addListener((r,c,p)=>{for(let u of R)(!p||!u.sourceId||u.sourceId===p)&&it(u,r)}),D.setProcessor(async r=>{let c=r.provider??z;try{let p=await y.run({provider:c,model:r.model,threadId:r.threadId});if(r.status==="cancelled")return;let u=await y.loadRuns(),h=p.runId?u.runs.find(b=>b.id===p.runId):void 0,d=yr(p,h);if(r.threadId&&(await f.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c})||await f.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c})),p.success)r.status="done",r.result=d,D.broadcast({type:"done",jobId:r.id,success:!0,responseText:d,threadId:r.threadId},r.id,r.sourceId),C.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),ie();else{if(r.status="error",r.error=p.error??"Materialization failed",r.threadId){let b=`Model materialization failed.
|
|
390
390
|
|
|
391
|
-
${r.error}`;await f.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:
|
|
391
|
+
${r.error}`;await f.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:b,error:r.error,model:r.model,provider:c})||await f.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:b,error:r.error,model:r.model,provider:c})}D.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),C.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),ie()}}catch(p){if(r.status==="cancelled")return;if(r.status="error",r.error=p instanceof Error?p.message:String(p),r.threadId){let u=`Model materialization failed.
|
|
392
392
|
|
|
393
|
-
${r.error}`;await f.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:
|
|
393
|
+
${r.error}`;await f.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:u,error:r.error,model:r.model,provider:c})||await f.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:u,error:r.error,model:r.model,provider:c})}D.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),C.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),ie()}}),I.setProcessor(async r=>{let c=r,p=c._replyPrompt,u=c._replyText,h=c._replyImagePaths,d=r.provider??z;r.threadId&&u!==void 0&&await f.updateMessage(r.threadId,r.id,{queued:!1});let b;if(r.threadId){let _=await f.getThread(r.threadId);if(_){for(let H=_.messages.length-1;H>=0;H--)if(_.messages[H].sessionId){b=_.messages[H].sessionId;break}}}let S;if(b&&p){if(S=u??p,h&&h.length>0){S+=`
|
|
394
394
|
|
|
395
|
-
The developer attached reference images with their reply:`;for(let _ of h)
|
|
396
|
-
Attached image: use the Read tool to view the image at: ${_}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?
|
|
395
|
+
The developer attached reference images with their reply:`;for(let _ of h)S+=`
|
|
396
|
+
Attached image: use the Read tool to view the image at: ${_}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?S+=`
|
|
397
397
|
|
|
398
|
-
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:
|
|
398
|
+
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:S+=`
|
|
399
399
|
|
|
400
|
-
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(
|
|
400
|
+
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(b)S=De(r.feedback,r.imagePaths)+`
|
|
401
401
|
|
|
402
402
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
403
403
|
|
|
404
404
|
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
|
|
405
405
|
|
|
406
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let _=!u&&r.threadId?await f.getThreadHistory(r.threadId):void 0,H=u?null:await v.loadModel();g=u??yn(r.screenshotPath,r.feedback,{threadHistory:_&&_.length>0?_:void 0,provider:d,imagePaths:r.imagePaths,designModel:H??void 0,screenshotPaths:r.screenshotPaths})}let R=xr(r.color,`[\u22B9 ${B}:${r.id}]`),W=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${R} Reviewing ${W} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${x?` (resuming: ${x.slice(0,8)})`:""}`);let J=(_,H)=>{_.type==="delta"&&"text"in _?I.accumulateText(H,"response",_.text):_.type==="thinking"&&"text"in _&&I.accumulateText(H,"thinking",_.text),I.broadcast(_,H,r.sourceId)},{process:F,result:Q}=d==="codex"?Le(r.id,{prompt:g,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:x,model:r.model,onEvent:J}):d==="copilot"?Ft(r.id,{prompt:g,projectRoot:t,resumeSessionId:x,model:r.model,timeoutMs:$,copilotPath:S.copilot?.path??E,onEvent:J}):je(r.id,{prompt:g,projectRoot:t,maxTurns:l,maxBudgetUsd:m,allowedTools:k,claudePath:b,resumeSessionId:x,model:r.model,timeoutMs:$,onEvent:J});I.setActiveProcess(r.id,F);let P=await Q;if(r.result=P.text,P.success){console.log(`${R} Iteration complete`),P.fileEdits&&P.fileEdits.length>0&&console.log(`${R} Captured ${P.fileEdits.length} file edit(s): ${P.fileEdits.map(z=>`${z.tool} ${z.file_path}`).join(", ")}`),P.editEvents&&P.editEvents.length>0&&console.log(`${R} Captured ${P.editEvents.length} edit event(s): ${P.editEvents.map(z=>`${z.operation} ${z.filePath}`).join(", ")}`),r.status="done";let _=vn(P.text),H=wn(P.text),te=H.some(z=>(z.finalScope??z.inferredScope)?.breadth==="pattern");if(H.length>0&&r.annotationIds&&r.annotationIds.length>0){let z=new Set(r.annotationIds);H.every(re=>z.has(re.annotationId))||(H=H.map((re,w)=>({...re,annotationId:r.annotationIds[w%r.annotationIds.length]})))}let ue=P.fileEdits&&P.fileEdits.length>0?P.fileEdits.map(z=>`${z.tool} ${z.file_path.split("/").pop()}`):P.toolsUsed,le=I.getBufferedEvents(r.id),ce=le?gr(le.events):void 0;if(r.threadId&&await f.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P.text,resolutions:H.length>0?H:void 0,question:_??void 0,sessionId:P.sessionId,toolsUsed:ue,editEvents:P.editEvents&&P.editEvents.length>0?P.editEvents:void 0,segments:ce&&ce.length>0?ce:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&G.captureGitDiff(t).then(async z=>{let V=Date.now(),re=r.imagePaths?Object.values(r.imagePaths).flat():[],w=[];if(r.imagePaths)for(let[U,Y]of Object.entries(r.imagePaths))for(let ae=0;ae<Y.length;ae++)w.push(`screenshots/p-${r.id}-${U}-${ae}.webp`);await G.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:V,durationMs:V-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:w,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:d,model:r.model,sessionId:P.sessionId,threadId:r.threadId,responseText:P.text,resolutions:H.length>0?H:[],question:_??void 0,fileEdits:P.fileEdits??[],editEvents:P.editEvents??[],toolsUsed:ue,gitDiff:z},r.screenshotPath,re),te&&d!=="copilot"?await It({provider:d,model:r.model,threadId:r.threadId,annotationIds:r.annotationIds,sourceId:r.sourceId,reason:`Materialize model \u2014 ${r.feedback.annotations[0]?.instruction??"pattern decision"}`}):te&&console.log(`${R} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&P.text){let z=Xe(P.text);if(z){Array.isArray(z.rules)&&(z.rules=_e(z.rules));let V=await v.loadModel();V&&(!z.tokens&&V.tokens&&(z.tokens=V.tokens),!z.components&&V.components&&(z.components=V.components)),await v.writeModel(z),console.log(`${R} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&P.text){let z=Ht(P.text),V=Gt(P.text),re=z??V;if(re&&re.length>0){let w=await A.writeSynthesized(re),U=r._proposalId;U&&await v.attachGeneratedEvals(U,re.map(Y=>Y.id)),console.log(`${R} Eval synthesis: wrote ${re.length} ${z?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${w.cases.length} total)`)}}else if(r.kind==="run_eval"&&P.text&&r.evalId&&r.evalRunId){let z=await A.findCase(r.evalId),V=r._evalRunScope;if(z&&V){let re=qt(P.text,z.assertions),w=Date.now();await A.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:w,durationMs:w-r.createdAt,scope:V,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:_n(t),rawResponse:P.text,...re}),console.log(`${R} Eval run: ${z.title} \u2192 ${re.status}`)}}_&&(console.log(`${R} \u{1F4AC} Question detected: "${_.slice(0,120)}" \u2192 broadcasting to ${M.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),I.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:_,annotationIds:r.annotationIds},r.id,r.sourceId));let pe=Sn(P.text);pe.length>0&&(console.log(`${R} Novel pattern(s): ${pe.map(z=>`${z.category}/${z.element}`).join(", ")}`),I.broadcast({type:"novel_patterns",jobId:r.id,patterns:pe,threadId:r.threadId},r.id,r.sourceId)),I.broadcast({type:"done",jobId:r.id,success:!0,resolutions:H.length>0?H:void 0,responseText:P.text,threadId:r.threadId},r.id,r.sourceId),T.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${R} Error: ${P.error}`),r.status="error",r.error=P.error,r.threadId&&await f.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:P.error||"Unknown error",model:r.model,provider:d}),I.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:P.error||"Unknown error",provider:d,model:r.model,recoverable:P.recoverableError,code:P.errorCode},r.id,r.sourceId),T.push({id:r.id,status:"error",completedAt:Date.now(),error:P.error,threadId:r.threadId,annotationIds:r.annotationIds});ie()});let lt=lr(async(r,c)=>{if(wr(r,c),r.method==="OPTIONS"){c.writeHead(204),c.end();return}let u=r.url||"/",p=u.split("?")[0],h=new URL(u,`http://127.0.0.1:${B}`),d=h.pathname,x=Sr(r,h);if(x&&x!==o){y(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:x,projectName:rt(t)});return}if(r.headers.origin){if(!Dn(r.headers.origin)){y(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(x!==o){y(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:x,projectName:rt(t)});return}}try{if(r.method==="POST"&&d==="/send")await Un(r,c);else if(r.method==="GET"&&d==="/events")Wn(r,c);else if(r.method==="GET"&&d==="/status")await Hn(c,x);else if(r.method==="PATCH"&&d==="/config")await Gn(r,c);else if(r.method==="POST"&&d==="/shutdown"){if(q!=="detached"){y(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:q});return}y(c,200,{ok:!0}),setTimeout(()=>process.exit(0),100)}else if(r.method==="POST"&&d==="/restart"){if(q!=="detached"){y(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:q});return}y(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let g of M)try{g.res.end()}catch{}lt.close(()=>{Tn(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(r.method==="GET"&&d==="/capabilities")y(c,200,{providers:S});else if(r.method==="POST"&&d==="/mcp/install")await os(r,c);else if(r.method==="POST"&&d==="/reply")await Ln(r,c);else if(r.method==="POST"&&d==="/cancel")qn(r,c);else if(r.method==="POST"&&d==="/materialize")await Qn(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let g=await v.loadRuns();y(c,200,g)}else if(r.method==="GET"&&d==="/model/proposals"){let g=await v.loadModelProposals();y(c,200,g)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply-selected")){let g=d.slice(17,-15);await Yn(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let g=d.slice(17,-6);await Xn(g,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let g=d.slice(17,-8);await Kn(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let g=d.slice(17,-14);await Vn(g,r,c)}else if(r.method==="POST"&&d==="/model/component")await rs(r,c);else if(r.method==="DELETE"&&d==="/model/component")await is(r,c);else if(r.method==="PATCH"&&d==="/model/token")await as(r,c);else if(r.method==="DELETE"&&d==="/model/token")await ls(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:g,model:R}=await Me(r);if(g==="copilot"){y(c,400,{error:"Model consolidation is not available for Copilot yet."});return}v.consolidate({provider:g,model:R}).catch(W=>console.error("[Bridge] Consolidation error:",W)),y(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await Zn(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await es(r,c);else if(r.method==="GET"&&d==="/evals"){let g=await A.loadSuiteWithCurrentRuns(_n(t));y(c,200,g)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let g=d.slice(7,-4);await ts(g,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await ns(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let g=await v.loadModel();y(c,200,{model:g})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let g=d.slice(6,d.length-7),R=parseInt(h.searchParams.get("afterSeq")??"-1",10),W=I.getBufferedEvents(g,isNaN(R)?-1:R);W?y(c,200,W):y(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&p.startsWith("/files/"))await ps(p.slice(7),c);else if(r.method==="GET"&&d==="/threads/recent"){let g=Math.min(Math.max(parseInt(h.searchParams.get("limit")??"5",10)||5,1),20),R=await f.listRecent(g);y(c,200,R)}else if(r.method==="GET"&&d.startsWith("/thread/")){let g=d.slice(8);await hs(g,c)}else if(r.method==="DELETE"&&d.startsWith("/thread/")){let g=d.slice(8);await fs(g,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?cs(r,c):r.method==="GET"&&d==="/canvas/manifest"?await ds(c):r.method==="GET"&&d==="/canvas/app.mjs"?await us(c):y(c,404,{error:"Not found"})}catch(g){console.error("[Bridge] Request error:",g),y(c,500,{error:g instanceof Error?g.message:"Internal error"})}});async function Un(r,c){let{screenshot:u,feedback:p,color:h,provider:d,model:x,sourceId:g,pastedImages:R,pageScreenshots:W}=await Ze(r),J;try{J=JSON.parse(p)}catch{y(c,400,{error:"Invalid feedback JSON"});return}let F=we().slice(0,8),Q={};if(W.length>0)for(let w of W){let U=encodeURIComponent(w.pathname),Y=me(a,`screenshot-${F}-${U}.webp`);await Be(Y,w.data),Q[w.pathname]=Y}let P=me(a,`screenshot-${F}.webp`);await Be(P,u);let _={};if(R.length>0)for(let w of R){let U=me(a,`pasted-${F}-${w.annotationId}-${w.index}.webp`);await Be(U,w.data),_[w.annotationId]||(_[w.annotationId]=[]),_[w.annotationId].push(U)}let H=J.annotations.map(w=>w.linkedSelector?w.pathname?`${w.pathname}:${w.linkedSelector}`:w.linkedSelector:null).filter(w=>!!w),te;if(H.length>0){let w=await f.findContinuationThread(H);w?(te=w.id,await f.addElementIdentifiers(te,H)):te=(await f.createThread(F,H)).id}else te=(await f.createThread(F,[])).id;let ue=J.annotations.map(w=>w.id),le=Object.keys(Q).length>0,ce={id:F,status:"queued",screenshotPath:P,feedback:J,createdAt:Date.now(),color:h,threadId:te,annotationIds:ue,provider:Ie(d),model:x||void 0,...Object.keys(_).length>0?{imagePaths:_}:{},sourceId:g||void 0,...le?{screenshotPaths:Q}:{}},pe=new Set(J.annotations.map(w=>w.pathname).filter(Boolean)),z;if(pe.size>1){let w=new Map;for(let U of J.annotations){let Y=U.pathname||"(unknown)";w.has(Y)||w.set(Y,[]),w.get(Y).push(U.instruction||$n({...J,annotations:[U]}))}z=[...w.entries()].map(([U,Y])=>`\`${U}\`
|
|
406
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let _=!p&&r.threadId?await f.getThreadHistory(r.threadId):void 0,H=p?null:await y.loadModel();S=p??yn(r.screenshotPath,r.feedback,{threadHistory:_&&_.length>0?_:void 0,provider:d,imagePaths:r.imagePaths,designModel:H??void 0,screenshotPaths:r.screenshotPaths})}let E=br(r.color,`[\u22B9 ${j}:${r.id}]`),k=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${E} Reviewing ${k} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${b?` (resuming: ${b.slice(0,8)})`:""}`);let A=(_,H)=>{_.type==="delta"&&"text"in _?I.accumulateText(H,"response",_.text):_.type==="thinking"&&"text"in _&&I.accumulateText(H,"thinking",_.text),I.broadcast(_,H,r.sourceId)},{process:N,result:X}=d==="codex"?Le(r.id,{prompt:S,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:b,model:r.model,onEvent:A}):d==="copilot"?Ft(r.id,{prompt:S,projectRoot:t,resumeSessionId:b,model:r.model,timeoutMs:J,copilotPath:w.copilot?.path??T,onEvent:A}):je(r.id,{prompt:S,projectRoot:t,maxTurns:a,maxBudgetUsd:m,allowedTools:M,claudePath:x,resumeSessionId:b,model:r.model,timeoutMs:J,onEvent:A});I.setActiveProcess(r.id,N);let P=await X;if(r.result=P.text,P.success){console.log(`${E} Iteration complete`),P.fileEdits&&P.fileEdits.length>0&&console.log(`${E} Captured ${P.fileEdits.length} file edit(s): ${P.fileEdits.map(F=>`${F.tool} ${F.file_path}`).join(", ")}`),P.editEvents&&P.editEvents.length>0&&console.log(`${E} Captured ${P.editEvents.length} edit event(s): ${P.editEvents.map(F=>`${F.operation} ${F.filePath}`).join(", ")}`),r.status="done";let _=vn(P.text),H=wn(P.text),te=H.some(F=>(F.finalScope??F.inferredScope)?.breadth==="pattern");if(H.length>0&&r.annotationIds&&r.annotationIds.length>0){let F=new Set(r.annotationIds);H.every(re=>F.has(re.annotationId))||(H=H.map((re,v)=>({...re,annotationId:r.annotationIds[v%r.annotationIds.length]})))}let ue=P.fileEdits&&P.fileEdits.length>0?P.fileEdits.map(F=>`${F.tool} ${F.file_path.split("/").pop()}`):P.toolsUsed,le=I.getBufferedEvents(r.id),ce=le?gr(le.events):void 0;if(r.threadId&&await f.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P.text,resolutions:H.length>0?H:void 0,question:_??void 0,sessionId:P.sessionId,toolsUsed:ue,editEvents:P.editEvents&&P.editEvents.length>0?P.editEvents:void 0,segments:ce&&ce.length>0?ce:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&G.captureGitDiff(t).then(async F=>{let K=Date.now(),re=r.imagePaths?Object.values(r.imagePaths).flat():[],v=[];if(r.imagePaths)for(let[L,Y]of Object.entries(r.imagePaths))for(let ae=0;ae<Y.length;ae++)v.push(`screenshots/p-${r.id}-${L}-${ae}.webp`);await G.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:K,durationMs:K-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:v,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:d,model:r.model,sessionId:P.sessionId,threadId:r.threadId,responseText:P.text,resolutions:H.length>0?H:[],question:_??void 0,fileEdits:P.fileEdits??[],editEvents:P.editEvents??[],toolsUsed:ue,gitDiff:F},r.screenshotPath,re),te&&d!=="copilot"?await It({provider:d,model:r.model,threadId:r.threadId,annotationIds:r.annotationIds,sourceId:r.sourceId,reason:`Materialize model \u2014 ${r.feedback.annotations[0]?.instruction??"pattern decision"}`}):te&&console.log(`${E} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&P.text){let F=Xe(P.text);if(F){Array.isArray(F.rules)&&(F.rules=_e(F.rules));let K=await y.loadModel();K&&(!F.tokens&&K.tokens&&(F.tokens=K.tokens),!F.components&&K.components&&(F.components=K.components)),await y.writeModel(F),console.log(`${E} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&P.text){let F=Ht(P.text),K=Gt(P.text),re=F??K;if(re&&re.length>0){let v=await O.writeSynthesized(re),L=r._proposalId;L&&await y.attachGeneratedEvals(L,re.map(Y=>Y.id)),console.log(`${E} Eval synthesis: wrote ${re.length} ${F?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${v.cases.length} total)`)}}else if(r.kind==="run_eval"&&P.text&&r.evalId&&r.evalRunId){let F=await O.findCase(r.evalId),K=r._evalRunScope;if(F&&K){let re=qt(P.text,F.assertions),v=Date.now();await O.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:v,durationMs:v-r.createdAt,scope:K,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:_n(t),rawResponse:P.text,...re}),console.log(`${E} Eval run: ${F.title} \u2192 ${re.status}`)}}_&&(console.log(`${E} \u{1F4AC} Question detected: "${_.slice(0,120)}" \u2192 broadcasting to ${R.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),I.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:_,annotationIds:r.annotationIds},r.id,r.sourceId));let pe=Sn(P.text);pe.length>0&&(console.log(`${E} Novel pattern(s): ${pe.map(F=>`${F.category}/${F.element}`).join(", ")}`),I.broadcast({type:"novel_patterns",jobId:r.id,patterns:pe,threadId:r.threadId},r.id,r.sourceId)),I.broadcast({type:"done",jobId:r.id,success:!0,resolutions:H.length>0?H:void 0,responseText:P.text,threadId:r.threadId},r.id,r.sourceId),C.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${E} Error: ${P.error}`),r.status="error",r.error=P.error,r.threadId&&await f.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:P.error||"Unknown error",model:r.model,provider:d}),I.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:P.error||"Unknown error",provider:d,model:r.model,recoverable:P.recoverableError,code:P.errorCode},r.id,r.sourceId),C.push({id:r.id,status:"error",completedAt:Date.now(),error:P.error,threadId:r.threadId,annotationIds:r.annotationIds});ie()});let lt=lr(async(r,c)=>{if(wr(r,c),r.method==="OPTIONS"){c.writeHead(204),c.end();return}let p=r.url||"/",u=p.split("?")[0],h=new URL(p,`http://127.0.0.1:${j}`),d=h.pathname,b=Sr(r,h);if(b&&b!==o){g(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:b,projectName:rt(t)});return}if(r.headers.origin){if(!Dn(r.headers.origin)){g(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(b!==o){g(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:b,projectName:rt(t)});return}}try{if(r.method==="POST"&&d==="/send")await Un(r,c);else if(r.method==="GET"&&d==="/events")Wn(r,c);else if(r.method==="GET"&&d==="/status")await Hn(c,b);else if(r.method==="PATCH"&&d==="/config")await Gn(r,c);else if(r.method==="POST"&&d==="/shutdown"){if(q!=="detached"){g(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:q});return}g(c,200,{ok:!0}),setTimeout(()=>process.exit(0),100)}else if(r.method==="POST"&&d==="/restart"){if(q!=="detached"){g(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:q});return}g(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let S of R)try{S.res.end()}catch{}lt.close(()=>{Tn(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(r.method==="GET"&&d==="/capabilities")g(c,200,{providers:w});else if(r.method==="POST"&&d==="/mcp/install")await os(r,c);else if(r.method==="POST"&&d==="/reply")await Ln(r,c);else if(r.method==="POST"&&d==="/cancel")qn(r,c);else if(r.method==="POST"&&d==="/materialize")await Qn(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let S=await y.loadRuns();g(c,200,S)}else if(r.method==="GET"&&d==="/model/proposals"){let S=await y.loadModelProposals();g(c,200,S)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply-selected")){let S=d.slice(17,-15);await Yn(S,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let S=d.slice(17,-6);await Xn(S,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let S=d.slice(17,-8);await Vn(S,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let S=d.slice(17,-14);await Kn(S,r,c)}else if(r.method==="POST"&&d==="/model/component")await rs(r,c);else if(r.method==="DELETE"&&d==="/model/component")await is(r,c);else if(r.method==="PATCH"&&d==="/model/token")await as(r,c);else if(r.method==="DELETE"&&d==="/model/token")await ls(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:S,model:E}=await Me(r);if(S==="copilot"){g(c,400,{error:"Model consolidation is not available for Copilot yet."});return}y.consolidate({provider:S,model:E}).catch(k=>console.error("[Bridge] Consolidation error:",k)),g(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await Zn(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await es(r,c);else if(r.method==="GET"&&d==="/evals"){let S=await O.loadSuiteWithCurrentRuns(_n(t));g(c,200,S)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let S=d.slice(7,-4);await ts(S,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await ns(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let S=await y.loadModel();g(c,200,{model:S})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let S=d.slice(6,d.length-7),E=parseInt(h.searchParams.get("afterSeq")??"-1",10),k=I.getBufferedEvents(S,isNaN(E)?-1:E);k?g(c,200,k):g(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&u.startsWith("/files/"))await ps(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),E=await f.listRecent(S);g(c,200,E)}else if(r.method==="GET"&&d.startsWith("/thread/")){let S=d.slice(8);await hs(S,c)}else if(r.method==="DELETE"&&d.startsWith("/thread/")){let S=d.slice(8);await fs(S,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?cs(r,c):r.method==="GET"&&d==="/canvas/manifest"?await ds(c):r.method==="GET"&&d==="/canvas/app.mjs"?await us(c):g(c,404,{error:"Not found"})}catch(S){console.error("[Bridge] Request error:",S),g(c,500,{error:S instanceof Error?S.message:"Internal error"})}});async function Un(r,c){let{screenshot:p,feedback:u,color:h,provider:d,model:b,sourceId:S,pastedImages:E,pageScreenshots:k}=await Ze(r),A;try{A=JSON.parse(u)}catch{g(c,400,{error:"Invalid feedback JSON"});return}let N=we().slice(0,8),X={};if(k.length>0)for(let v of k){let L=encodeURIComponent(v.pathname),Y=me(l,`screenshot-${N}-${L}.webp`);await Be(Y,v.data),X[v.pathname]=Y}let P=me(l,`screenshot-${N}.webp`);await Be(P,p);let _={};if(E.length>0)for(let v of E){let L=me(l,`pasted-${N}-${v.annotationId}-${v.index}.webp`);await Be(L,v.data),_[v.annotationId]||(_[v.annotationId]=[]),_[v.annotationId].push(L)}let H=A.annotations.map(v=>v.linkedSelector?v.pathname?`${v.pathname}:${v.linkedSelector}`:v.linkedSelector:null).filter(v=>!!v),te;if(H.length>0){let v=await f.findContinuationThread(H);v?(te=v.id,await f.addElementIdentifiers(te,H)):te=(await f.createThread(N,H)).id}else te=(await f.createThread(N,[])).id;let ue=A.annotations.map(v=>v.id),le=Object.keys(X).length>0,ce={id:N,status:"queued",screenshotPath:P,feedback:A,createdAt:Date.now(),color:h,threadId:te,annotationIds:ue,provider:Ie(d),model:b||void 0,...Object.keys(_).length>0?{imagePaths:_}:{},sourceId:S||void 0,...le?{screenshotPaths:X}:{}},pe=new Set(A.annotations.map(v=>v.pathname).filter(Boolean)),F;if(pe.size>1){let v=new Map;for(let L of A.annotations){let Y=L.pathname||"(unknown)";v.has(Y)||v.set(Y,[]),v.get(Y).push(L.instruction||$n({...A,annotations:[L]}))}F=[...v.entries()].map(([L,Y])=>`\`${L}\`
|
|
407
407
|
${Y.map(ae=>`- ${ae}`).join(`
|
|
408
408
|
`)}`).join(`
|
|
409
|
-
`)}else
|
|
409
|
+
`)}else F=$n(A);let K=De(A,Object.keys(_).length>0?_:void 0);await f.appendMessage(te,{role:"human",timestamp:Date.now(),jobId:N,screenshotPath:P,...le?{screenshotPaths:X}:{},...Object.keys(_).length>0?{imagePaths:_}:{},annotationIds:ue,feedbackSummary:F,feedbackContext:K||void 0});let re=I.enqueue(ce);g(c,200,{jobId:N,position:re,threadId:te})}async function Ln(r,c){let p=r.headers["content-type"]||"",u,h,d,b,S,E,k=[];if(p.includes("multipart/form-data")){let v=await Ze(r),L=v.feedback?JSON.parse(v.feedback):{};u=L.threadId,h=L.reply,d=L.color,b=L.provider,S=L.model,E=L.sourceId||v.sourceId;for(let Y of v.pastedImages)k.push(Y.data)}else{let v=[];for await(let ae of r)v.push(typeof ae=="string"?Buffer.from(ae):ae);let L=Buffer.concat(v).toString("utf-8"),Y;try{Y=JSON.parse(L)}catch{g(c,400,{error:"Invalid JSON"});return}u=Y.threadId,h=Y.reply,d=Y.color,b=Y.provider,S=Y.model,E=Y.sourceId}if(!u||!h){g(c,400,{error:"Missing threadId or reply"});return}if(!await f.getThread(u)){g(c,404,{error:"Thread not found"});return}let N="";{let v=await f.getThreadHistory(u);for(let L=v.length-1;L>=0;L--)if(v[L].screenshotPath){N=v[L].screenshotPath;break}}let X=await ss(u);if(!N&&!X){g(c,400,{error:"No screenshot available"});return}let P=I.hasActiveThread(u),_=P?I.getQueuedThreadJob(u,v=>v._replyText!==void 0||v._replyPrompt!==void 0):null,H=_?.id??we().slice(0,8),te=[],ue=`${H}-${Date.now()}`;for(let v=0;v<k.length;v++){let L=me(l,`reply-${ue}-${v}.webp`);await Be(L,k[v]),te.push(L)}await f.appendMessage(u,{role:"human",timestamp:Date.now(),jobId:H,replyToQuestion:h,screenshotPath:N,...P?{queued:!0}:{},...te.length>0?{replyImagePaths:te}:{}});let le=await f.getThreadHistory(u),ce=[];for(let v of le)if(v.annotationIds)for(let L of v.annotationIds)ce.includes(L)||ce.push(L);let pe=Ie(b),F=xt(N,le,pe,te.length>0?te:void 0);if(_){let v=_,Y=[...v._replyTexts??(v._replyText?[v._replyText]:[]),h],ae=[...v._replyImagePaths??[],...te];v._replyTexts=Y,v._replyText=Cn(Y),v._replyImagePaths=ae.length>0?ae:void 0,v._replyPrompt=xt(N,le,pe,ae.length>0?ae:void 0),v.annotationIds=ce.length>0?ce:v.annotationIds,g(c,200,{jobId:H,position:1,threadId:u,bundled:!0});return}let K={id:H,status:"queued",screenshotPath:N,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:d,threadId:u,annotationIds:ce.length>0?ce:void 0,provider:pe,model:S||void 0,sourceId:E||void 0};X&&(K.kind=X),K._replyPrompt=F,K._replyTexts=[h],K._replyText=Cn([h]),te.length>0&&(K._replyImagePaths=te);let re=P?I.enqueueNext(K):I.enqueue(K);g(c,200,{jobId:H,position:re,threadId:u})}function Wn(r,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
|
|
410
410
|
data: {"status":"connected"}
|
|
411
411
|
|
|
412
|
-
`);let
|
|
412
|
+
`);let u=new URL(r.url||"/",`http://127.0.0.1:${j}`).searchParams.get("sourceId")||void 0,h={id:we().slice(0,8),res:c,sourceId:u};R.add(h),r.on("close",()=>{R.delete(h)})}async function Hn(r,c){let p=[...I.allActive,...D.allActive.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds??[],color:"#000000",kind:"materialize_model",standalone:d.standalone}))],[u,h]=await Promise.all([y.loadRuns(),y.loadModelProposals()]);g(r,200,{ok:!0,version:En,restartMode:q,projectId:o,projectName:rt(t),projectRoot:t,requestProjectId:c,projectIdVerified:c===o,devOrigin:i,activeJob:p[0]?{id:p[0].id,status:p[0].status}:null,activeJobs:p.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds,color:d.color,kind:d.kind,standalone:"standalone"in d?d.standalone:void 0})),queueDepth:I.depth+D.depth,materializerQueueDepth:D.depth,materialization:{activeJob:D.active?{id:D.active.id,status:D.active.status,threadId:D.active.threadId,annotationIds:D.active.annotationIds??[],provider:D.active.provider,model:D.active.model}:null,queueDepth:D.depth,recentRuns:[...u.runs].sort((d,b)=>(b.completedAt??b.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:C})}async function Gn(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),g(c,200,{ok:!0,devOrigin:i})}catch{g(c,400,{error:"Invalid JSON"})}}async function qn(r,c){let u=new URL(r.url||"/",`http://127.0.0.1:${j}`).searchParams.get("jobId"),h=u?I.allActive.filter(A=>A.id===u):I.allActive,d=u?D.allActive.filter(A=>A.id===u):D.allActive,b=[...h.map(A=>A.threadId),...d.map(A=>A.threadId)].filter(Boolean),S=u?I.cancelJob(u):I.cancelActive(),E=u?D.cancelJob(u):D.cancelActive(),k=!!(S||E);for(let A of b)await f.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:u||E?.id||"",cancelled:!0});g(c,200,{cancelled:k})}async function It(r){let c=we().slice(0,8),p=r.threadId,u=!p;p||(p=(await f.createThread(c,[])).id,ee.set(p,"materialize_model")),u&&await f.appendMessage(p,{role:"human",timestamp:Date.now(),jobId:c,feedbackSummary:r.reason}),await f.appendMessage(p,{role:"assistant",timestamp:Date.now(),jobId:c,responseText:u?"Materializing model suggestions...":"Thinking through model suggestions from this decision...",model:r.model,provider:r.provider});let h={id:c,status:"queued",createdAt:Date.now(),provider:r.provider,model:r.model,threadId:p,annotationIds:r.annotationIds,sourceId:r.sourceId,standalone:u},d=D.enqueue(h);return{jobId:c,position:d,threadId:p}}async function Qn(r,c){if(D.isRunning){g(c,200,{skipped:!0,reason:"Already running"});return}let{provider:p,model:u}=await Me(r);if(p==="copilot"){g(c,400,{error:"Materialization is not available for Copilot yet."});return}let h=await y.getUnmaterializedPatternDecisions();if(h.length===0){g(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"});g(c,200,{started:!0,decisionCount:h.length,decisionIds:h.map(b=>b.id),...d})}async function Xn(r,c){let p=decodeURIComponent(r),u=await y.applyModelProposal(p);if(!u){g(c,404,{error:"Model proposal not found"});return}u.threadId&&await f.appendMessage(u.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${u.id}`,responseText:`Model proposal applied.
|
|
413
413
|
|
|
414
|
-
${
|
|
415
|
-
${
|
|
414
|
+
${u.title}
|
|
415
|
+
${u.summary}`}),g(c,200,{proposal:u})}async function Yn(r,c,p){let u=decodeURIComponent(r),h=[];for await(let k of c)h.push(typeof k=="string"?Buffer.from(k):k);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{g(p,400,{error:"Invalid JSON"});return}let b=(d.changes??[]).flatMap(k=>{if(!Array.isArray(k.path)||k.path.length===0)return[];let A=k.path.filter(N=>typeof N=="string"||typeof N=="number");return A.length!==k.path.length?[]:[{path:A,value:k.value,remove:k.remove===!0}]});if(b.length===0){g(p,400,{error:"No selected model changes"});return}let S=(d.changeSummaries??[]).flatMap(k=>{if(!k||typeof k!="object")return[];let A=Array.isArray(k.path)?k.path.filter(N=>typeof N=="string"||typeof N=="number"):void 0;return Array.isArray(k.path)&&A?.length!==k.path.length?[]:[{group:typeof k.group=="string"?k.group:void 0,label:typeof k.label=="string"?k.label:void 0,detail:typeof k.detail=="string"?k.detail:void 0,path:A,value:k.value,currentValue:k.currentValue}]}),E=await y.applySelectedModelProposal(u,b,S);if(!E){g(p,404,{error:"Model proposal not found"});return}if(E.threadId){let k=Ie(d.provider),A=typeof d.model=="string"&&d.model?d.model:void 0;await f.appendMessage(E.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${E.id}`,responseText:`Model proposal applied with ${b.length} selected change${b.length===1?"":"s"}.
|
|
416
416
|
|
|
417
|
-
${
|
|
417
|
+
${E.title}`,provider:k,model:A})}g(p,200,{proposal:E})}async function Vn(r,c,p){let u=decodeURIComponent(r),{provider:h,model:d}=await Me(c),b=await y.dismissModelProposal(u);if(!b){g(p,404,{error:"Model proposal not found"});return}b.threadId&&await f.appendMessage(b.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${b.id}`,responseText:`Model proposal dismissed.
|
|
418
418
|
|
|
419
|
-
${
|
|
420
|
-
`)});let P={id:
|
|
421
|
-
`)});let Y={id:P,status:"queued",screenshotPath:_,feedback:
|
|
422
|
-
`)}async function jn(){try{await kr(Fn)}catch{}}async function
|
|
419
|
+
${b.title}`,provider:h,model:d}),g(p,200,{proposal:b})}async function Kn(r,c,p){let u=decodeURIComponent(r),h=await y.findModelProposal(u);if(!h){g(p,404,{error:"Model proposal not found"});return}if(h.status!=="applied"){g(p,400,{error:"Only applied model proposals can be projected into evals"});return}let{provider:d,model:b}=await Me(c),S=d??h.provider??z;if(S==="copilot"){g(p,400,{error:"Eval projection is not available for Copilot yet."});return}let E=await y.loadModel(),k=await O.loadSuite(),A=Vt({proposal:h,currentModel:E,existingSuite:k}),N=we().slice(0,8),X=h.threadId??(await f.createThread(N,[])).id;ee.set(X,"synthesize_evals"),await f.appendMessage(X,{role:"human",timestamp:Date.now(),jobId:N,feedbackSummary:`Create eval drafts \u2014 ${h.title}`,feedbackContext:[`Model proposal: ${h.title}`,`Sources: ${h.decisionIds.length} decisions`,"Projection target: pending eval proposals"].join(`
|
|
420
|
+
`)});let P={id:N,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:X,kind:"synthesize_evals",provider:S,model:b??h.model};P._replyPrompt=A,P._proposalId=h.id;let _=I.enqueue(P);g(p,200,{jobId:N,position:_,threadId:X})}async function Me(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:Ie(typeof p.provider=="string"?p.provider:void 0),model:typeof p.model=="string"&&p.model?p.model:void 0}}catch{return{}}}async function Zn(r,c){let p=await y.loadModel();if(!p){g(c,400,{error:"No model exists yet"});return}let u,h;try{let N=[];for await(let P of r)N.push(typeof P=="string"?Buffer.from(P):P);let X=JSON.parse(Buffer.concat(N).toString());u=X.provider,h=X.model}catch{}if(u==="copilot"){g(c,400,{error:"Rule synthesis is not available for Copilot yet."});return}let d=nn(p),b=we().slice(0,8),E=(await f.createThread(b,[])).id;ee.set(E,"synthesize"),await f.appendMessage(E,{role:"human",timestamp:Date.now(),jobId:b,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let k={id:b,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:E,kind:"synthesize",provider:Ie(u),model:h||void 0};k._replyPrompt=d;let A=I.enqueue(k);g(c,200,{jobId:b,position:A,threadId:E})}async function es(r,c){let{provider:p,model:u}=await Me(r);if(p==="copilot"){g(c,400,{error:"Eval synthesis is not available for Copilot yet."});return}let h=await G.listDecisionIds(),d=await G.loadDecisions(h),b=await f.load(),S=await y.loadModel(),E=await O.loadSuite(),k=Xt({decisions:d,threads:b,model:S,existingSuite:E}),A=we().slice(0,8),X=(await f.createThread(A,[])).id;ee.set(X,"synthesize_evals"),await f.appendMessage(X,{role:"human",timestamp:Date.now(),jobId:A,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let P={id:A,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:X,kind:"synthesize_evals",provider:p,model:u||void 0};P._replyPrompt=k;let _=I.enqueue(P);g(c,200,{jobId:A,position:_,threadId:X})}async function ts(r,c,p){let u=decodeURIComponent(r),h=await O.findCase(u);if(!h){g(p,404,{error:"Eval not found"});return}if(h.status!=="approved"){g(p,400,{error:"Only approved evals can be run"});return}let{screenshot:d,feedback:b,provider:S,model:E,sourceId:k}=await Ze(c),A=Ie(S)??z;if(A==="copilot"){g(p,400,{error:"Eval runs are not available for Copilot yet."});return}let N={};try{N=b?JSON.parse(b):{}}catch{g(p,400,{error:"Invalid eval run context JSON"});return}let X=we().slice(0,8),P=we().slice(0,8),_=me(l,`eval-run-${X}.webp`);await Be(_,d);let H=await O.writeRunScreenshot(X,d),te=N.viewport,ue=te&&typeof te=="object"?te:{},le={type:"current_page",url:typeof N.url=="string"?N.url:"",viewport:{width:typeof ue.width=="number"?ue.width:0,height:typeof ue.height=="number"?ue.height:0}},ce=await y.loadModel(),pe=A==="claude"?W.name:A==="codex"?Q.name:null,F=A==="codex"?Z.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),K=Yt({evalCase:h,scope:le,model:ce,screenshotPath:_,chromeDevtoolsAvailable:F}),v=(await f.createThread(P,[])).id;ee.set(v,"run_eval");let L={timestamp:new Date().toISOString(),url:le.url,viewport:le.viewport,scrollPosition:{x:typeof N.scrollX=="number"?N.scrollX:0,y:typeof N.scrollY=="number"?N.scrollY:0},annotations:[],styleModifications:[]};await f.appendMessage(v,{role:"human",timestamp:Date.now(),jobId:P,screenshotPath:_,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${le.url||"unknown"}`,"Assertions:",...h.assertions.map(gs=>`- ${gs}`)].join(`
|
|
421
|
+
`)});let Y={id:P,status:"queued",screenshotPath:_,feedback:L,createdAt:Date.now(),color:"#111827",threadId:v,kind:"run_eval",evalId:u,evalRunId:X,provider:A,model:E||void 0,sourceId:k||void 0};Y._replyPrompt=K,Y._evalRunScope=le,Y._evalScreenshotPath=H;let ae=I.enqueue(Y);g(p,200,{jobId:P,runId:X,position:ae,threadId:v,screenshotPath:H})}async function ns(r,c,p){let u=decodeURIComponent(r),h={},d,b,S;try{let k=[];for await(let N of c)k.push(typeof N=="string"?Buffer.from(N):N);let A=JSON.parse(Buffer.concat(k).toString());d=A.status,b=A.title,S=A.assertions}catch{g(p,400,{error:"Invalid JSON"});return}if(d!==void 0&&d!=="pending"&&d!=="approved"&&d!=="rejected"){g(p,400,{error:"Invalid status"});return}if(d&&(h.status=d),b!==void 0){if(typeof b!="string"||b.trim().length===0){g(p,400,{error:"Invalid title"});return}h.title=b.trim()}if(S!==void 0){if(!Array.isArray(S)){g(p,400,{error:"Invalid assertions"});return}let k=S.filter(A=>typeof A=="string").map(A=>A.trim()).filter(Boolean);if(k.length===0){g(p,400,{error:"Invalid assertions"});return}h.assertions=k}if(!h.status&&!h.title&&!h.assertions){g(p,400,{error:"No eval changes provided"});return}let E=await O.updateCase(u,h);if(!E){g(p,404,{error:"Eval not found"});return}g(p,200,{eval:E})}async function ss(r){let c=ee.get(r);if(c)return c;let h=(await f.getThread(r))?.messages.find(d=>d.role==="human")?.feedbackSummary??"";if(h.startsWith("Synthesize evals"))return ee.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return ee.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return ee.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return ee.set(r,"materialize_model"),"materialize_model"}async function os(r,c){let p=[];for await(let E of r)p.push(typeof E=="string"?Buffer.from(E):E);let u;if(p.length>0)try{u=JSON.parse(Buffer.concat(p).toString("utf-8")).serverUrl}catch{}let h=[];w.claude?.available&&w.claude.mcp&&!w.claude.mcp.found&&h.push(await fn(u)),w.codex?.available&&w.codex.mcp&&!w.codex.mcp.found&&h.push(await mn(u)),w.copilot?.available&&w.copilot.mcp&&!w.copilot.mcp.found&&h.push(await gn(u,w.copilot.path??T));let[d,b,S]=await Promise.all([yt(t),vt(t),wt(t,w.copilot?.path??T)]);w.claude&&(w.claude.mcp=d),w.codex&&(w.codex.mcp=b),w.copilot&&(w.copilot.mcp=S),g(c,200,{results:h,capabilities:{providers:w}})}async function rs(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{g(c,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){g(c,400,{error:"Missing or invalid name"});return}let h=await y.addComponent(u.name);g(c,200,h)}async function is(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{g(c,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){g(c,400,{error:"Missing or invalid name"});return}let h=await y.removeComponent(u.name);g(c,200,h)}async function as(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{g(c,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"||typeof u.value!="string"){g(c,400,{error:"Missing or invalid path/value"});return}let h=await y.updateToken(u.path,u.value);g(c,200,h)}async function ls(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{g(c,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"){g(c,400,{error:"Missing or invalid path"});return}let h=await y.removeToken(u.path);g(c,200,h)}function cs(r,c){let p=i??"http://localhost:3000";if(!i){let h=r.headers.referer||r.headers.origin;if(h)try{let d=new URL(typeof h=="string"?h:h[0]||"");(d.hostname==="localhost"||d.hostname==="127.0.0.1")&&(p=d.origin)}catch{}}let u=Rt(j,p);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(u)}async function ds(r){let c=Date.now();if(oe&&c<oe.expires){g(r,200,oe.data);return}try{let{scanForComponents:p}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:u}=await import("./render-generator-HWFLZYC3.mjs"),h=await p(t);oe={data:h,expires:c+5e3},u(h,t,ke).then(d=>{ke=d}).catch(d=>console.warn("[Bridge] Render generation failed:",d)),g(r,200,h)}catch(p){console.error("[Bridge] Scanner error:",p),g(r,500,{error:"Failed to scan components"})}}async function us(r){let c=[me(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),me(t,"packages","popmelt","dist","canvas.mjs")];try{let p=ur(import.meta.url);c.unshift(me(dr(p),"canvas.mjs"))}catch{}for(let p of c)try{let u=await An(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),g(r,404,{error:"Canvas bundle not found"})}async function ps(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){g(c,400,{error:"Invalid filename"});return}try{let p=await An(me(l,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{g(c,404,{error:"File not found"})}}function Fe(r){return`/files/${rt(r)}`}async function hs(r,c){let p=await f.getThread(r);if(!p){g(c,404,{error:"Thread not found"});return}let u=(await O.loadRuns()).runs.filter(E=>E.threadId===r).sort((E,k)=>k.completedAt-E.completedAt)[0],h=u?await O.findCase(u.evalId):null,d=await y.findModelProposalsByThread(r),b=[...d].sort((E,k)=>k.updatedAt-E.updatedAt)[0]??null,S=p.messages.map(({screenshotPath:E,screenshotPaths:k,imagePaths:A,replyImagePaths:N,...X})=>({...X,...X.role==="assistant"&&u?{evalRun:{...u,title:h?.title}}:{},...E?{screenshotUrl:Fe(E)}:{},...k?{screenshotUrls:Object.fromEntries(Object.entries(k).map(([P,_])=>[P,Fe(_)]))}:{},...A?{imageUrls:Object.fromEntries(Object.entries(A).map(([P,_])=>[P,_.map(Fe)]))}:{},...N?{replyImageUrls:N.map(Fe)}:{}}));g(c,200,{id:p.id,createdAt:p.createdAt,messages:S,modelProposal:b,modelProposals:d})}async function fs(r,c){let p=decodeURIComponent(r);if(!await f.deleteThread(p)){g(c,404,{deleted:!1,error:"Thread not found"});return}g(c,200,{deleted:!0})}let kt=9,Mt=!1;for(let r=e;r<e+kt;r++)try{await Pr(lt,r),j=r,Mt=!0,console.log(`[\u22B9 is watching :${j}]`);break}catch(c){if(c.code==="EADDRINUSE"){let p=await xr(r);if(p&&p.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!Mt)throw new Error(`[Bridge] All ports ${e}\u2013${e+kt-1} in use`);for(let[r,c]of Object.entries(w))!c.available||!c.path||V(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 R)it(u,{type:"capabilities_changed",data:{}})}});let ms=setInterval(()=>{On(l).catch(()=>{})},fr);return{port:j,projectId:o,close:async()=>{clearInterval(ms),await I.destroyAsync();for(let r of R)try{r.res.end()}catch{}return R.clear(),new Promise(r=>{lt.close(()=>r())})}}}async function On(s){try{let e=await or(s),n=Date.now();for(let t of e){let o=me(s,t);try{let i=await ir(o);n-i.mtimeMs>mr&&await ar(o)}catch{}}}catch{}}var Rr=parseInt(process.env.POPMELT_PORT||"1111",10),zn=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Er=process.env.POPMELT_DEV_ORIGIN||void 0,Tr=process.env.POPMELT_COPILOT_PATH||void 0,Bn=Jn(zn,".popmelt"),Fn=Jn(Bn,"bridge.lock");async function Ar(s){await Ir(Bn,{recursive:!0}),await Mr(Fn,JSON.stringify({pid:process.pid,port:s,startedAt:Date.now()})+`
|
|
422
|
+
`)}async function jn(){try{await kr(Fn)}catch{}}async function Cr(){let s=await Nn({port:Rr,projectRoot:zn,devOrigin:Er,copilotPath:Tr,restartMode:"detached"});await Ar(s.port),await new Promise(e=>{let n=async()=>{await s.close(),await jn(),e()};process.on("SIGTERM",n),process.on("SIGINT",n)})}Cr().catch(s=>{console.error("[popmelt bridge-entry] Fatal:",s),jn().finally(()=>process.exit(1))});
|