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