@popmelt.com/core 0.8.3 → 0.8.4
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 +52 -52
- package/dist/canvas.mjs +1 -1
- package/dist/chunk-3TS7MVTZ.mjs +1 -0
- package/dist/chunk-RBFQCZQP.mjs +1 -0
- package/dist/cli.mjs +54 -54
- package/dist/dev-server-rQIWJcSX.d.mts +26 -0
- package/dist/index.d.mts +7 -5
- package/dist/index.mjs +27 -27
- package/dist/plugin-astro.d.mts +8 -7
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-next.mjs +1 -1
- package/dist/plugin-vite.d.mts +4 -7
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-7UMGXB6S.mjs +421 -0
- package/dist/server.d.mts +7 -3
- package/dist/server.mjs +53 -53
- package/package.json +18 -5
- package/dist/server-2X6UD5RQ.mjs +0 -421
package/dist/bridge-entry.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdir as
|
|
1
|
+
import{mkdir as Wr,unlink as Hr,writeFile as Gr}from"fs/promises";import{join as Yn}from"path";import{execFileSync as mt,spawn as jn}from"child_process";import{createHash as wr,randomUUID as Pe}from"crypto";import{mkdir as Sr,readFile as Ln,readdir as xr,realpath as br,stat as Pr,unlink as Ir,writeFile as Le}from"fs/promises";import{createServer as kr}from"http";import{tmpdir as Mr}from"os";import{basename as ft,dirname as Rr,join as ye}from"path";import{fileURLToPath as Er}from"url";function zt(s,e){return`<!DOCTYPE html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -25,12 +25,12 @@ import{mkdir as $r,unlink as _r,writeFile as Or}from"fs/promises";import{join as
|
|
|
25
25
|
});
|
|
26
26
|
</script>
|
|
27
27
|
</body>
|
|
28
|
-
</html>`}import{spawn as
|
|
29
|
-
\u2026[truncated]`:t}function
|
|
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
|
|
31
|
-
`)[0].slice(0,80)}`:"Bash";w.push(
|
|
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
|
|
28
|
+
</html>`}var $s=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),_s=new Set(["default","flex","fast","priority"]);function Re(s){let e=typeof s.reasoningEffort=="string"&&$s.has(s.reasoningEffort)?s.reasoningEffort:void 0,n=typeof s.serviceTier=="string"&&_s.has(s.serviceTier)?s.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function qe(s){let e=[];return s?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(s.reasoningEffort)}`),s?.serviceTier&&e.push(`service_tier=${JSON.stringify(s.serviceTier)}`),e}import{spawn as Os}from"child_process";import{createInterface as Ds}from"readline";var Ns=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"]),Bt=1e5;function Js(s){let e=s.input?.file_path||s.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Ns.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>Bt?t.slice(0,Bt)+`
|
|
29
|
+
\u2026[truncated]`:t}function Qe(s,e){let{prompt:n,projectRoot:t,maxTurns:o=40,maxBudgetUsd:i=1,allowedTools:a=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:l="claude",resumeSessionId:f,model:v,reasoningEffort:x,timeoutMs:E=3e5,onEvent:B}=e,J=[];f?J.push("--resume",f,"-p",n):J.push("-p",n),J.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(i)),v&&J.push("--model",v),x&&J.push("--effort",x);for(let w of a)J.push("--allowedTools",w);let U=Os(l,J,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),W=new Promise(w=>{let q,V=[],Q=[],K=[],z=!1,Z="",O,A,k=!1,M=setTimeout(()=>{k=!0,U.kill("SIGTERM"),setTimeout(()=>{try{U.kill("SIGKILL")}catch{}},5e3)},E),N=Ds({input:U.stdout}),$=new Set;N.on("line",L=>{if(L.trim())try{let _=JSON.parse(L);_.session_id&&!q&&(q=_.session_id);let ee=_.type??(_.event?.type?`event.${_.event.type}`:"unknown");if($.add(ee),_.type==="result"&&_.result&&V.length===0){let y=typeof _.result=="string"?_.result:"";y&&(V.push(y),B?.({type:"delta",jobId:s,text:y},s))}if(_.type==="assistant"&&Array.isArray(_.message?.content)){typeof _.error=="string"&&(O=_.error);for(let y of _.message.content){if(y.type==="text"&&y.text&&(V.push(y.text),B?.({type:"delta",jobId:s,text:y.text},s)),y.type==="tool_use"&&y.name){let le=y.input?.file_path||y.input?.path||void 0,ie=Js(y);if(B?.({type:"tool_use",jobId:s,tool:y.name,...le?{file:le}:{},...ie?{content:ie}:{}},s),y.name==="Edit"&&y.input?.file_path){let G={tool:"Edit",file_path:y.input.file_path,old_string:y.input.old_string,new_string:y.input.new_string,replace_all:y.input.replace_all};Q.push(G),K.push({sequence:K.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:G.file_path,oldString:typeof G.old_string=="string"?G.old_string:void 0,newString:typeof G.new_string=="string"?G.new_string:void 0,replaceAll:typeof G.replace_all=="boolean"?G.replace_all:void 0})}else y.name==="Write"&&y.input?.file_path&&(Q.push({tool:"Write",file_path:y.input.file_path,content:y.input.content}),K.push({sequence:K.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:y.input.file_path,content:typeof y.input.content=="string"?y.input.content:void 0}))}y.type==="thinking"&&y.thinking&&B?.({type:"thinking",jobId:s,text:y.thinking},s)}}_.type==="result"&&_.is_error===!0&&(z=!0,typeof _.error=="string"&&(O=_.error),typeof _.result=="string"&&(A=_.result)),_.type==="user"&&_.tool_use_result?.file?.filePath&&B?.({type:"tool_use",jobId:s,tool:"Read",file:_.tool_use_result.file.filePath},s)}catch{}});let T=[];U.stderr?.on("data",L=>{T.push(L.toString())}),U.on("close",L=>{if(clearTimeout(M),N.close(),V.length===0&&$.size>0&&console.warn(`[Claude:${s}] No text captured. Event types seen: ${[...$].join(", ")}`),k)z=!0,Z=`Timed out after ${Math.round(E/6e4)} minutes`;else if(L!==0&&L!==null){z=!0;let ee=T.join("").trim(),y=V.join("").trim(),le=V.length===0&&$.size>0?` (no text captured, event types: ${[...$].join(", ")})`:"";Z=ee||A||y||`Claude process exited with code ${L}${le}`}z&&!Z&&A&&(Z=A);let _=zs(Z,O);w({sessionId:q,text:V.join(""),success:!z,error:z?_.message:void 0,errorCode:z?_.code:void 0,recoverableError:z?_.recoverable:void 0,fileEdits:Q.length>0?Q:void 0,editEvents:K.length>0?K:void 0})}),U.on("error",L=>{clearTimeout(M),z=!0,Z=L.message,w({sessionId:q,text:V.join(""),success:!1,error:Z,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:Q.length>0?Q:void 0,editEvents:K.length>0?K:void 0})})});return{process:U,result:W}}function zs(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 Bs,spawnSync as Ht}from"child_process";import{readFileSync as Fs,statSync as js}from"fs";import{basename as Ls,extname as Us,isAbsolute as Ws,relative as Gt,resolve as Hs}from"path";import{createInterface as Gs}from"readline";function Ft(s){let e=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var jt=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"]),vt=2e5,qs=1e5,qt=2e5;function Qt(s){let e=Ls(s).toLowerCase(),n=Us(s).toLowerCase();return jt.has(n)||jt.has(e)}function Xt(s,e){let n=Ws(e)?e:Hs(s,e),t=Gt(s,n);return t===""||t.startsWith("..")?null:n}function Xe(s,e){if(!Qt(e))return;let n=Xt(s,e);if(n)try{let t=js(n);return t.isFile()?t.size>vt?{exists:!0,truncated:!0}:{exists:!0,content:Fs(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Qs(s,e){for(let n of e){let t=s[n];if(typeof t=="string")return t}}function Xs(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 Lt(s){return Qs(s,["patch","diff","unifiedDiff","unified_diff"])}function wt(s,e){return s.length<=e?{text:s}:{text:s.slice(0,e),truncated:!0}}function Ut(s,e){let n=Ht("git",e,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:qt+65536});return n.status!==0?null:n.stdout??""}function Ys(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 Wt(s){let e=Ut(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Ut(s,["diff","--no-ext-diff","HEAD","--"])??"",t=wt(n,qt);return{status:e,changedFiles:Ys(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Vs(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function Ks(s,e){if(!Qt(e))return;let n=Xt(s,e);if(!n)return;let t=Gt(s,n);if(t===""||t.startsWith(".."))return;let o=Ht("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:vt+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",a=wt(i,vt);return{exists:!0,content:a.text,...a.truncated?{truncated:!0}:{}}}function Zs(s,e,n){return e.map(t=>{let o=n.has(t)?n.get(t):Ks(s,t),i=Xe(s,t);return{filePath:t,...o?{before:o}:{},...i?{after:i}:{}}})}function Ye(s,e){let{prompt:n,projectRoot:t,screenshotPath:o,resumeSessionId:i,model:a,onEvent:l,sandboxMode:f="workspace-write",configOverrides:v=[]}=e,x=[];if(i){x.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${f}"`);for(let J of v)x.push("-c",J);a&&x.push("-m",a),x.push(i),x.push(n),o&&x.push("--image",o)}else{x.push("exec","--skip-git-repo-check","--json","--sandbox",f);for(let J of v)x.push("-c",J);a&&x.push("-m",a),x.push(n),o&&x.push("--image",o)}let E=Bs("codex",x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),B=new Promise(J=>{let U,W=[],w=[],q=[],V=new Map,Q=new Map,K=!1,z="",Z=Gs({input:E.stdout}),O=new Set;Z.on("line",k=>{if(k.trim())try{let M=JSON.parse(k),N=M.type??"unknown";if(O.add(N),N==="thread.started"&&M.thread_id&&!U&&(U=M.thread_id),(N==="item.agentMessage.delta"||N==="item/agentMessage/delta")&&M.delta?.text&&(W.push(M.delta.text),l?.({type:"delta",jobId:s,text:M.delta.text},s)),(N==="item.reasoning.delta"||N==="item/reasoning/delta")&&M.delta?.text&&l?.({type:"thinking",jobId:s,text:M.delta.text},s),(N==="item.started"||N==="item/started")&&M.item){let $=M.item.type;if($==="command_execution"){let T=M.item.command,L=T?Ft(T):void 0,_=Wt(t),ee=new Map;for(let le of _?.changedFiles??[])ee.set(le,Xe(t,le));typeof M.item.id=="string"&&Q.set(M.item.id,{...T?{rawCommand:T}:{},...L?{command:L}:{},..._?{beforeWorktree:_}:{},beforeSnapshots:ee});let y=L?`Bash: ${L.split(`
|
|
31
|
+
`)[0].slice(0,80)}`:"Bash";w.push(y),l?.({type:"tool_use",jobId:s,tool:"Bash",...L?{content:L}:{}},s)}else if($==="file_change"){let T=M.item.filename||M.item.path;T&&!V.has(T)&&V.set(T,Xe(t,T)),w.push(T?`Edit ${T.split("/").pop()}`:"Edit"),l?.({type:"tool_use",jobId:s,tool:"Edit",...T?{file:T}:{}},s)}else if($==="file_read"){let T=M.item.filename||M.item.path;w.push(T?`Read ${T.split("/").pop()}`:"Read"),l?.({type:"tool_use",jobId:s,tool:"Read",...T?{file:T}:{}},s)}else if($==="web_search")w.push("WebSearch"),l?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if($==="mcp_tool_call"){let T=M.item.tool_name||M.item.name||"MCP";w.push(T),l?.({type:"tool_use",jobId:s,tool:T},s)}}if((N==="item.completed"||N==="item/completed")&&M.item){if(M.item.type==="agent_message"){let $=M.item.text;typeof $=="string"&&$&&(W.push($),l?.({type:"delta",jobId:s,text:$},s))}else if(M.item.type==="reasoning"){let $=M.item.text;typeof $=="string"&&$&&l?.({type:"thinking",jobId:s,text:$},s)}else if(M.item.type==="file_change"&&Array.isArray(M.item.changes))for(let $ of M.item.changes){let T=$.path||$.filename,L=$.kind==="add"?"Write":"Edit";if(T){w.push(`${L} ${T.split("/").pop()}`),l?.({type:"tool_use",jobId:s,tool:L,file:T},s);let _=$,ee=typeof _.kind=="string"?_.kind:void 0,y=Xs(ee),le=V.get(T),ie=Xe(t,T);q.push({sequence:q.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:y,filePath:T,...le?{before:le}:{},...ie?{after:ie}:{},...Lt(_)?{patch:Lt(_)}:{},...ee?{rawKind:ee}:{}}),V.set(T,ie)}}else if(M.item.type==="command_execution"){let $=typeof M.item.id=="string"?M.item.id:void 0,T=$?Q.get($):void 0,L=typeof M.item.command=="string"?M.item.command:T?.rawCommand,_=L?Ft(L):T?.command,ee=Wt(t);if(Vs(T?.beforeWorktree,ee)){let y=[...new Set([...T?.beforeWorktree?.changedFiles??[],...ee?.changedFiles??[]])],le=typeof M.item.aggregated_output=="string"?wt(M.item.aggregated_output,qs):void 0,ie=typeof M.item.exit_code=="number"?M.item.exit_code:M.item.exit_code===null?null:void 0,G=typeof M.item.status=="string"?M.item.status:void 0;q.push({sequence:q.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...L?{rawCommand:L}:{},..._?{command:_}:{},...ie!==void 0?{exitCode:ie}:{},...G?{status:G}:{},...le?{output:le.text}:{},...le?.truncated?{outputTruncated:!0}:{},...T?.beforeWorktree?{beforeWorktree:T.beforeWorktree}:{},...ee?{afterWorktree:ee}:{},...y.length>0?{touchedFiles:Zs(t,y,T?.beforeSnapshots??new Map)}:{}})}$&&Q.delete($)}}N==="turn.failed"&&(K=!0,z=M.error?.message||M.message||"Turn failed")}catch{}});let A=[];E.stderr?.on("data",k=>{A.push(k.toString())}),E.on("close",k=>{Z.close(),W.length===0&&O.size>0&&console.warn(`[Codex:${s}] No text captured. Event types seen: ${[...O].join(", ")}`),k!==0&&k!==null&&(K=!0,z=A.join("")||`Codex process exited with code ${k}`),J({sessionId:U,text:W.join(""),success:!K,error:K?z:void 0,editEvents:q.length>0?q:void 0,toolsUsed:w.length>0?w:void 0})}),E.on("error",k=>{K=!0,z=k.message,J({sessionId:U,text:W.join(""),success:!1,error:z,editEvents:q.length>0?q:void 0,toolsUsed:w.length>0?w:void 0})})});return{process:E,result:B}}import{spawn as eo}from"child_process";import{createInterface as to}from"readline";function Yt(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 Vt(s,e){let{prompt:n,projectRoot:t,resumeSessionId:o,model:i,timeoutMs:a=3e5,onEvent:l,copilotPath:f="copilot"}=e,v=["--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&&v.push(`--resume=${o}`),i&&v.push("--model",i),v.push("-p",n);let x=eo(f,v,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),E=new Promise(B=>{let J,U=[],W=[],w=!1,q="",V=!1,Q=setTimeout(()=>{V=!0,x.kill("SIGTERM"),setTimeout(()=>{try{x.kill("SIGKILL")}catch{}},5e3)},a),K=to({input:x.stdout}),z=new Set,Z=[];K.on("line",A=>{if(A.trim())try{let k=JSON.parse(A),M=Ce(k);z.add(M),Z.length<5&&so(M)&&Z.push(A.slice(0,800));let N=Ae(k,["sessionId","session_id","id"],["session","conversation","thread"]);N&&!J&&(J=N);let $=no(k,U.length===0);$&&(U.push($),l?.({type:"delta",jobId:s,text:$},s));let T=oo(k);T&&l?.({type:"thinking",jobId:s,text:T},s);let L=ro(k);L&&(W.push(L.label),l?.({type:"tool_use",jobId:s,tool:L.tool,...L.file?{file:L.file}:{},...L.content?{content:L.content}:{}},s));let _=io(k);_&&(w=!0,q=_)}catch{}});let O=[];x.stderr?.on("data",A=>{O.push(A.toString())}),x.on("close",A=>{clearTimeout(Q),K.close(),U.length===0&&z.size>0&&(console.warn(`[Copilot:${s}] No text captured. Event types seen: ${[...z].join(", ")}`),Z.length>0&&console.warn(`[Copilot:${s}] Sample text-bearing candidates: ${Z.join(`
|
|
32
|
+
`)}`)),V?(w=!0,q=`Timed out after ${Math.round(a/6e4)} minutes`):A!==0&&A!==null&&(w=!0,q=O.join("").trim()||q||`Copilot process exited with code ${A}`);let k=w?Yt(q,i):null;B({sessionId:J,text:U.join(""),success:!w,error:k?.message,errorCode:k?.code,recoverableError:k?.recoverable,provider:"copilot",toolsUsed:W.length>0?W:void 0})}),x.on("error",A=>{clearTimeout(Q);let k=Yt(A.message,i);B({sessionId:J,text:U.join(""),success:!1,error:k.message,errorCode:k.code,recoverableError:k.recoverable,provider:"copilot",toolsUsed:W.length>0?W:void 0})})});return{process:x,result:E}}function Ce(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 no(s,e=!1){let n=Ce(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 me(s.delta)??me(s.content)??me(s.message);if(n==="assistant.message"&&e)return me(s.message)??me(s.content)??me(s);if(n==="result"&&e)return me(s.result)??me(s.output)??me(s.message)??me(s);let i=s.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof s.text=="string"&&St(s))return s.text;if(typeof s.message=="string"&&St(s))return s.message;if(typeof s.delta=="string"&&St(s))return s.delta}function me(s){if(typeof s=="string")return s;if(!s)return;if(Array.isArray(s)){let n=s.map(me).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=me(e[n]);if(t)return t}}function so(s){let e=s.toLowerCase();return e.includes("assistant.message")||e==="result"}function oo(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 ro(s){let e=Ae(s,["tool","toolName","tool_name","name"]),n=Ae(s,["command","cmd"]),t=Ae(s,["file","path","filename","filePath"]),o=Ce(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 io(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"&&Ce(s).toLowerCase().includes("error"))return s.message}function Ae(s,e,n=[]){for(let t of e){let o=s[t];if(typeof o=="string")return o}for(let[t,o]of Object.entries(s)){if(!o||typeof o!="object"||n.length>0&&!n.some(a=>t.toLowerCase().includes(a)))continue;let i=Ae(o,e);if(i)return i}}function St(s){let e=Ce(s).toLowerCase();return(typeof s.role=="string"?s.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{execFile as ao}from"child_process";import{copyFile as Kt,mkdir as Zt,readdir as lo,readFile as co,writeFile as uo}from"fs/promises";import{join as Ie}from"path";var Ve=class{constructor(e){this.projectRoot=e;let n=Ie(e,".popmelt");this.decisionsDir=Ie(n,"decisions"),this.screenshotsDir=Ie(n,"screenshots")}async persist(e,n,t){try{await Zt(this.decisionsDir,{recursive:!0}),await Zt(this.screenshotsDir,{recursive:!0});try{await Kt(n,Ie(this.screenshotsDir,`s-${e.id}.webp`))}catch{}for(let o=0;o<t.length;o++)try{let i=e.pastedImagePaths[o];i&&await Kt(t[o],Ie(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await uo(Ie(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 lo(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 co(Ie(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=>{ao("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(t,o)=>{if(t){n(null);return}n(o||null)})})}};import{mkdir as $e,readFile as en,writeFile as _e}from"fs/promises";import{join as Oe}from"path";var po=80,fo=24,tn=1e3,Ke=class{constructor(e){this.evalsDir=Oe(e,".popmelt","evals"),this.suitePath=Oe(this.evalsDir,"evals.json"),this.runsPath=Oe(this.evalsDir,"runs.json"),this.screenshotsDir=Oe(this.evalsDir,"screenshots")}async loadSuite(){try{let e=await en(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 en(this.runsPath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.runs))return n}catch{}return{version:1,updatedAt:0,runs:[]}}async loadSuiteWithRuns(){let[e,n]=await Promise.all([this.loadSuite(),this.loadRuns()]);return{...e,runs:n.runs}}async loadSuiteWithCurrentRuns(e){let n=await this.loadSuiteWithRuns();return e?{...n,runs:n.runs.filter(t=>t.codeFingerprint===e)}:n}async writeSynthesized(e){let n=await this.loadSuite(),t=new Map(n.cases.map(a=>[a.id,a])),o=new Set;for(let a of e){let l=t.get(a.id);l&&(l.title!==a.title||l.prompt!==a.prompt||JSON.stringify(l.assertions)!==JSON.stringify(a.assertions))&&o.add(a.id),t.set(a.id,a)}let i={version:1,updatedAt:Date.now(),cases:[...t.values()]};return await $e(this.evalsDir,{recursive:!0}),await _e(this.suitePath,JSON.stringify(i,null,2)),o.size>0&&await this.invalidateRunsForEvals(o),i}async updateCase(e,n){let t=await this.loadSuite(),o=n.title!==void 0||n.assertions!==void 0,i=t.cases.map(l=>l.id===e?{...l,...n.status?{status:n.status}:{},...n.title?{title:n.title}:{},...n.assertions?{assertions:n.assertions}:{}}:l),a=i.find(l=>l.id===e)??null;return a?(await $e(this.evalsDir,{recursive:!0}),await _e(this.suitePath,JSON.stringify({version:1,updatedAt:Date.now(),cases:i},null,2)),o&&await this.invalidateRunsForEvals(new Set([e])),a):null}async invalidateRunsForEvals(e){let t=(await this.loadRuns()).runs.filter(i=>!e.has(i.evalId)),o={version:1,updatedAt:Date.now(),runs:t};return await $e(this.evalsDir,{recursive:!0}),await _e(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 $e(this.evalsDir,{recursive:!0}),await _e(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(e,n){return await $e(this.screenshotsDir,{recursive:!0}),await _e(Oe(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 nn(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?rn(t):null}catch{return null}}function sn(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?rn(t,"pending"):null}catch{return null}}function on(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=wo(t.assertionResults,e),i=So(o);return{status:i,summary:ge(t.summary)||dn(i),assertionResults:o,tooling:xo(t.tooling)}}catch{}return{status:"needs_review",summary:Ze(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 rn(s,e="approved"){let n=[];return s.forEach((t,o)=>{if(!t||typeof t!="object")return;let i=t,a=ge(i.title),l=ge(i.prompt),f=ge(i.rationale),v=Ee(i.assertions);if(!a||!l||v.length===0)return;let x=go(i.category),E=bo(ge(i.id))||`eval-${un(a).slice(0,32)||o+1}`,B=yo(i.status)??e;n.push({id:E,title:a,status:B,category:x,prompt:l,assertions:v,rationale:f||"Inferred from Popmelt design history.",sourceDecisionIds:Ee(i.sourceDecisionIds),sourceThreadIds:Ee(i.sourceThreadIds)})}),n}function an(s){let e=[...s.decisions].sort((t,o)=>o.createdAt-t.createdAt).slice(0,po),n=Object.values(s.threads.threads).sort((t,o)=>o.updatedAt-t.updatedAt).slice(0,fo);return`You are helping a designer turn organic Popmelt annotation history into a project eval suite.
|
|
34
34
|
|
|
35
35
|
The designer does NOT work eval-first. They use annotations and conversation threads to zhuzh the UI over time. Your job is to infer useful eval proposals from that trail. The developer will reject, refine, or approve proposals in this thread. Do not write files or run commands.
|
|
36
36
|
|
|
@@ -45,12 +45,12 @@ ${JSON.stringify(s.existingSuite,null,2)}
|
|
|
45
45
|
\`\`\`
|
|
46
46
|
|
|
47
47
|
## Recent Decisions
|
|
48
|
-
${e.map(
|
|
48
|
+
${e.map(ho).join(`
|
|
49
49
|
|
|
50
50
|
`)||"No decisions found."}
|
|
51
51
|
|
|
52
52
|
## Recent Threads
|
|
53
|
-
${n.map(
|
|
53
|
+
${n.map(mo).join(`
|
|
54
54
|
|
|
55
55
|
`)||"No threads found."}
|
|
56
56
|
|
|
@@ -86,7 +86,7 @@ Allowed categories: component, layout, copy, interaction, visual, workflow.
|
|
|
86
86
|
Return only the <evals> block after approval.
|
|
87
87
|
|
|
88
88
|
## First Response Structured Block
|
|
89
|
-
At the end of your first proposal response, output a JSON array inside <eval_proposals> tags using the same schema, but with "status": "pending".`}function
|
|
89
|
+
At the end of your first proposal response, output a JSON array inside <eval_proposals> tags using the same schema, but with "status": "pending".`}function ln(s){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
|
|
90
90
|
|
|
91
91
|
## Eval
|
|
92
92
|
\`\`\`json
|
|
@@ -141,7 +141,7 @@ The block must be valid JSON with this shape:
|
|
|
141
141
|
\`\`\`
|
|
142
142
|
|
|
143
143
|
Allowed statuses: pass, fail, needs_review.
|
|
144
|
-
Allowed chromeDevtools values: available, unavailable, unknown.`}function
|
|
144
|
+
Allowed chromeDevtools values: available, unavailable, unknown.`}function cn(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,23 +190,23 @@ Allowed categories: component, layout, copy, interaction, visual, workflow.
|
|
|
190
190
|
|
|
191
191
|
<eval_proposals>
|
|
192
192
|
[]
|
|
193
|
-
</eval_proposals>`}function
|
|
193
|
+
</eval_proposals>`}function ho(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(l=>l.instruction).filter(Boolean).join(`
|
|
194
194
|
`),i=n.map(l=>{let f=l.finalScope??l.inferredScope??l.declaredScope;return`- ${l.status}: ${l.summary}${f?` [${f.breadth}/${f.target}]`:""}`}).join(`
|
|
195
195
|
`),a=[...new Set([...n.flatMap(l=>l.filesModified??[]),...t.map(l=>l.filePath).filter(l=>!!l)])].slice(0,12);return`### Decision ${s.id}
|
|
196
196
|
Thread: ${s.threadId??"none"}
|
|
197
197
|
Created: ${new Date(s.createdAt).toISOString()}
|
|
198
198
|
URL: ${s.url||"unknown"}
|
|
199
199
|
Instructions:
|
|
200
|
-
${
|
|
200
|
+
${Ze(o||"(none)",tn)}
|
|
201
201
|
Resolutions:
|
|
202
|
-
${
|
|
203
|
-
Files: ${a.length>0?a.join(", "):"none"}`}function
|
|
202
|
+
${Ze(i||"(none)",tn)}
|
|
203
|
+
Files: ${a.length>0?a.join(", "):"none"}`}function mo(s){let n=s.messages.slice(0,2).concat(s.messages.length>4?s.messages.slice(-2):s.messages.slice(2)).map(t=>{let o=t.feedbackSummary??t.replyToQuestion??t.question??t.responseText??"",i=t.resolutions?.map(a=>`${a.status}: ${a.summary}`).join("; ")??"";return`- ${t.role}: ${Ze(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 ge(s){return typeof s=="string"?s.trim():""}function ke(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function no(s){let e=ge(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function so(s){let e=ge(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function oo(s){let e=ge(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function ro(s,e){let t=(Array.isArray(s)?s:[]).map(o=>{if(!o||typeof o!="object")return null;let i=o,a=ge(i.assertion);return a?{assertion:a,status:oo(i.status)??"needs_review",summary:ge(i.summary)||tn("needs_review"),evidence:ke(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 io(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function ao(s){if(!s||typeof s!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=s,n=ge(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:ke(e.evidenceTypes).length>0?ke(e.evidenceTypes):["screenshot"]}}function tn(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 lo(s){return nn(s).slice(0,48)}function nn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Qe(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as sn}from"crypto";import{mkdir as mt,readFile as Xe,writeFile as Se}from"fs/promises";import{dirname as gt,join as $e}from"path";var ie="[Materializer]",on={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},co={version:1,runs:[]},uo={version:1,updatedAt:0,proposals:[]},po=12;function fo(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(`${ie} 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(`${ie} Rule count ${e.length} exceeds cap of 30`),e}function ho(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function mo(s,e){let n=new Set(e),t=new Set,o=Array.isArray(s.rules)?s.rules:[];for(let l of o){if(!l||typeof l!="object")continue;let f=l.sources;if(Array.isArray(f))for(let v of f)typeof v=="string"&&n.has(v)&&t.add(v)}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 go(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function yo(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 vo(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=yo(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=go(n)}function wo(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 Ye=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 Xe(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=fo(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 Se(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ie} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]});let o=e.split("."),i=t;for(let f=0;f<o.length-1;f++){let v=o[f];(!i[v]||typeof i[v]!="object")&&(i[v]={}),i=i[v]}let a=o[o.length-1],l;try{l=JSON.parse(n)}catch{l=null}if(l&&typeof l=="object"&&l!==null&&"value"in l)i[a]=l;else{let f=i[a];f&&typeof f=="object"&&f!==null&&"value"in f?f.value=n:i[a]=n}return await Se(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} 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 Se(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ie} 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 Se(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ie} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){return(await this.selectUnmaterializedPatternDecisions()).decisions}async selectUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=(await this.decisionStore.listDecisionIds()).filter(l=>{let f=e.decisions[l];return f?f.status==="applied"||f.status==="merged"||f.status==="rejected"||f.status==="running"||f.status==="queued"||f.status==="proposed"?!1:f.attemptCount<3:!0});if(t.length===0)return{decisions:[],totalCandidateDecisionCount:0};let i=(await this.decisionStore.loadDecisions(t)).filter(l=>l.resolutions.some(f=>(f.finalScope??f.inferredScope)?.breadth==="pattern")),a=i.sort((l,f)=>f.createdAt-l.createdAt).slice(0,po);return i.length>a.length&&console.log(`${ie} 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(U=>U.id);console.log(`${ie} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let a=await this.loadModel(),l=Po(o,a),f=ho(o,t.totalCandidateDecisionCount,l);n=sn().slice(0,8);let v={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,decisionIds:i,startedAt:Date.now(),promptStats:f};await this.persistRun(v),await this.updateDecisionStates(i,"running",n);let b=!0,E,F,D;try{let U=`mat-${Date.now()}`,{provider:w,result:G}=this.spawnModelAgent(U,l,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});v={...v,provider:w},await this.persistRun(v);let Y=await G;if(!Y.success)b=!1,E=Y.error,console.error(`${ie} ${w} spawn error:`,E);else{let q=Ve(Y.text);if(q){Array.isArray(q.rules)&&(q.rules=_e(q.rules)),F=mo(q,i);let V=await this.createModelProposal({decisionIds:i,proposedModel:q,runId:n,threadId:e.threadId,provider:w,model:e.model??this.options.model});D=V.id,console.log(`${ie} Created model proposal ${V.id} for ${i.length} decision(s)`)}else b=!1,E="No <model> block found in response",console.error(`${ie} ${E}`)}}catch(U){b=!1,E=U instanceof Error?U.message:String(U),console.error(`${ie} Error:`,E)}let H=await this.loadIndex();return H.lastRunAt=Date.now(),H.lastRunDecisionIds=i,H.lastRunError=E??null,await this.persistIndex(H),await this.updateDecisionStates(i,b?"proposed":"failed",n,E),await this.persistRun({...v,status:b?"proposed":"failed",completedAt:Date.now(),error:E,outputStats:F,proposalId:D}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:b,error:E}),{processedIds:i,success:b,error:E,runId:n,proposalId:D}}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=Io(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(`${ie} ${o} consolidation spawn error:`,a.error),{success:!1,error:a.error};let l=Ve(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 Se(this.modelPath,JSON.stringify(l,null,2)),console.log(`${ie} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${ie} 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(`${ie} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=_e(e.rules)),await Se(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ie} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await Xe(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={...on,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...on,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 mt(gt(this.indexPath),{recursive:!0}),await Se(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ie} Failed to write index:`,n)}}async loadRuns(){try{let e=await Xe(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...co,runs:[]}}async loadModelProposals(){try{let e=await Xe(this.proposalsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.proposals))return n}catch{}return{...uo,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 l of n)!Array.isArray(l.path)||l.path.length===0||(l.remove?wo(i,l.path):vo(i,l.path,l.value));await this.writeModel(i);let a=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0,selectedChanges:t});return await this.updateDecisionStates(o.decisionIds,"applied",o.runId??e),a}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:sn().slice(0,8),status:"pending",title:xo(e.proposedModel),summary:bo(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 mt(gt(this.proposalsPath),{recursive:!0}),await Se(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ie} 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 mt(gt(this.runsPath),{recursive:!0}),await Se(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${ie} Failed to write materialization run:`,n)}}async updateDecisionStates(e,n,t,o){let i=await this.loadIndex(),a=Date.now();for(let l of e){let f=i.decisions[l],v=f?.runIds.includes(t)?f.runIds:[...f?.runIds??[],t];i.decisions[l]={status:n,runIds:v,error:o,attemptCount:n==="running"?f?.attemptCount??0:(f?.attemptCount??0)+1,updatedAt:a}}await this.persistIndex(i)}spawnModelAgent(e,n,t,o){let i=t.provider??this.options.provider??"claude",a=this.options.onEvent?(l,f)=>this.options.onEvent?.(l):void 0;return i==="codex"?{provider:"codex",...He(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:So(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:a})}:(i==="copilot"&&console.warn(`${ie} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...Ue(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,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:a})})}};function So(s){let e=[];return s?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(s.reasoningEffort)}`),s?.serviceTier&&e.push(`service_tier=${JSON.stringify(s.serviceTier)}`),e}function xo(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 bo(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 Ve(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 Po(s,e){let n=s.map(i=>{let l=i.resolutions.filter(b=>(b.finalScope??b.inferredScope)?.breadth==="pattern").map(b=>{let F=(b.finalScope??b.inferredScope)?.target??"unknown",D=b.filesModified?.join(", ")??"none";return`- **${b.summary}** [scope: pattern/${F}]
|
|
208
|
-
Files modified: ${
|
|
209
|
-
`),f=i.annotations.map(
|
|
207
|
+
${n}`}function ge(s){return typeof s=="string"?s.trim():""}function Ee(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function go(s){let e=ge(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function yo(s){let e=ge(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function vo(s){let e=ge(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function wo(s,e){let t=(Array.isArray(s)?s:[]).map(o=>{if(!o||typeof o!="object")return null;let i=o,a=ge(i.assertion);return a?{assertion:a,status:vo(i.status)??"needs_review",summary:ge(i.summary)||dn("needs_review"),evidence:Ee(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 So(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function xo(s){if(!s||typeof s!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=s,n=ge(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Ee(e.evidenceTypes).length>0?Ee(e.evidenceTypes):["screenshot"]}}function dn(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 bo(s){return un(s).slice(0,48)}function un(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ze(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as pn}from"crypto";import{mkdir as xt,readFile as et,writeFile as be}from"fs/promises";import{dirname as bt,join as De}from"path";var ae="[Materializer]",fn={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Po={version:1,runs:[]},Io={version:1,updatedAt:0,proposals:[]},ko=12;function Mo(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 Ne(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(`${ae} 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(`${ae} Rule count ${e.length} exceeds cap of 30`),e}function Ro(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Eo(s,e){let n=new Set(e),t=new Set,o=Array.isArray(s.rules)?s.rules:[];for(let l of o){if(!l||typeof l!="object")continue;let f=l.sources;if(Array.isArray(f))for(let v of f)typeof v=="string"&&n.has(v)&&t.add(v)}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 To(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function Ao(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 Co(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=Ao(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=To(n)}function $o(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 tt=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=De(e,".popmelt");this.indexPath=De(o,"materialized.json"),this.runsPath=De(o,"materialization-runs.json"),this.proposalsPath=De(o,"model-proposals.json"),this.modelPath=De(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await et(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Mo(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 be(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]});let o=e.split("."),i=t;for(let f=0;f<o.length-1;f++){let v=o[f];(!i[v]||typeof i[v]!="object")&&(i[v]={}),i=i[v]}let a=o[o.length-1],l;try{l=JSON.parse(n)}catch{l=null}if(l&&typeof l=="object"&&l!==null&&"value"in l)i[a]=l;else{let f=i[a];f&&typeof f=="object"&&f!==null&&"value"in f?f.value=n:i[a]=n}return await be(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ae} 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 be(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} 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 be(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){return(await this.selectUnmaterializedPatternDecisions()).decisions}async selectUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=(await this.decisionStore.listDecisionIds()).filter(l=>{let f=e.decisions[l];return f?f.status==="applied"||f.status==="merged"||f.status==="rejected"||f.status==="running"||f.status==="queued"||f.status==="proposed"?!1:f.attemptCount<3:!0});if(t.length===0)return{decisions:[],totalCandidateDecisionCount:0};let i=(await this.decisionStore.loadDecisions(t)).filter(l=>l.resolutions.some(f=>(f.finalScope??f.inferredScope)?.breadth==="pattern")),a=i.sort((l,f)=>f.createdAt-l.createdAt).slice(0,ko);return i.length>a.length&&console.log(`${ae} 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(W=>W.id);console.log(`${ae} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let a=await this.loadModel(),l=Do(o,a),f=Ro(o,t.totalCandidateDecisionCount,l);n=pn().slice(0,8);let v={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,decisionIds:i,startedAt:Date.now(),promptStats:f};await this.persistRun(v),await this.updateDecisionStates(i,"running",n);let x=!0,E,B,J;try{let W=`mat-${Date.now()}`,{provider:w,result:q}=this.spawnModelAgent(W,l,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});v={...v,provider:w},await this.persistRun(v);let V=await q;if(!V.success)x=!1,E=V.error,console.error(`${ae} ${w} spawn error:`,E);else{let Q=nt(V.text);if(Q){Array.isArray(Q.rules)&&(Q.rules=Ne(Q.rules)),B=Eo(Q,i);let K=await this.createModelProposal({decisionIds:i,proposedModel:Q,runId:n,threadId:e.threadId,provider:w,model:e.model??this.options.model});J=K.id,console.log(`${ae} Created model proposal ${K.id} for ${i.length} decision(s)`)}else x=!1,E="No <model> block found in response",console.error(`${ae} ${E}`)}}catch(W){x=!1,E=W instanceof Error?W.message:String(W),console.error(`${ae} Error:`,E)}let U=await this.loadIndex();return U.lastRunAt=Date.now(),U.lastRunDecisionIds=i,U.lastRunError=E??null,await this.persistIndex(U),await this.updateDecisionStates(i,x?"proposed":"failed",n,E),await this.persistRun({...v,status:x?"proposed":"failed",completedAt:Date.now(),error:E,outputStats:B,proposalId:J}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:x,error:E}),{processedIds:i,success:x,error:E,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=No(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(`${ae} ${o} consolidation spawn error:`,a.error),{success:!1,error:a.error};let l=nt(a.text);return l?(Array.isArray(l.rules)&&(l.rules=Ne(l.rules)),!l.tokens&&n.tokens&&(l.tokens=n.tokens),!l.components&&n.components&&(l.components=n.components),await be(this.modelPath,JSON.stringify(l,null,2)),console.log(`${ae} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${ae} 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(`${ae} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ne(e.rules)),await be(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ae} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await et(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={...fn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...fn,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 xt(bt(this.indexPath),{recursive:!0}),await be(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ae} Failed to write index:`,n)}}async loadRuns(){try{let e=await et(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...Po,runs:[]}}async loadModelProposals(){try{let e=await et(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 l of n)!Array.isArray(l.path)||l.path.length===0||(l.remove?$o(i,l.path):Co(i,l.path,l.value));await this.writeModel(i);let a=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0,selectedChanges:t});return await this.updateDecisionStates(o.decisionIds,"applied",o.runId??e),a}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:pn().slice(0,8),status:"pending",title:_o(e.proposedModel),summary:Oo(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 xt(bt(this.proposalsPath),{recursive:!0}),await be(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ae} 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 xt(bt(this.runsPath),{recursive:!0}),await be(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${ae} Failed to write materialization run:`,n)}}async updateDecisionStates(e,n,t,o){let i=await this.loadIndex(),a=Date.now();for(let l of e){let f=i.decisions[l],v=f?.runIds.includes(t)?f.runIds:[...f?.runIds??[],t];i.decisions[l]={status:n,runIds:v,error:o,attemptCount:n==="running"?f?.attemptCount??0:(f?.attemptCount??0)+1,updatedAt:a}}await this.persistIndex(i)}spawnModelAgent(e,n,t,o){let i=t.provider??this.options.provider??"claude",a=this.options.onEvent?(l,f)=>this.options.onEvent?.(l):void 0;return i==="codex"?{provider:"codex",...Ye(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:qe(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:a})}:(i==="copilot"&&console.warn(`${ae} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...Qe(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,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:a})})}};function _o(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 Oo(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 nt(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 Do(s,e){let n=s.map(i=>{let l=i.resolutions.filter(x=>(x.finalScope??x.inferredScope)?.breadth==="pattern").map(x=>{let B=(x.finalScope??x.inferredScope)?.target??"unknown",J=x.filesModified?.join(", ")??"none";return`- **${x.summary}** [scope: pattern/${B}]
|
|
208
|
+
Files modified: ${J}`}).join(`
|
|
209
|
+
`),f=i.annotations.map(x=>x.instruction).filter(Boolean).join(`
|
|
210
210
|
`),v=i.gitDiff?`
|
|
211
211
|
\`\`\`diff
|
|
212
212
|
${i.gitDiff.slice(0,2e3)}
|
|
@@ -290,7 +290,7 @@ Example:
|
|
|
290
290
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
291
291
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
292
292
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
293
|
-
Include property and bindings when the decision context has class-level evidence.`}function
|
|
293
|
+
Include property and bindings when the decision context has class-level evidence.`}function No(s){return`You are consolidating a design model's rules. The model has accumulated too many rules and needs cleanup.
|
|
294
294
|
|
|
295
295
|
## Current Model
|
|
296
296
|
\`\`\`json
|
|
@@ -329,7 +329,7 @@ Output the complete model inside <model> tags. Preserve tokens and components as
|
|
|
329
329
|
|
|
330
330
|
<model>
|
|
331
331
|
{ "tokens": { ... }, "components": { ... }, "rules": [ ... ] }
|
|
332
|
-
</model>`}function
|
|
332
|
+
</model>`}function hn(s){return`You are a design system curator reviewing a project's design model. Your job is to propose improvements to the rules \u2014 merging duplicates, filling gaps, removing noise.
|
|
333
333
|
|
|
334
334
|
## Current Model
|
|
335
335
|
\`\`\`json
|
|
@@ -362,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
|
|
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 st=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}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}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 Jo}from"child_process";import{readFile as It}from"fs/promises";import{homedir as rt}from"os";import{join as he}from"path";var kt=/popmelt/i,zo=/chrome|devtools/i;function ke(){return{found:!1,name:null,scope:null,disabled:!1}}function Te(s,e,n=!1){return{found:!0,name:s,scope:e,disabled:n}}function Je(s){for(let e of Object.keys(s))if(kt.test(e))return e;return null}async function ot(s){try{let e=await It(s,"utf-8");return JSON.parse(e)}catch{return null}}async function Mt(s){let e=rt(),n=await ot(he(e,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=Je(o.mcpServers);if(i)return Te(i,"user")}if(o.projects&&typeof o.projects=="object"){let a=o.projects[s];if(a&&typeof a=="object"){let l=a;if(l.mcpServers&&typeof l.mcpServers=="object"){let f=Je(l.mcpServers);if(f){let v=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(x=>kt.test(x));return Te(f,"project",v)}}}}}let t=await ot(he(s,".mcp.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=Je(o.mcpServers);if(a){let l=await mn(s,a);return Te(a,"mcp.json",l)}}let i=Je(o);if(i&&i!=="mcpServers"){let a=await mn(s,i);return Te(i,"mcp.json",a)}}return ke()}async function mn(s,e){let n=he(s,".claude","settings.local.json"),t=await ot(n);if(t&&typeof t=="object"){let o=t;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var Bo=/^\[mcp_servers\.([^\]]+)\]/;function Fo(s){return s.replace(/^"(.+)"$/,"$1")}function jo(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function yn(s){let e=s.split(`
|
|
366
|
+
`),n=[],t=null;for(let o of e){let i=o.match(Bo);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
|
|
370
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
369
|
+
`)}),n}function vn(s){return/enabled\s*=\s*false/i.test(s)}async function Rt(s){let e=process.env.CODEX_HOME||he(rt(),".codex"),n=await gn(he(e,"config.toml"),"user");if(n.found)return n;let t=await gn(he(s,".codex","config.toml"),"project");return t.found?t:ke()}async function Lo(s,e){let n=process.env.CODEX_HOME||he(rt(),".codex"),t=new Set;for(let o of[he(n,"config.toml"),he(s,".codex","config.toml")])try{let i=await It(o,"utf-8");for(let a of yn(i)){if(jo(a.name)||vn(a.body))continue;let l=Fo(a.name);e.test(l)&&t.add(l)}}catch{}return[...t]}async function wn(s){return Lo(s,zo)}async function Et(s,e="copilot"){let n=await Uo(e);if(n.found)return n;let t=process.env.COPILOT_HOME||he(rt(),".copilot"),o=await Pt(he(t,"mcp-config.json"),"user");if(o.found)return o;let i=await Pt(he(s,".mcp.json"),"mcp.json");if(i.found)return i;let a=await Pt(he(s,".github","mcp.json"),"mcp.json");return a.found?a:ke()}async function Uo(s){try{let e=await new Promise((n,t)=>{Jo(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return Sn(JSON.parse(e),"user")}catch{return ke()}}async function Pt(s,e){let n=await ot(s);return Sn(n,e)}function Sn(s,e){if(!s||typeof s!="object")return ke();let n=s,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=Je(t);return o?Te(o,e):ke()}async function gn(s,e){try{let n=await It(s,"utf-8"),t=yn(n);for(let o of t)if(kt.test(o.name)){let i=vn(o.body);return Te(o.name,e,i)}}catch{}return ke()}import{execFile as xn}from"child_process";import{mkdir as Wo,readFile as bn,writeFile as Pn}from"fs/promises";import{homedir as In}from"os";import{dirname as Ho,join as Tt}from"path";var At="https://mcp.popmelt.com/mcp";async function kn(s=At){let e=Tt(In(),".claude.json"),n;try{let o=await bn(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=At){let e=process.env.CODEX_HOME||Tt(In(),".codex"),n=Tt(e,"config.toml"),t;try{t=await bn(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Wo(Ho(n),{recursive:!0});let o=`
|
|
371
371
|
[mcp_servers.popmelt]
|
|
372
372
|
url = "${s}"
|
|
373
|
-
`;return await
|
|
373
|
+
`;return await Pn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Rn(s=At,e="copilot"){let n=await Go(e);if(qo(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{xn(e,["mcp","add","--transport","http","--json","popmelt",s],{encoding:"utf-8",timeout:1e4},i=>{if(i){o(i);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function Go(s){try{let e=await new Promise((n,t)=>{xn(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 qo(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))}var it=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let o=this.leases.get(e),i={id:e,ownerPid:n,createdAt:o?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,o]of this.leases)o.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};async function at(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 Qo(s),i=Buffer.from(`--${t}`),a=Buffer.from(`--${t}--`),l,f,v,x,E,B,J,U,W,w,q,V,Q,K,z=[],Z=[],O=0,A=[];for(;O<o.length;){let k=o.indexOf(i,O);if(k===-1)break;let M=k+i.length;if(o.slice(k,k+a.length).equals(a))break;let N=M;o[N]===13&&o[N+1]===10&&(N+=2);let $=o.indexOf(`\r
|
|
374
374
|
\r
|
|
375
|
-
`,
|
|
375
|
+
`,N);if($===-1)break;let T=o.slice(N,$).toString("utf-8"),L=$+4,_=o.indexOf(i,L),ee=_!==-1?_-2:o.length;A.push({headers:T,body:o.slice(L,ee)}),O=_!==-1?_:o.length}for(let k of A){let M=k.headers.match(/name="([^"]+)"/);if(!M)continue;let N=M[1];if(N==="screenshot")l=k.body;else if(N==="feedback")f=k.body.toString("utf-8");else if(N==="color")v=k.body.toString("utf-8");else if(N==="provider")x=k.body.toString("utf-8");else if(N==="model")E=k.body.toString("utf-8");else if(N==="reasoningEffort")B=k.body.toString("utf-8");else if(N==="serviceTier")J=k.body.toString("utf-8");else if(N==="goal")U=k.body.toString("utf-8");else if(N==="pageUrl")W=k.body.toString("utf-8");else if(N==="viewport")w=k.body.toString("utf-8");else if(N==="planId")q=k.body.toString("utf-8");else if(N==="manifest")V=k.body.toString("utf-8");else if(N==="tasks")Q=k.body.toString("utf-8");else if(N==="sourceId")K=k.body.toString("utf-8");else if(N.startsWith("screenshot-")){let $=N.slice(11);try{let T=decodeURIComponent($);Z.push({pathname:T,data:k.body})}catch{}}else if(N.startsWith("image-")){let $=N.split("-"),T=parseInt($[$.length-1],10),L=$.slice(1,-1).join("-");L&&!isNaN(T)&&z.push({annotationId:L,index:T,data:k.body})}}if(!l)throw new Error("Missing screenshot field");return f||(f=""),{screenshot:l,feedback:f,color:v,provider:x,model:E,reasoningEffort:B,serviceTier:J,goal:U,pageUrl:W,viewport:w,planId:q,manifest:V,tasks:Q,sourceId:K,pastedImages:z,pageScreenshots:Z}}function Qo(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 ze(s,e){let n=[];if(s.annotations.length>0){n.push("## Annotations");for(let t of s.annotations){let o=t.elements.map(l=>{let f=[l.selector];return l.reactComponent&&f.push(`(${l.reactComponent})`),f.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${o||"none"}`);let a=e?.[t.id];if(a&&a.length>0)for(let l of a)n.push(` Attached image: use the Read tool to view ${l}`)}}if(s.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of s.styleModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${o}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if(s.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of s.textModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=JSON.stringify(t.original),a=JSON.stringify(t.modified),l=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${o}${l}: ${i} \u2192 ${a}`)}}if(s.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of s.domModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",a=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${o}${i} \u2192 ${t.targetParentSelector}${a}`)}}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
|
|
378
|
-
`)}function
|
|
379
|
-
`)}function
|
|
380
|
-
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let o=t.match(
|
|
381
|
-
`));return ot([...st,...f])}function nt(s,e,n=5e3){return new Promise((t,o)=>{Fo(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function En(s){return jo(s,"utf-8")}async function qo(s){let e=[ve(s,"projects"),ve(s,"telemetry")],n=[];for(let t of e)await Tn(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Tn(s,e,n){if(n<0)return;let t;try{t=await Bo(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=ve(s,o.name);if(o.isDirectory()){await Tn(i,e,n-1);return}if(!(!o.isFile()||!Qo(o.name)))try{let a=await Lo(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function Qo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function ot(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 Xo(s){return[...new Set(s)]}function Yo(s){return s.charAt(0).toUpperCase()+s.slice(1)}var rt=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 Vo,readFile as Ko,writeFile as Zo}from"fs/promises";import{dirname as er,join as tr}from"path";var nr={version:1,threads:{}},it=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=tr(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await Ko(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={...nr,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 Vo(er(this.filePath),{recursive:!0}),await Zo(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function An(s){return or(s).slice(0,12)}var sr=[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 or(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):rr(s),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let F=7;F>=0;F--)e.push(n/Math.pow(2,F*8)&255);let t=1779033703,o=3144134277,i=1013904242,a=2773480762,l=1359893119,f=2600822924,v=528734635,b=1541459225,E=new Array(64);for(let F=0;F<e.length;F+=64){for(let J=0;J<16;J++){let K=F+J*4;E[J]=(e[K]<<24|e[K+1]<<16|e[K+2]<<8|e[K+3])>>>0}for(let J=16;J<64;J++){let K=we(E[J-15],7)^we(E[J-15],18)^E[J-15]>>>3,N=we(E[J-2],17)^we(E[J-2],19)^E[J-2]>>>10;E[J]=E[J-16]+K+E[J-7]+N>>>0}let D=t,H=o,U=i,w=a,G=l,Y=f,q=v,V=b;for(let J=0;J<64;J++){let K=we(G,6)^we(G,11)^we(G,25),N=G&Y^~G&q,$=V+K+N+sr[J]+E[J]>>>0,k=we(D,2)^we(D,13)^we(D,22),m=D&H^D&U^H&U,A=k+m>>>0;V=q,q=Y,Y=G,G=w+$>>>0,w=U,U=H,H=D,D=$+A>>>0}t=t+D>>>0,o=o+H>>>0,i=i+U>>>0,a=a+w>>>0,l=l+G>>>0,f=f+Y>>>0,v=v+q>>>0,b=b+V>>>0}return[t,o,i,a,l,f,v,b].map(F=>F.toString(16).padStart(8,"0")).join("")}function we(s,e){return s>>>e|s<<32-e}function rr(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 Cn={name:"@popmelt.com/core",version:"0.8.3",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 $n=Cn.version;var yr=1111,vr=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],wr=1800*1e3,Sr=3600*1e3;function Dn(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
|
|
383
|
-
`)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=t?`Using ${t}`:"tool";break}let f=o??i??void 0,v=e[e.length-1];v&&v.kind==="tool_group"&&v.tool===t?v.items.push({label:l,detail:f}):e.push({kind:"tool_group",tool:t,items:[{label:l,detail:f}]})}return e}function
|
|
384
|
-
`)}function
|
|
377
|
+
`)}function En(s,e,n){let t=[],i=new Set(e.annotations.map(a=>a.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!i&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let a=0;for(let l of n.threadHistory)if(l.role==="human")a++,l.replyToQuestion?(t.push(`### Round ${a} (human) \u2014 reply`),t.push(`"${l.replyToQuestion}"`)):(t.push(`### Round ${a} (human)`),l.feedbackSummary&&t.push(`Annotations: ${l.feedbackSummary}`),l.annotationIds&&l.annotationIds.length>0&&t.push(`Annotation IDs: ${l.annotationIds.join(", ")}`));else if(l.question)t.push(`### Round ${a} (assistant) \u2014 question`),t.push(`"${l.question}"`);else{if(t.push(`### Round ${a} (assistant)`),l.responseText&&t.push(`Response: ${l.responseText}`),l.resolutions&&l.resolutions.length>0)for(let f of l.resolutions){let v=f.finalScope??f.inferredScope,x=v?` [${v.breadth} ${v.target}]`:"";t.push(`- ${f.annotationId}: ${f.status}${x} \u2014 ${f.summary}`),f.filesModified&&f.filesModified.length>0&&t.push(` Files: ${f.filesModified.join(", ")}`)}l.toolsUsed&&l.toolsUsed.length>0&&t.push(`Tools used: ${l.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let a=n.designModel.rules;if(Array.isArray(a)&&a.length>0)if(t.push(""),t.push("Rules:"),a.length>0&&typeof a[0]=="object"&&a[0]!==null&&"scope"in a[0]){let x=new Map;for(let E of a)if(typeof E=="object"&&E!==null&&"text"in E){let B=E,J=B.scope||"general";x.has(J)||x.set(J,[]),x.get(J).push(B.text)}for(let[E,B]of x){t.push(`**${E.charAt(0).toUpperCase()+E.slice(1)}**`);for(let J of B)t.push(`- ${J}`)}}else for(let x of a)typeof x=="string"&&t.push(`- ${x}`);let l=n.designModel.tokens;l&&typeof l=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(l,null,2)),t.push("```"));let f=n.designModel.components;f&&typeof f=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(f,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code.")),i){let a=n?.screenshotPaths??{},l=new Map;for(let f of e.annotations){let v=f.pathname||new URL(e.url).pathname;l.has(v)||l.set(v,[]),l.get(v).push(f)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[f,v]of l){t.push(""),t.push(`## Page: ${f}`);let x=a[f];x&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${x}`):!x&&n?.provider!=="codex"&&(Object.keys(a).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${s}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let E={...e,annotations:v,styleModifications:e.styleModifications},B=ze(E,n?.imagePaths);B&&(t.push(""),t.push(B))}}else{let a=ze(e,n?.imagePaths);a&&(t.push(""),t.push(a))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
|
|
378
|
+
`)}function Tn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Ct(s,e,n,t){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=e.find(a=>a.role==="human"&&a.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),e.length>0){o.push(""),o.push("## Conversation History");let a=0;for(let l of e)l.role==="human"?(a++,l.replyToQuestion?(o.push(`### Round ${a} (human) \u2014 reply`),o.push(`"${l.replyToQuestion}"`)):(o.push(`### Round ${a} (human)`),l.feedbackSummary&&o.push(`Annotations: ${l.feedbackSummary}`))):l.question?(o.push(`### Round ${a} (assistant) \u2014 question`),o.push(`"${l.question}"`)):(o.push(`### Round ${a} (assistant)`),l.responseText&&o.push(`Response: ${l.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let a of t)o.push(`Attached image: use the Read tool to view the image at: ${a}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output a resolution block listing what you did for each annotation:"),o.push("<resolution>"),o.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),o.push("</resolution>"),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
|
|
379
|
+
`)}function Xo(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 Yo(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&&!Xo(e[n]))return!1;return!0}function An(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(Yo):[]}catch{return[]}}function Cn(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 Vo}from"child_process";import{readdir as Ko,readFile as Zo,stat as er}from"fs/promises";import{homedir as Be}from"os";import{join as Se}from"path";var ct=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:$n()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:$n()}],Fe=[{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"}],je={id:"",label:"Default",source:"cli"},tr=/^\s*-\s+"([^"]+)"/;function nr(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(tr);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:$t(i),source:"cli"})}return dt([je,...e])}function sr(s){let e=JSON.parse(s);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,o)=>{let i=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,a=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-a}).flatMap(t=>{let o=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!o)return[];let i=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():$t(o),a=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(f=>{if(!f||typeof f!="object")return[];let v=f;return typeof v.effort!="string"?[]:[{effort:v.effort,...typeof v.description=="string"?{description:v.description}:{}}]}):void 0,l=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(f=>{if(!f||typeof f!="object")return[];let v=f;return typeof v.id!="string"?[]:[{id:v.id,label:typeof v.name=="string"?v.name:v.id,...typeof v.description=="string"?{description:v.description}:{}}]}):void 0;return[{id:o,label:i,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...a&&a.length>0?{supportedReasoningLevels:a}:{},...l&&l.length>0?{speedTiers:l}:{}}]})}function $n(){return["low","medium","high","xhigh","max"].map(s=>({effort:s}))}function or(s){let e=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return dt(e.map(n=>({id:n,label:$t(n),source:"cli"})))}function $t(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":lr(t[1]),a=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${i}${a}${t[4]?" Fast":""}`}let o=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let i=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${i}`:o[3]==="codex"?`Codex ${i}`:o[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function _n(s="copilot"){let e=await lt(s,["help","config"]),n=nr(e);return n.length>1?n:[je]}async function On(s="codex"){let e=await lt(s,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Se(Be(),".codex");return Nn(Se(t,"models_cache.json"))}),n=sr(e);return n.length>0?dt([...n,...Fe]):Fe}async function Dn(s="claude"){let e=Se(Be(),".claude"),n=[Se(Be(),".claude","stats-cache.json"),Se(Be(),".claude","settings.json"),Se(Be(),".claude.json"),Se(e,"cache","changelog.md")],[t,o,i]=await Promise.all([lt(s,["--help"]).catch(()=>""),lt(s,["--version"]).catch(()=>""),rr(e).catch(()=>[])]),a=ar([...n,...i]),l=await Promise.all(a.map(v=>Nn(v).catch(()=>""))),f=or([t,o,...l].join(`
|
|
381
|
+
`));return dt([...ct,...f])}function lt(s,e,n=5e3){return new Promise((t,o)=>{Vo(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function Nn(s){return Zo(s,"utf-8")}async function rr(s){let e=[Se(s,"projects"),Se(s,"telemetry")],n=[];for(let t of e)await Jn(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Jn(s,e,n){if(n<0)return;let t;try{t=await Ko(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=Se(s,o.name);if(o.isDirectory()){await Jn(i,e,n-1);return}if(!(!o.isFile()||!ir(o.name)))try{let a=await er(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function ir(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function dt(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 ar(s){return[...new Set(s)]}function lr(s){return s.charAt(0).toUpperCase()+s.slice(1)}var ut=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 cr,readFile as dr,writeFile as ur}from"fs/promises";import{dirname as pr,join as fr}from"path";var hr={version:1,threads:{}},pt=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=fr(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await dr(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={...hr,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 cr(pr(this.filePath),{recursive:!0}),await ur(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function zn(s){return gr(s).slice(0,12)}var mr=[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 gr(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):yr(s),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let B=7;B>=0;B--)e.push(n/Math.pow(2,B*8)&255);let t=1779033703,o=3144134277,i=1013904242,a=2773480762,l=1359893119,f=2600822924,v=528734635,x=1541459225,E=new Array(64);for(let B=0;B<e.length;B+=64){for(let z=0;z<16;z++){let Z=B+z*4;E[z]=(e[Z]<<24|e[Z+1]<<16|e[Z+2]<<8|e[Z+3])>>>0}for(let z=16;z<64;z++){let Z=xe(E[z-15],7)^xe(E[z-15],18)^E[z-15]>>>3,O=xe(E[z-2],17)^xe(E[z-2],19)^E[z-2]>>>10;E[z]=E[z-16]+Z+E[z-7]+O>>>0}let J=t,U=o,W=i,w=a,q=l,V=f,Q=v,K=x;for(let z=0;z<64;z++){let Z=xe(q,6)^xe(q,11)^xe(q,25),O=q&V^~q&Q,A=K+Z+O+mr[z]+E[z]>>>0,k=xe(J,2)^xe(J,13)^xe(J,22),M=J&U^J&W^U&W,N=k+M>>>0;K=Q,Q=V,V=q,q=w+A>>>0,w=W,W=U,U=J,J=A+N>>>0}t=t+J>>>0,o=o+U>>>0,i=i+W>>>0,a=a+w>>>0,l=l+q>>>0,f=f+V>>>0,v=v+Q>>>0,x=x+K>>>0}return[t,o,i,a,l,f,v,x].map(B=>B.toString(16).padStart(8,"0")).join("")}function xe(s,e){return s>>>e|s<<32-e}function yr(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 Bn={name:"@popmelt.com/core",version:"0.8.4",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 .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},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",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var Fn=Bn.version;var Tr=1111,Ar=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Cr=1800*1e3,$r=3600*1e3,Un=45e3,_r=5e3,Or=1e4;function Wn(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 Qn(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 Dr(s){let e=[];for(let n of s)if(n.type==="delta"){let t=n.text;if(!t)continue;let o=e[e.length-1];o&&o.kind==="text"?o.text+=t:e.push({kind:"text",text:t})}else if(n.type==="tool_use"){let t=n.tool||"",o=n.file??void 0,i=n.content??void 0,a=o?o.split("/").pop()??o:void 0,l;switch(t){case"Read":l=a?`Reading ${a}`:"Reading file";break;case"Edit":l=a?`Editing ${a}`:"Editing file";break;case"Write":l=a?`Writing ${a}`:"Writing file";break;case"Bash":l=i?i.split(`
|
|
383
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=t?`Using ${t}`:"tool";break}let f=o??i??void 0,v=e[e.length-1];v&&v.kind==="tool_group"&&v.tool===t?v.items.push({label:l,detail:f}):e.push({kind:"tool_group",tool:t,items:[{label:l,detail:f}]})}return e}function Nr(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 Jr(s,e=96){let n=s.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Hn(s){let e=s.styleModifications.flatMap(a=>{let l=a.element?.reactComponent||a.element?.tagName||a.selector;return a.changes.map(f=>`${l}: ${f.property} ${f.original||"unset"} -> ${f.modified||"unset"}`)}),n=(s.spacingTokenChanges??[]).map(a=>`${a.tokenName}: ${a.originalPx}px -> ${a.newPx}px`),t=(s.textModifications??[]).map(a=>`${a.element?.reactComponent||a.element?.tagName||a.selector}: text ${a.original||"empty"} -> ${a.modified||"empty"}`),o=s.annotations.map(a=>{let l=a.instruction?.trim();if(l)return l;if(a.imageCount&&a.imageCount>0)return`${a.imageCount} image${a.imageCount===1?"":"s"}`;let f=a.elements?.[0]?.reactComponent||a.elements?.[0]?.selector||a.linkedSelector||a.type;return`${a.type==="annotation"?"Annotation":`${a.type} annotation`} on ${f}`}),i=[...e,...t,...n,...o].map(a=>Jr(a)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function zr(s,e){let n=s.headers.origin;Qn(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 m(s,e,n){s.writeHead(e,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}async function Br(s){let e=[],n=0;for await(let o of s){let i=typeof o=="string"?Buffer.from(o):o;if(n+=i.length,n>16384)throw new Error("Request body too large");e.push(i)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}function Fr(s,e){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function jr(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 ht(s,e){try{s.res.write(`event: ${e.type}
|
|
385
385
|
data: ${JSON.stringify(e)}
|
|
386
386
|
|
|
387
|
-
`)}catch{}}function
|
|
387
|
+
`)}catch{}}function Ue(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function Lr(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 Ur(s,e){return new Promise((n,t)=>{let o=a=>{s.removeListener("listening",i),t(a)},i=()=>{s.removeListener("error",o),n()};s.once("error",o),s.once("listening",i),s.listen(e,"127.0.0.1")})}function Gn(s){try{let e=mt("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=mt("git",["status","--porcelain","--untracked-files=all",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),o=mt("git",["diff","HEAD",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return wr("sha256").update(`${e}
|
|
388
388
|
${t}
|
|
389
|
-
${o}`).digest("hex").slice(0,16)}catch{return}}async function
|
|
389
|
+
${o}`).digest("hex").slice(0,16)}catch{return}}async function Xn(s={}){let e=s.port??Tr,n=s.projectRoot??process.cwd(),t=await br(n).catch(()=>n),o=zn(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),a=s.tempDir??ye(Mr(),"popmelt-bridge"),l=s.maxTurns??40,f=s.maxBudgetUsd??1,v=[...s.allowedTools??Ar],x=s.claudePath??"claude",E=s.copilotPath??"copilot",B=s.provider??"claude",J=s.timeoutMs,U=s.restartMode??"embedded",W=e,w={},q={claude:x,codex:"codex",copilot:E};for(let[r,c]of Object.entries(q))try{let u=c.includes("/")?c:mt("which",[c],{encoding:"utf-8"}).trim();w[r]={available:!0,path:u}}catch{w[r]={available:!1,path:null}}function V(r,c){return new Promise(u=>{let p=jn(c,["--version"],{stdio:["ignore","ignore","ignore"]}),h=!1,d=g=>{h||(h=!0,u(g))},P=setTimeout(()=>{p.kill("SIGTERM"),d(!0)},5e3);p.on("error",()=>{clearTimeout(P),d(!1)}),p.on("close",g=>{clearTimeout(P),d(g===0)})})}await Promise.all([(async()=>{w.claude&&(w.claude.models=w.claude.available&&w.claude.path?await Dn(w.claude.path).catch(()=>ct):ct)})(),(async()=>{w.codex&&(w.codex.models=w.codex.available&&w.codex.path?await On(w.codex.path).catch(()=>Fe):Fe)})(),(async()=>{w.copilot&&(w.copilot.models=w.copilot.available&&w.copilot.path?await _n(w.copilot.path).catch(()=>[je]):[je])})()]);let[Q,K,z]=await Promise.all([Mt(t),Rt(t),Et(t,w.copilot?.path??E)]),Z=await wn(t);w.claude&&(w.claude.mcp=Q),w.codex&&(w.codex.mcp=K),w.copilot&&(w.copilot.mcp=z),Q.found&&Q.name&&v.push(`mcp__${Q.name}__*`),await Sr(a,{recursive:!0}),qn(a).catch(()=>{});let O=new ut(1),A=new st,k=new it(Un),M=null,N=0,$=!1,T=()=>{N+=1,$=!1,M&&clearTimeout(M),M=null},L=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},_=()=>{if(U!=="detached"||k.size>0||$)return;$=!0;let r=++N,c=Date.now()+Or,u=()=>{if(r!==N)return;if(k.size>0){T();return}if(!(O.isRunning||O.depth>0||A.isRunning||A.depth>0)||Date.now()>=c){$=!1,M=setTimeout(L,50),M.unref?.();return}M=setTimeout(u,250),M.unref?.()};u()},ee=new Set,y=new pt(t),le=new Ve(t),ie=new Ke(t),G=new tt(t,le,{claudePath:x,provider:B,timeoutMs:J,onEvent:r=>{for(let c of ee)ht(c,r)}}),ts=20,ns=300*1e3,ve=[];function We(){let r=Date.now()-ns;for(;ve.length>0&&(ve[0].completedAt<r||ve.length>ts);)ve.shift()}let we=new Map,He=null,_t;O.addListener((r,c,u)=>{for(let p of ee)(!u||!p.sourceId||p.sourceId===u)&&ht(p,r)}),A.addListener((r,c,u)=>{for(let p of ee)(!u||!p.sourceId||p.sourceId===u)&&ht(p,r)}),A.setProcessor(async r=>{let c=r.provider??B;try{let u=await G.run({provider:c,model:r.model,threadId:r.threadId,agentSettings:r.agentSettings});if(r.status==="cancelled")return;let p=await G.loadRuns(),h=u.runId?p.runs.find(P=>P.id===u.runId):void 0,d=Nr(u,h);if(r.threadId&&(await y.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c})||await y.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c})),u.success)r.status="done",r.result=d,A.broadcast({type:"done",jobId:r.id,success:!0,responseText:d,threadId:r.threadId},r.id,r.sourceId),ve.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),We();else{if(r.status="error",r.error=u.error??"Materialization failed",r.threadId){let P=`Model materialization failed.
|
|
390
390
|
|
|
391
|
-
${r.error}`;await
|
|
391
|
+
${r.error}`;await y.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P,error:r.error,model:r.model,provider:c})||await y.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P,error:r.error,model:r.model,provider:c})}A.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),ve.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),We()}}catch(u){if(r.status==="cancelled")return;if(r.status="error",r.error=u instanceof Error?u.message:String(u),r.threadId){let p=`Model materialization failed.
|
|
392
392
|
|
|
393
|
-
${r.error}`;await
|
|
393
|
+
${r.error}`;await y.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:p,error:r.error,model:r.model,provider:c})||await y.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:p,error:r.error,model:r.model,provider:c})}A.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),ve.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),We()}}),O.setProcessor(async r=>{let c=r,u=c._replyPrompt,p=c._replyText,h=c._replyImagePaths,d=r.provider??B;r.threadId&&p!==void 0&&await y.updateMessage(r.threadId,r.id,{queued:!1});let P;if(r.threadId){let D=await y.getThread(r.threadId);if(D){for(let H=D.messages.length-1;H>=0;H--)if(D.messages[H].sessionId){P=D.messages[H].sessionId;break}}}let g;if(P&&u){if(g=p??u,h&&h.length>0){g+=`
|
|
394
394
|
|
|
395
|
-
The developer attached reference images with their reply:`;for(let
|
|
396
|
-
Attached image: use the Read tool to view the image at: ${
|
|
395
|
+
The developer attached reference images with their reply:`;for(let D of h)g+=`
|
|
396
|
+
Attached image: use the Read tool to view the image at: ${D}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?g+=`
|
|
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.`:g+=`
|
|
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(P)
|
|
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(P)g=ze(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 O=!u&&r.threadId?await m.getThreadHistory(r.threadId):void 0,W=u?null:await x.loadModel();y=u??Sn(r.screenshotPath,r.feedback,{threadHistory:O&&O.length>0?O:void 0,provider:d,imagePaths:r.imagePaths,designModel:W??void 0,screenshotPaths:r.screenshotPaths})}let R=Mr(r.color,`[\u22B9 ${U}:${r.id}]`),I=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 ${I} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${P?` (resuming: ${P.slice(0,8)})`:""}`);let C=(O,W)=>{O.type==="delta"&&"text"in O?N.accumulateText(W,"response",O.text):O.type==="thinking"&&"text"in O&&N.accumulateText(W,"thinking",O.text),N.broadcast(O,W,r.sourceId)},{process:ee,result:Q}=d==="codex"?He(r.id,{prompt:y,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:P,model:r.model,configOverrides:Tr(r.agentSettings),onEvent:C}):d==="copilot"?Ut(r.id,{prompt:y,projectRoot:t,resumeSessionId:P,model:r.model,timeoutMs:D,copilotPath:w.copilot?.path??E,onEvent:C}):Ue(r.id,{prompt:y,projectRoot:t,maxTurns:l,maxBudgetUsd:f,allowedTools:v,claudePath:b,resumeSessionId:P,model:r.model,reasoningEffort:r.agentSettings?.reasoningEffort,timeoutMs:D,onEvent:C});N.setActiveProcess(r.id,ee);let S=await Q;if(r.result=S.text,S.success){console.log(`${R} Iteration complete`),S.fileEdits&&S.fileEdits.length>0&&console.log(`${R} Captured ${S.fileEdits.length} file edit(s): ${S.fileEdits.map(B=>`${B.tool} ${B.file_path}`).join(", ")}`),S.editEvents&&S.editEvents.length>0&&console.log(`${R} Captured ${S.editEvents.length} edit event(s): ${S.editEvents.map(B=>`${B.operation} ${B.filePath}`).join(", ")}`),r.status="done";let O=xn(S.text),W=bn(S.text),se=W.some(B=>(B.finalScope??B.inferredScope)?.breadth==="pattern");if(W.length>0&&r.annotationIds&&r.annotationIds.length>0){let B=new Set(r.annotationIds);W.every(te=>B.has(te.annotationId))||(W=W.map((te,ue)=>({...te,annotationId:r.annotationIds[ue%r.annotationIds.length]})))}let ae=S.fileEdits&&S.fileEdits.length>0?S.fileEdits.map(B=>`${B.tool} ${B.file_path.split("/").pop()}`):S.toolsUsed,ce=N.getBufferedEvents(r.id),de=ce?xr(ce.events):void 0;if(r.threadId&&await m.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:S.text,resolutions:W.length>0?W:void 0,question:O??void 0,sessionId:S.sessionId,toolsUsed:ae,editEvents:S.editEvents&&S.editEvents.length>0?S.editEvents:void 0,segments:de&&de.length>0?de:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&A.captureGitDiff(t).then(async B=>{let oe=Date.now(),te=r.imagePaths?Object.values(r.imagePaths).flat():[],ue=[];if(r.imagePaths)for(let[j,M]of Object.entries(r.imagePaths))for(let X=0;X<M.length;X++)ue.push(`screenshots/p-${r.id}-${j}-${X}.webp`);await A.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:oe,durationMs:oe-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:ue,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:d,model:r.model,sessionId:S.sessionId,threadId:r.threadId,responseText:S.text,resolutions:W.length>0?W:[],question:O??void 0,fileEdits:S.fileEdits??[],editEvents:S.editEvents??[],toolsUsed:ae,gitDiff:B},r.screenshotPath,te),se&&d!=="copilot"?await Rt({provider:d,model:r.model,agentSettings:r.agentSettings,threadId:r.threadId,annotationIds:r.annotationIds,sourceId:r.sourceId,reason:`Materialize model \u2014 ${r.feedback.annotations[0]?.instruction??"pattern decision"}`}):se&&console.log(`${R} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&S.text){let B=Ve(S.text);if(B){Array.isArray(B.rules)&&(B.rules=_e(B.rules));let oe=await x.loadModel();oe&&(!B.tokens&&oe.tokens&&(B.tokens=oe.tokens),!B.components&&oe.components&&(B.components=oe.components)),await x.writeModel(B),console.log(`${R} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&S.text){let B=Qt(S.text),oe=Xt(S.text),te=B??oe;if(te&&te.length>0){let ue=await T.writeSynthesized(te),j=r._proposalId;j&&await x.attachGeneratedEvals(j,te.map(M=>M.id)),console.log(`${R} Eval synthesis: wrote ${te.length} ${B?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${ue.cases.length} total)`)}}else if(r.kind==="run_eval"&&S.text&&r.evalId&&r.evalRunId){let B=await T.findCase(r.evalId),oe=r._evalRunScope;if(B&&oe){let te=Yt(S.text,B.assertions),ue=Date.now();await T.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:ue,durationMs:ue-r.createdAt,scope:oe,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:Jn(t),rawResponse:S.text,...te}),console.log(`${R} Eval run: ${B.title} \u2192 ${te.status}`)}}O&&(console.log(`${R} \u{1F4AC} Question detected: "${O.slice(0,120)}" \u2192 broadcasting to ${k.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),N.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:O,annotationIds:r.annotationIds},r.id,r.sourceId));let le=Pn(S.text);le.length>0&&(console.log(`${R} Novel pattern(s): ${le.map(B=>`${B.category}/${B.element}`).join(", ")}`),N.broadcast({type:"novel_patterns",jobId:r.id,patterns:le,threadId:r.threadId},r.id,r.sourceId)),N.broadcast({type:"done",jobId:r.id,success:!0,resolutions:W.length>0?W:void 0,responseText:S.text,threadId:r.threadId},r.id,r.sourceId),Z.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${R} Error: ${S.error}`),r.status="error",r.error=S.error,r.threadId&&await m.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:S.error||"Unknown error",model:r.model,provider:d}),N.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:S.error||"Unknown error",provider:d,model:r.model,recoverable:S.recoverableError,code:S.errorCode},r.id,r.sourceId),Z.push({id:r.id,status:"error",completedAt:Date.now(),error:S.error,threadId:r.threadId,annotationIds:r.annotationIds});z()});let dt=fr(async(r,c)=>{if(Ir(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:${U}`),d=h.pathname,P=kr(r,h);if(P&&P!==o){g(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:at(t)});return}if(r.headers.origin){if(!Fn(r.headers.origin)){g(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(P!==o){g(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:at(t)});return}}try{if(r.method==="POST"&&d==="/send")await Gn(r,c);else if(r.method==="GET"&&d==="/events")Qn(r,c);else if(r.method==="GET"&&d==="/status")await Xn(c,P);else if(r.method==="PATCH"&&d==="/config")await Yn(r,c);else if(r.method==="POST"&&d==="/shutdown"){if(H!=="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:H});return}g(c,200,{ok:!0}),setTimeout(()=>process.exit(0),100)}else if(r.method==="POST"&&d==="/restart"){if(H!=="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:H});return}g(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let y of k)try{y.res.end()}catch{}dt.close(()=>{_n(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 ls(r,c);else if(r.method==="POST"&&d==="/reply")await qn(r,c);else if(r.method==="POST"&&d==="/cancel")Vn(r,c);else if(r.method==="POST"&&d==="/materialize")await Kn(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let y=await x.loadRuns();g(c,200,y)}else if(r.method==="GET"&&d==="/model/proposals"){let y=await x.loadModelProposals();g(c,200,y)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply-selected")){let y=d.slice(17,-15);await es(y,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let y=d.slice(17,-6);await Zn(y,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let y=d.slice(17,-8);await ts(y,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let y=d.slice(17,-14);await ns(y,r,c)}else if(r.method==="POST"&&d==="/model/component")await cs(r,c);else if(r.method==="DELETE"&&d==="/model/component")await ds(r,c);else if(r.method==="PATCH"&&d==="/model/token")await us(r,c);else if(r.method==="DELETE"&&d==="/model/token")await ps(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:y,model:R,agentSettings:I}=await Ie(r);if(y==="copilot"){g(c,400,{error:"Model consolidation is not available for Copilot yet."});return}x.consolidate({provider:y,model:R,agentSettings:I}).catch(C=>console.error("[Bridge] Consolidation error:",C)),g(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await ss(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await os(r,c);else if(r.method==="GET"&&d==="/evals"){let y=await T.loadSuiteWithCurrentRuns(Jn(t));g(c,200,y)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let y=d.slice(7,-4);await rs(y,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await is(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let y=await x.loadModel();g(c,200,{model:y})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let y=d.slice(6,d.length-7),R=parseInt(h.searchParams.get("afterSeq")??"-1",10),I=N.getBufferedEvents(y,isNaN(R)?-1:R);I?g(c,200,I):g(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&p.startsWith("/files/"))await gs(p.slice(7),c);else if(r.method==="GET"&&d==="/threads/recent"){let y=Math.min(Math.max(parseInt(h.searchParams.get("limit")??"5",10)||5,1),20),R=await m.listRecent(y);g(c,200,R)}else if(r.method==="GET"&&d.startsWith("/thread/")){let y=d.slice(8);await ys(y,c)}else if(r.method==="DELETE"&&d.startsWith("/thread/")){let y=d.slice(8);await vs(y,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?fs(r,c):r.method==="GET"&&d==="/canvas/manifest"?await hs(c):r.method==="GET"&&d==="/canvas/app.mjs"?await ms(c):g(c,404,{error:"Not found"})}catch(y){console.error("[Bridge] Request error:",y),g(c,500,{error:y instanceof Error?y.message:"Internal error"})}});async function Gn(r,c){let{screenshot:u,feedback:p,color:h,provider:d,model:P,reasoningEffort:y,serviceTier:R,sourceId:I,pastedImages:C,pageScreenshots:ee}=await tt(r),Q;try{Q=JSON.parse(p)}catch{g(c,400,{error:"Invalid feedback JSON"});return}let S=xe().slice(0,8),O={};if(ee.length>0)for(let M of ee){let X=encodeURIComponent(M.pathname),re=ye(a,`screenshot-${S}-${X}.webp`);await Fe(re,M.data),O[M.pathname]=re}let W=ye(a,`screenshot-${S}.webp`);await Fe(W,u);let se={};if(C.length>0)for(let M of C){let X=ye(a,`pasted-${S}-${M.annotationId}-${M.index}.webp`);await Fe(X,M.data),se[M.annotationId]||(se[M.annotationId]=[]),se[M.annotationId].push(X)}let ae=Q.annotations.map(M=>M.linkedSelector?M.pathname?`${M.pathname}:${M.linkedSelector}`:M.linkedSelector:null).filter(M=>!!M),ce;if(ae.length>0){let M=await m.findContinuationThread(ae);M?(ce=M.id,await m.addElementIdentifiers(ce,ae)):ce=(await m.createThread(S,ae)).id}else ce=(await m.createThread(S,[])).id;let de=Q.annotations.map(M=>M.id),le=Object.keys(O).length>0,B={id:S,status:"queued",screenshotPath:W,feedback:Q,createdAt:Date.now(),color:h,threadId:ce,annotationIds:de,provider:Be(d),model:P||void 0,agentSettings:je({reasoningEffort:y,serviceTier:R}),...Object.keys(se).length>0?{imagePaths:se}:{},sourceId:I||void 0,...le?{screenshotPaths:O}:{}},oe=new Set(Q.annotations.map(M=>M.pathname).filter(Boolean)),te;if(oe.size>1){let M=new Map;for(let X of Q.annotations){let re=X.pathname||"(unknown)";M.has(re)||M.set(re,[]),M.get(re).push(X.instruction||Nn({...Q,annotations:[X]}))}te=[...M.entries()].map(([X,re])=>`\`${X}\`
|
|
407
|
-
${re.map(
|
|
406
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let D=!u&&r.threadId?await y.getThreadHistory(r.threadId):void 0,H=u?null:await G.loadModel();g=u??En(r.screenshotPath,r.feedback,{threadHistory:D&&D.length>0?D:void 0,provider:d,imagePaths:r.imagePaths,designModel:H??void 0,screenshotPaths:r.screenshotPaths})}let b=jr(r.color,`[\u22B9 ${W}:${r.id}]`),I=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${b} Reviewing ${I} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${P?` (resuming: ${P.slice(0,8)})`:""}`);let C=(D,H)=>{D.type==="delta"&&"text"in D?O.accumulateText(H,"response",D.text):D.type==="thinking"&&"text"in D&&O.accumulateText(H,"thinking",D.text),O.broadcast(D,H,r.sourceId)},{process:te,result:X}=d==="codex"?Ye(r.id,{prompt:g,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:P,model:r.model,configOverrides:qe(r.agentSettings),onEvent:C}):d==="copilot"?Vt(r.id,{prompt:g,projectRoot:t,resumeSessionId:P,model:r.model,timeoutMs:J,copilotPath:w.copilot?.path??E,onEvent:C}):Qe(r.id,{prompt:g,projectRoot:t,maxTurns:l,maxBudgetUsd:f,allowedTools:v,claudePath:x,resumeSessionId:P,model:r.model,reasoningEffort:r.agentSettings?.reasoningEffort,timeoutMs:J,onEvent:C});O.setActiveProcess(r.id,te);let S=await X;if(r.result=S.text,S.success){console.log(`${b} Iteration complete`),S.fileEdits&&S.fileEdits.length>0&&console.log(`${b} Captured ${S.fileEdits.length} file edit(s): ${S.fileEdits.map(F=>`${F.tool} ${F.file_path}`).join(", ")}`),S.editEvents&&S.editEvents.length>0&&console.log(`${b} Captured ${S.editEvents.length} edit event(s): ${S.editEvents.map(F=>`${F.operation} ${F.filePath}`).join(", ")}`),r.status="done";let D=Tn(S.text),H=An(S.text),se=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(ne=>F.has(ne.annotationId))||(H=H.map((ne,fe)=>({...ne,annotationId:r.annotationIds[fe%r.annotationIds.length]})))}let ce=S.fileEdits&&S.fileEdits.length>0?S.fileEdits.map(F=>`${F.tool} ${F.file_path.split("/").pop()}`):S.toolsUsed,ue=O.getBufferedEvents(r.id),pe=ue?Dr(ue.events):void 0;if(r.threadId&&await y.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:S.text,resolutions:H.length>0?H:void 0,question:D??void 0,sessionId:S.sessionId,toolsUsed:ce,editEvents:S.editEvents&&S.editEvents.length>0?S.editEvents:void 0,segments:pe&&pe.length>0?pe:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&le.captureGitDiff(t).then(async F=>{let oe=Date.now(),ne=r.imagePaths?Object.values(r.imagePaths).flat():[],fe=[];if(r.imagePaths)for(let[j,R]of Object.entries(r.imagePaths))for(let Y=0;Y<R.length;Y++)fe.push(`screenshots/p-${r.id}-${j}-${Y}.webp`);await le.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:oe,durationMs:oe-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:fe,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:d,model:r.model,sessionId:S.sessionId,threadId:r.threadId,responseText:S.text,resolutions:H.length>0?H:[],question:D??void 0,fileEdits:S.fileEdits??[],editEvents:S.editEvents??[],toolsUsed:ce,gitDiff:F},r.screenshotPath,ne),se&&d!=="copilot"?await Ot({provider:d,model:r.model,agentSettings:r.agentSettings,threadId:r.threadId,annotationIds:r.annotationIds,sourceId:r.sourceId,reason:`Materialize model \u2014 ${r.feedback.annotations[0]?.instruction??"pattern decision"}`}):se&&console.log(`${b} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&S.text){let F=nt(S.text);if(F){Array.isArray(F.rules)&&(F.rules=Ne(F.rules));let oe=await G.loadModel();oe&&(!F.tokens&&oe.tokens&&(F.tokens=oe.tokens),!F.components&&oe.components&&(F.components=oe.components)),await G.writeModel(F),console.log(`${b} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&S.text){let F=nn(S.text),oe=sn(S.text),ne=F??oe;if(ne&&ne.length>0){let fe=await ie.writeSynthesized(ne),j=r._proposalId;j&&await G.attachGeneratedEvals(j,ne.map(R=>R.id)),console.log(`${b} Eval synthesis: wrote ${ne.length} ${F?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${fe.cases.length} total)`)}}else if(r.kind==="run_eval"&&S.text&&r.evalId&&r.evalRunId){let F=await ie.findCase(r.evalId),oe=r._evalRunScope;if(F&&oe){let ne=on(S.text,F.assertions),fe=Date.now();await ie.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:fe,durationMs:fe-r.createdAt,scope:oe,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:Gn(t),rawResponse:S.text,...ne}),console.log(`${b} Eval run: ${F.title} \u2192 ${ne.status}`)}}D&&(console.log(`${b} \u{1F4AC} Question detected: "${D.slice(0,120)}" \u2192 broadcasting to ${ee.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),O.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:D,annotationIds:r.annotationIds},r.id,r.sourceId));let de=Cn(S.text);de.length>0&&(console.log(`${b} Novel pattern(s): ${de.map(F=>`${F.category}/${F.element}`).join(", ")}`),O.broadcast({type:"novel_patterns",jobId:r.id,patterns:de,threadId:r.threadId},r.id,r.sourceId)),O.broadcast({type:"done",jobId:r.id,success:!0,resolutions:H.length>0?H:void 0,responseText:S.text,threadId:r.threadId},r.id,r.sourceId),ve.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${b} Error: ${S.error}`),r.status="error",r.error=S.error,r.threadId&&await y.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:S.error||"Unknown error",model:r.model,provider:d}),O.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:S.error||"Unknown error",provider:d,model:r.model,recoverable:S.recoverableError,code:S.errorCode},r.id,r.sourceId),ve.push({id:r.id,status:"error",completedAt:Date.now(),error:S.error,threadId:r.threadId,annotationIds:r.annotationIds});We()});let gt=kr(async(r,c)=>{if(zr(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:${W}`),d=h.pathname,P=Fr(r,h);if(P&&P!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:ft(t)});return}if(r.headers.origin){if(!Qn(r.headers.origin)){m(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(P!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:ft(t)});return}}try{if(r.method==="POST"&&d==="/send")await ss(r,c);else if(r.method==="GET"&&d==="/events")rs(r,c);else if(r.method==="GET"&&d==="/status")await is(c,P);else if(r.method==="PATCH"&&d==="/config")await as(r,c);else if(r.method==="POST"&&d==="/leases"){if(U!=="detached"){m(c,409,{error:"Bridge leases are only available for detached bridges."});return}try{let g=await Br(r),b=typeof g.leaseId=="string"?g.leaseId.trim():"",I=typeof g.ownerPid=="number"&&Number.isInteger(g.ownerPid)&&g.ownerPid>0?g.ownerPid:void 0;if(!b||b.length>128){m(c,400,{error:"A valid leaseId is required."});return}T();let C=k.acquire(b,I);m(c,201,{ok:!0,lease:C,ttlMs:Un})}catch{m(c,400,{error:"Invalid lease request."})}}else if(d.startsWith("/leases/")&&(r.method==="PATCH"||r.method==="DELETE")){if(U!=="detached"){m(c,409,{error:"Bridge leases are only available for detached bridges."});return}let g="";try{g=decodeURIComponent(d.slice(8))}catch{m(c,400,{error:"Invalid lease id."});return}if(!g){m(c,400,{error:"A lease id is required."});return}if(r.method==="PATCH"){let b=k.heartbeat(g);if(!b){m(c,404,{error:"Lease not found."});return}m(c,200,{ok:!0,lease:b})}else{let b=k.release(g);m(c,b.found?200:404,{ok:b.found}),b.becameEmpty&&_()}}else if(r.method==="POST"&&d==="/shutdown"){if(U!=="detached"){m(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:U});return}m(c,200,{ok:!0}),setTimeout(L,100)}else if(r.method==="POST"&&d==="/restart"){if(U!=="detached"){m(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:U});return}m(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let g of ee)try{g.res.end()}catch{}gt.close(()=>{jn(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")m(c,200,{providers:w});else if(r.method==="POST"&&d==="/mcp/install")await ws(r,c);else if(r.method==="POST"&&d==="/reply")await os(r,c);else if(r.method==="POST"&&d==="/cancel")ls(r,c);else if(r.method==="POST"&&d==="/materialize")await cs(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let g=await G.loadRuns();m(c,200,g)}else if(r.method==="GET"&&d==="/model/proposals"){let g=await G.loadModelProposals();m(c,200,g)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply-selected")){let g=d.slice(17,-15);await us(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let g=d.slice(17,-6);await ds(g,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let g=d.slice(17,-8);await ps(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let g=d.slice(17,-14);await fs(g,r,c)}else if(r.method==="POST"&&d==="/model/component")await Ss(r,c);else if(r.method==="DELETE"&&d==="/model/component")await xs(r,c);else if(r.method==="PATCH"&&d==="/model/token")await bs(r,c);else if(r.method==="DELETE"&&d==="/model/token")await Ps(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:g,model:b,agentSettings:I}=await Me(r);if(g==="copilot"){m(c,400,{error:"Model consolidation is not available for Copilot yet."});return}G.consolidate({provider:g,model:b,agentSettings:I}).catch(C=>console.error("[Bridge] Consolidation error:",C)),m(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await hs(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await ms(r,c);else if(r.method==="GET"&&d==="/evals"){let g=await ie.loadSuiteWithCurrentRuns(Gn(t));m(c,200,g)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let g=d.slice(7,-4);await gs(g,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await ys(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let g=await G.loadModel();m(c,200,{model:g})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let g=d.slice(6,d.length-7),b=parseInt(h.searchParams.get("afterSeq")??"-1",10),I=O.getBufferedEvents(g,isNaN(b)?-1:b);I?m(c,200,I):m(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&p.startsWith("/files/"))await Rs(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),b=await y.listRecent(g);m(c,200,b)}else if(r.method==="GET"&&d.startsWith("/thread/")){let g=d.slice(8);await Es(g,c)}else if(r.method==="DELETE"&&d.startsWith("/thread/")){let g=d.slice(8);await Ts(g,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?Is(r,c):r.method==="GET"&&d==="/canvas/manifest"?await ks(c):r.method==="GET"&&d==="/canvas/app.mjs"?await Ms(c):m(c,404,{error:"Not found"})}catch(g){console.error("[Bridge] Request error:",g),m(c,500,{error:g instanceof Error?g.message:"Internal error"})}});async function ss(r,c){let{screenshot:u,feedback:p,color:h,provider:d,model:P,reasoningEffort:g,serviceTier:b,sourceId:I,pastedImages:C,pageScreenshots:te}=await at(r),X;try{X=JSON.parse(p)}catch{m(c,400,{error:"Invalid feedback JSON"});return}let S=Pe().slice(0,8),D={};if(te.length>0)for(let R of te){let Y=encodeURIComponent(R.pathname),re=ye(a,`screenshot-${S}-${Y}.webp`);await Le(re,R.data),D[R.pathname]=re}let H=ye(a,`screenshot-${S}.webp`);await Le(H,u);let se={};if(C.length>0)for(let R of C){let Y=ye(a,`pasted-${S}-${R.annotationId}-${R.index}.webp`);await Le(Y,R.data),se[R.annotationId]||(se[R.annotationId]=[]),se[R.annotationId].push(Y)}let ce=X.annotations.map(R=>R.linkedSelector?R.pathname?`${R.pathname}:${R.linkedSelector}`:R.linkedSelector:null).filter(R=>!!R),ue;if(ce.length>0){let R=await y.findContinuationThread(ce);R?(ue=R.id,await y.addElementIdentifiers(ue,ce)):ue=(await y.createThread(S,ce)).id}else ue=(await y.createThread(S,[])).id;let pe=X.annotations.map(R=>R.id),de=Object.keys(D).length>0,F={id:S,status:"queued",screenshotPath:H,feedback:X,createdAt:Date.now(),color:h,threadId:ue,annotationIds:pe,provider:Ue(d),model:P||void 0,agentSettings:Re({reasoningEffort:g,serviceTier:b}),...Object.keys(se).length>0?{imagePaths:se}:{},sourceId:I||void 0,...de?{screenshotPaths:D}:{}},oe=new Set(X.annotations.map(R=>R.pathname).filter(Boolean)),ne;if(oe.size>1){let R=new Map;for(let Y of X.annotations){let re=Y.pathname||"(unknown)";R.has(re)||R.set(re,[]),R.get(re).push(Y.instruction||Hn({...X,annotations:[Y]}))}ne=[...R.entries()].map(([Y,re])=>`\`${Y}\`
|
|
407
|
+
${re.map(yt=>`- ${yt}`).join(`
|
|
408
408
|
`)}`).join(`
|
|
409
|
-
`)}else
|
|
409
|
+
`)}else ne=Hn(X);let fe=ze(X,Object.keys(se).length>0?se:void 0);await y.appendMessage(ue,{role:"human",timestamp:Date.now(),jobId:S,screenshotPath:H,...de?{screenshotPaths:D}:{},...Object.keys(se).length>0?{imagePaths:se}:{},annotationIds:pe,feedbackSummary:ne,feedbackContext:fe||void 0});let j=O.enqueue(F);m(c,200,{jobId:S,position:j,threadId:ue})}async function os(r,c){let u=r.headers["content-type"]||"",p,h,d,P,g,b,I,C=[];if(u.includes("multipart/form-data")){let j=await at(r),R=j.feedback?JSON.parse(j.feedback):{};p=R.threadId,h=R.reply,d=R.color,P=R.provider,g=R.model,b=Re(R),I=R.sourceId||j.sourceId;for(let Y of j.pastedImages)C.push(Y.data)}else{let j=[];for await(let re of r)j.push(typeof re=="string"?Buffer.from(re):re);let R=Buffer.concat(j).toString("utf-8"),Y;try{Y=JSON.parse(R)}catch{m(c,400,{error:"Invalid JSON"});return}p=Y.threadId,h=Y.reply,d=Y.color,P=Y.provider,g=Y.model,b=Re(Y),I=Y.sourceId}if(!p||!h){m(c,400,{error:"Missing threadId or reply"});return}if(!await y.getThread(p)){m(c,404,{error:"Thread not found"});return}let X="";{let j=await y.getThreadHistory(p);for(let R=j.length-1;R>=0;R--)if(j[R].screenshotPath){X=j[R].screenshotPath;break}}let S=await vs(p);if(!X&&!S){m(c,400,{error:"No screenshot available"});return}let D=O.hasActiveThread(p),H=D?O.getQueuedThreadJob(p,j=>j._replyText!==void 0||j._replyPrompt!==void 0):null,se=H?.id??Pe().slice(0,8),ce=[],ue=`${se}-${Date.now()}`;for(let j=0;j<C.length;j++){let R=ye(a,`reply-${ue}-${j}.webp`);await Le(R,C[j]),ce.push(R)}await y.appendMessage(p,{role:"human",timestamp:Date.now(),jobId:se,replyToQuestion:h,screenshotPath:X,...D?{queued:!0}:{},...ce.length>0?{replyImagePaths:ce}:{}});let pe=await y.getThreadHistory(p),de=[];for(let j of pe)if(j.annotationIds)for(let R of j.annotationIds)de.includes(R)||de.push(R);let F=Ue(P),oe=Ct(X,pe,F,ce.length>0?ce:void 0);if(H){let j=H,Y=[...j._replyTexts??(j._replyText?[j._replyText]:[]),h],re=[...j._replyImagePaths??[],...ce];j._replyTexts=Y,j._replyText=Wn(Y),j._replyImagePaths=re.length>0?re:void 0,j._replyPrompt=Ct(X,pe,F,re.length>0?re:void 0),j.annotationIds=de.length>0?de:j.annotationIds,j.agentSettings=b??j.agentSettings,m(c,200,{jobId:se,position:1,threadId:p,bundled:!0});return}let ne={id:se,status:"queued",screenshotPath:X,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:d,threadId:p,annotationIds:de.length>0?de:void 0,provider:F,model:g||void 0,agentSettings:b,sourceId:I||void 0};S&&(ne.kind=S),ne._replyPrompt=oe,ne._replyTexts=[h],ne._replyText=Wn([h]),ce.length>0&&(ne._replyImagePaths=ce);let fe=D?O.enqueueNext(ne):O.enqueue(ne);m(c,200,{jobId:se,position:fe,threadId:p})}function rs(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 p=new URL(r.url||"/",`http://127.0.0.1:${
|
|
412
|
+
`);let p=new URL(r.url||"/",`http://127.0.0.1:${W}`).searchParams.get("sourceId")||void 0,h={id:Pe().slice(0,8),res:c,sourceId:p};ee.add(h),r.on("close",()=>{ee.delete(h)})}async function is(r,c){let u=[...O.allActive,...A.allActive.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds??[],color:"#000000",kind:"materialize_model",standalone:d.standalone}))],[p,h]=await Promise.all([G.loadRuns(),G.loadModelProposals()]);m(r,200,{ok:!0,version:Fn,restartMode:U,projectId:o,projectName:ft(t),projectRoot:t,requestProjectId:c,projectIdVerified:c===o,devOrigin:i,activeJob:u[0]?{id:u[0].id,status:u[0].status}:null,activeJobs:u.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:O.depth+A.depth,materializerQueueDepth:A.depth,leases:{active:k.isActivated,count:k.size,nextExpiryAt:k.nextExpiryAt,shutdownPending:$},materialization:{activeJob:A.active?{id:A.active.id,status:A.active.status,threadId:A.active.threadId,annotationIds:A.active.annotationIds??[],provider:A.active.provider,model:A.active.model}:null,queueDepth:A.depth,recentRuns:[...p.runs].sort((d,P)=>(P.completedAt??P.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:ve})}async function as(r,c){let u=await new Promise(p=>{let h="";r.on("data",d=>{h+=d.toString()}),r.on("end",()=>p(h))});try{let p=JSON.parse(u);typeof p.devOrigin=="string"&&(i=p.devOrigin||null),m(c,200,{ok:!0,devOrigin:i})}catch{m(c,400,{error:"Invalid JSON"})}}async function ls(r,c){let p=new URL(r.url||"/",`http://127.0.0.1:${W}`).searchParams.get("jobId"),h=p?O.allActive.filter(C=>C.id===p):O.allActive,d=p?A.allActive.filter(C=>C.id===p):A.allActive,P=[...h.map(C=>C.threadId),...d.map(C=>C.threadId)].filter(Boolean),g=p?O.cancelJob(p):O.cancelActive(),b=p?A.cancelJob(p):A.cancelActive(),I=!!(g||b);for(let C of P)await y.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:p||b?.id||"",cancelled:!0});m(c,200,{cancelled:I})}async function Ot(r){let c=Pe().slice(0,8),u=r.threadId,p=!u;u||(u=(await y.createThread(c,[])).id,we.set(u,"materialize_model")),p&&await y.appendMessage(u,{role:"human",timestamp:Date.now(),jobId:c,feedbackSummary:r.reason}),await y.appendMessage(u,{role:"assistant",timestamp:Date.now(),jobId:c,responseText:p?"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,agentSettings:r.agentSettings,threadId:u,annotationIds:r.annotationIds,sourceId:r.sourceId,standalone:p},d=A.enqueue(h);return{jobId:c,position:d,threadId:u}}async function cs(r,c){if(A.isRunning){m(c,200,{skipped:!0,reason:"Already running"});return}let{provider:u,model:p,agentSettings:h}=await Me(r);if(u==="copilot"){m(c,400,{error:"Materialization is not available for Copilot yet."});return}let d=await G.getUnmaterializedPatternDecisions();if(d.length===0){m(c,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}let P=await Ot({provider:u,model:p,agentSettings:h,reason:"Materialize model \u2014 promote pattern decisions into the local taste model"});m(c,200,{started:!0,decisionCount:d.length,decisionIds:d.map(g=>g.id),...P})}async function ds(r,c){let u=decodeURIComponent(r),p=await G.applyModelProposal(u);if(!p){m(c,404,{error:"Model proposal not found"});return}p.threadId&&await y.appendMessage(p.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${p.id}`,responseText:`Model proposal applied.
|
|
413
413
|
|
|
414
414
|
${p.title}
|
|
415
|
-
${p.summary}`}),
|
|
415
|
+
${p.summary}`}),m(c,200,{proposal:p})}async function us(r,c,u){let p=decodeURIComponent(r),h=[];for await(let I of c)h.push(typeof I=="string"?Buffer.from(I):I);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{m(u,400,{error:"Invalid JSON"});return}let P=(d.changes??[]).flatMap(I=>{if(!Array.isArray(I.path)||I.path.length===0)return[];let C=I.path.filter(te=>typeof te=="string"||typeof te=="number");return C.length!==I.path.length?[]:[{path:C,value:I.value,remove:I.remove===!0}]});if(P.length===0){m(u,400,{error:"No selected model changes"});return}let g=(d.changeSummaries??[]).flatMap(I=>{if(!I||typeof I!="object")return[];let C=Array.isArray(I.path)?I.path.filter(te=>typeof te=="string"||typeof te=="number"):void 0;return Array.isArray(I.path)&&C?.length!==I.path.length?[]:[{group:typeof I.group=="string"?I.group:void 0,label:typeof I.label=="string"?I.label:void 0,detail:typeof I.detail=="string"?I.detail:void 0,path:C,value:I.value,currentValue:I.currentValue}]}),b=await G.applySelectedModelProposal(p,P,g);if(!b){m(u,404,{error:"Model proposal not found"});return}if(b.threadId){let I=Ue(d.provider),C=typeof d.model=="string"&&d.model?d.model:void 0;await y.appendMessage(b.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${b.id}`,responseText:`Model proposal applied with ${P.length} selected change${P.length===1?"":"s"}.
|
|
416
416
|
|
|
417
|
-
${
|
|
417
|
+
${b.title}`,provider:I,model:C})}m(u,200,{proposal:b})}async function ps(r,c,u){let p=decodeURIComponent(r),{provider:h,model:d}=await Me(c),P=await G.dismissModelProposal(p);if(!P){m(u,404,{error:"Model proposal not found"});return}P.threadId&&await y.appendMessage(P.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${P.id}`,responseText:`Model proposal dismissed.
|
|
418
418
|
|
|
419
|
-
${P.title}`,provider:h,model:d}),
|
|
420
|
-
`)});let
|
|
421
|
-
`)});let re={id:
|
|
422
|
-
`)}async function
|
|
419
|
+
${P.title}`,provider:h,model:d}),m(u,200,{proposal:P})}async function fs(r,c,u){let p=decodeURIComponent(r),h=await G.findModelProposal(p);if(!h){m(u,404,{error:"Model proposal not found"});return}if(h.status!=="applied"){m(u,400,{error:"Only applied model proposals can be projected into evals"});return}let{provider:d,model:P,agentSettings:g}=await Me(c),b=d??h.provider??B;if(b==="copilot"){m(u,400,{error:"Eval projection is not available for Copilot yet."});return}let I=await G.loadModel(),C=await ie.loadSuite(),te=cn({proposal:h,currentModel:I,existingSuite:C}),X=Pe().slice(0,8),S=h.threadId??(await y.createThread(X,[])).id;we.set(S,"synthesize_evals"),await y.appendMessage(S,{role:"human",timestamp:Date.now(),jobId:X,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 D={id:X,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:S,kind:"synthesize_evals",provider:b,model:P??h.model,agentSettings:g};D._replyPrompt=te,D._proposalId=h.id;let H=O.enqueue(D);m(u,200,{jobId:X,position:H,threadId:S})}async function Me(r){try{let c=[];for await(let p of r)c.push(typeof p=="string"?Buffer.from(p):p);if(c.length===0)return{};let u=JSON.parse(Buffer.concat(c).toString());return{provider:Ue(typeof u.provider=="string"?u.provider:void 0),model:typeof u.model=="string"&&u.model?u.model:void 0,agentSettings:Re(u)}}catch{return{}}}async function hs(r,c){let u=await G.loadModel();if(!u){m(c,400,{error:"No model exists yet"});return}let{provider:p,model:h,agentSettings:d}=await Me(r);if(p==="copilot"){m(c,400,{error:"Rule synthesis is not available for Copilot yet."});return}let P=hn(u),g=Pe().slice(0,8),I=(await y.createThread(g,[])).id;we.set(I,"synthesize"),await y.appendMessage(I,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let C={id:g,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:I,kind:"synthesize",provider:p,model:h,agentSettings:d};C._replyPrompt=P;let te=O.enqueue(C);m(c,200,{jobId:g,position:te,threadId:I})}async function ms(r,c){let{provider:u,model:p,agentSettings:h}=await Me(r);if(u==="copilot"){m(c,400,{error:"Eval synthesis is not available for Copilot yet."});return}let d=await le.listDecisionIds(),P=await le.loadDecisions(d),g=await y.load(),b=await G.loadModel(),I=await ie.loadSuite(),C=an({decisions:P,threads:g,model:b,existingSuite:I}),te=Pe().slice(0,8),S=(await y.createThread(te,[])).id;we.set(S,"synthesize_evals"),await y.appendMessage(S,{role:"human",timestamp:Date.now(),jobId:te,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let D={id:te,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:S,kind:"synthesize_evals",provider:u,model:p||void 0,agentSettings:h};D._replyPrompt=C;let H=O.enqueue(D);m(c,200,{jobId:te,position:H,threadId:S})}async function gs(r,c,u){let p=decodeURIComponent(r),h=await ie.findCase(p);if(!h){m(u,404,{error:"Eval not found"});return}if(h.status!=="approved"){m(u,400,{error:"Only approved evals can be run"});return}let{screenshot:d,feedback:P,provider:g,model:b,reasoningEffort:I,serviceTier:C,sourceId:te}=await at(c),X=Ue(g)??B;if(X==="copilot"){m(u,400,{error:"Eval runs are not available for Copilot yet."});return}let S={};try{S=P?JSON.parse(P):{}}catch{m(u,400,{error:"Invalid eval run context JSON"});return}let D=Pe().slice(0,8),H=Pe().slice(0,8),se=ye(a,`eval-run-${D}.webp`);await Le(se,d);let ce=await ie.writeRunScreenshot(D,d),ue=S.viewport,pe=ue&&typeof ue=="object"?ue:{},de={type:"current_page",url:typeof S.url=="string"?S.url:"",viewport:{width:typeof pe.width=="number"?pe.width:0,height:typeof pe.height=="number"?pe.height:0}},F=await G.loadModel(),oe=X==="claude"?Q.name:X==="codex"?K.name:null,ne=X==="codex"?Z.length>0:typeof oe=="string"&&/chrome|devtools/i.test(oe),fe=ln({evalCase:h,scope:de,model:F,screenshotPath:se,chromeDevtoolsAvailable:ne}),R=(await y.createThread(H,[])).id;we.set(R,"run_eval");let Y={timestamp:new Date().toISOString(),url:de.url,viewport:de.viewport,scrollPosition:{x:typeof S.scrollX=="number"?S.scrollX:0,y:typeof S.scrollY=="number"?S.scrollY:0},annotations:[],styleModifications:[]};await y.appendMessage(R,{role:"human",timestamp:Date.now(),jobId:H,screenshotPath:se,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${de.url||"unknown"}`,"Assertions:",...h.assertions.map(Cs=>`- ${Cs}`)].join(`
|
|
421
|
+
`)});let re={id:H,status:"queued",screenshotPath:se,feedback:Y,createdAt:Date.now(),color:"#111827",threadId:R,kind:"run_eval",evalId:p,evalRunId:D,provider:X,model:b||void 0,agentSettings:Re({reasoningEffort:I,serviceTier:C}),sourceId:te||void 0};re._replyPrompt=fe,re._evalRunScope=de,re._evalScreenshotPath=ce;let yt=O.enqueue(re);m(u,200,{jobId:H,runId:D,position:yt,threadId:R,screenshotPath:ce})}async function ys(r,c,u){let p=decodeURIComponent(r),h={},d,P,g;try{let I=[];for await(let te of c)I.push(typeof te=="string"?Buffer.from(te):te);let C=JSON.parse(Buffer.concat(I).toString());d=C.status,P=C.title,g=C.assertions}catch{m(u,400,{error:"Invalid JSON"});return}if(d!==void 0&&d!=="pending"&&d!=="approved"&&d!=="rejected"){m(u,400,{error:"Invalid status"});return}if(d&&(h.status=d),P!==void 0){if(typeof P!="string"||P.trim().length===0){m(u,400,{error:"Invalid title"});return}h.title=P.trim()}if(g!==void 0){if(!Array.isArray(g)){m(u,400,{error:"Invalid assertions"});return}let I=g.filter(C=>typeof C=="string").map(C=>C.trim()).filter(Boolean);if(I.length===0){m(u,400,{error:"Invalid assertions"});return}h.assertions=I}if(!h.status&&!h.title&&!h.assertions){m(u,400,{error:"No eval changes provided"});return}let b=await ie.updateCase(p,h);if(!b){m(u,404,{error:"Eval not found"});return}m(u,200,{eval:b})}async function vs(r){let c=we.get(r);if(c)return c;let h=(await y.getThread(r))?.messages.find(d=>d.role==="human")?.feedbackSummary??"";if(h.startsWith("Synthesize evals"))return we.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return we.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return we.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return we.set(r,"materialize_model"),"materialize_model"}async function ws(r,c){let u=[];for await(let b of r)u.push(typeof b=="string"?Buffer.from(b):b);let p;if(u.length>0)try{p=JSON.parse(Buffer.concat(u).toString("utf-8")).serverUrl}catch{}let h=[];w.claude?.available&&w.claude.mcp&&!w.claude.mcp.found&&h.push(await kn(p)),w.codex?.available&&w.codex.mcp&&!w.codex.mcp.found&&h.push(await Mn(p)),w.copilot?.available&&w.copilot.mcp&&!w.copilot.mcp.found&&h.push(await Rn(p,w.copilot.path??E));let[d,P,g]=await Promise.all([Mt(t),Rt(t),Et(t,w.copilot?.path??E)]);w.claude&&(w.claude.mcp=d),w.codex&&(w.codex.mcp=P),w.copilot&&(w.copilot.mcp=g),m(c,200,{results:h,capabilities:{providers:w}})}async function Ss(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let h=await G.addComponent(p.name);m(c,200,h)}async function xs(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let h=await G.removeComponent(p.name);m(c,200,h)}async function bs(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"||typeof p.value!="string"){m(c,400,{error:"Missing or invalid path/value"});return}let h=await G.updateToken(p.path,p.value);m(c,200,h)}async function Ps(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"){m(c,400,{error:"Missing or invalid path"});return}let h=await G.removeToken(p.path);m(c,200,h)}function Is(r,c){let u=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")&&(u=d.origin)}catch{}}let p=zt(W,u);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(p)}async function ks(r){let c=Date.now();if(He&&c<He.expires){m(r,200,He.data);return}try{let{scanForComponents:u}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:p}=await import("./render-generator-HWFLZYC3.mjs"),h=await u(t);He={data:h,expires:c+5e3},p(h,t,_t).then(d=>{_t=d}).catch(d=>console.warn("[Bridge] Render generation failed:",d)),m(r,200,h)}catch(u){console.error("[Bridge] Scanner error:",u),m(r,500,{error:"Failed to scan components"})}}async function Ms(r){let c=[ye(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ye(t,"packages","popmelt","dist","canvas.mjs")];try{let u=Er(import.meta.url);c.unshift(ye(Rr(u),"canvas.mjs"))}catch{}for(let u of c)try{let p=await Ln(u,"utf-8");r.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),r.end(p);return}catch{}console.error("[Bridge] Canvas bundle not found in:",c),m(r,404,{error:"Canvas bundle not found"})}async function Rs(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){m(c,400,{error:"Invalid filename"});return}try{let u=await Ln(ye(a,r)),p=r.split(".").pop()?.toLowerCase(),h=p==="png"?"image/png":p==="webp"?"image/webp":p==="jpg"||p==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":h,"Cache-Control":"public, max-age=3600"}),c.end(u)}catch{m(c,404,{error:"File not found"})}}function Ge(r){return`/files/${ft(r)}`}async function Es(r,c){let u=await y.getThread(r);if(!u){m(c,404,{error:"Thread not found"});return}let p=(await ie.loadRuns()).runs.filter(b=>b.threadId===r).sort((b,I)=>I.completedAt-b.completedAt)[0],h=p?await ie.findCase(p.evalId):null,d=await G.findModelProposalsByThread(r),P=[...d].sort((b,I)=>I.updatedAt-b.updatedAt)[0]??null,g=u.messages.map(({screenshotPath:b,screenshotPaths:I,imagePaths:C,replyImagePaths:te,...X})=>({...X,...X.role==="assistant"&&p?{evalRun:{...p,title:h?.title}}:{},...b?{screenshotUrl:Ge(b)}:{},...I?{screenshotUrls:Object.fromEntries(Object.entries(I).map(([S,D])=>[S,Ge(D)]))}:{},...C?{imageUrls:Object.fromEntries(Object.entries(C).map(([S,D])=>[S,D.map(Ge)]))}:{},...te?{replyImageUrls:te.map(Ge)}:{}}));m(c,200,{id:u.id,createdAt:u.createdAt,messages:g,modelProposal:P,modelProposals:d})}async function Ts(r,c){let u=decodeURIComponent(r);if(!await y.deleteThread(u)){m(c,404,{deleted:!1,error:"Thread not found"});return}m(c,200,{deleted:!0})}let Dt=9,Nt=!1;for(let r=e;r<e+Dt;r++)try{await Ur(gt,r),W=r,Nt=!0,console.log(`[\u22B9 is watching :${W}]`);break}catch(c){if(c.code==="EADDRINUSE"){let u=await Lr(r);if(u&&u.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!Nt)throw new Error(`[Bridge] All ports ${e}\u2013${e+Dt-1} in use`);for(let[r,c]of Object.entries(w))!c.available||!c.path||V(r,c.path).then(u=>{if(u)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 p of ee)ht(p,{type:"capabilities_changed",data:{}})}});let As=setInterval(()=>{qn(a).catch(()=>{})},Cr),Jt=setInterval(()=>{k.expireStale().becameEmpty&&_()},_r);return Jt.unref?.(),{port:W,projectId:o,close:async()=>{clearInterval(As),clearInterval(Jt),T(),k.clear(),await O.destroyAsync(),A.destroy();for(let r of ee)try{r.res.end()}catch{}return ee.clear(),new Promise(r=>{gt.close(()=>r())})}}}async function qn(s){try{let e=await xr(s),n=Date.now();for(let t of e){let o=ye(s,t);try{let i=await Pr(o);n-i.mtimeMs>$r&&await Ir(o)}catch{}}}catch{}}var qr=parseInt(process.env.POPMELT_PORT||"1111",10),Vn=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Qr=process.env.POPMELT_DEV_ORIGIN||void 0,Xr=process.env.POPMELT_COPILOT_PATH||void 0,Kn=Yn(Vn,".popmelt"),Zn=Yn(Kn,"bridge.lock");async function Yr(s){await Wr(Kn,{recursive:!0}),await Gr(Zn,JSON.stringify({pid:process.pid,port:s,startedAt:Date.now()})+`
|
|
422
|
+
`)}async function es(){try{await Hr(Zn)}catch{}}async function Vr(){let s=await Xn({port:qr,projectRoot:Vn,devOrigin:Qr,copilotPath:Xr,restartMode:"detached"});await Yr(s.port),await new Promise(e=>{let n=!1,t=async()=>{n||(n=!0,await s.close(),await es(),e(),process.exit(0))};process.on("SIGTERM",t),process.on("SIGINT",t)})}Vr().catch(s=>{console.error("[popmelt bridge-entry] Fatal:",s),es().finally(()=>process.exit(1))});
|