@popmelt.com/core 0.5.22 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,127 +0,0 @@
1
- import{a as q,b as se,c as tt,d as ce}from"./chunk-3HWT3PC2.mjs";import{execFileSync as en,spawn as tn}from"child_process";import{createHash as nn,randomUUID as Le}from"crypto";import{mkdir as sn,readFile as on,readdir as rn,stat as an,unlink as cn,writeFile as ze}from"fs/promises";import{createServer as ln}from"http";import{tmpdir as dn}from"os";import{dirname as un,join as re}from"path";import{fileURLToPath as pn}from"url";function nt(r,t){return`<!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8">
5
- <title>Popmelt Canvas</title>
6
- <link rel="preconnect" href="https://fonts.googleapis.com">
7
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
8
- <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
9
- <style>*{margin:0;padding:0;box-sizing:border-box}html,body,#root{height:100%;overflow:hidden}</style>
10
- </head>
11
- <body>
12
- <div id="root"></div>
13
- <script type="importmap">
14
- {"imports":{
15
- "react":"https://esm.sh/react@19?dev",
16
- "react-dom/client":"https://esm.sh/react-dom@19/client?dev",
17
- "react/jsx-runtime":"https://esm.sh/react@19/jsx-runtime?dev"
18
- }}
19
- </script>
20
- <script type="module">
21
- import { mountCanvas } from 'http://localhost:${r}/canvas/app.mjs';
22
- mountCanvas(document.getElementById('root'), {
23
- devOrigin: '${t}',
24
- bridgeOrigin: 'http://localhost:${r}',
25
- });
26
- </script>
27
- </body>
28
- </html>`}import{spawn as Mt}from"child_process";import{createInterface as Ct}from"readline";function be(r,t){let{prompt:e,projectRoot:n,maxTurns:s=40,maxBudgetUsd:a=1,allowedTools:l=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:i="claude",resumeSessionId:u,model:h,timeoutMs:A=3e5,onEvent:T}=t,k=[];u?k.push("--resume",u,"-p",e):k.push("-p",e),k.push("--output-format","stream-json","--verbose","--max-turns",String(s),"--max-budget-usd",String(a)),h&&k.push("--model",h);for(let B of l)k.push("--allowedTools",B);let f=Mt(i,k,{cwd:n,stdio:["ignore","pipe","pipe"],env:se(q({},process.env),{ANTHROPIC_API_KEY:void 0})}),L=new Promise(B=>{var z;let J,w=[],U=[],$=!1,F="",H=!1,O=setTimeout(()=>{H=!0,f.kill("SIGTERM"),setTimeout(()=>{try{f.kill("SIGKILL")}catch(S){}},5e3)},A),Z=Ct({input:f.stdout}),v=new Set;Z.on("line",S=>{var Q,de,ge,ye,we,ve,Se,Ie,xe;if(S.trim())try{let W=JSON.parse(S);W.session_id&&!J&&(J=W.session_id);let Ee=(de=W.type)!=null?de:(Q=W.event)!=null&&Q.type?`event.${W.event.type}`:"unknown";if(v.add(Ee),W.type==="result"&&W.result&&w.length===0){let M=typeof W.result=="string"?W.result:"";M&&(w.push(M),T==null||T({type:"delta",jobId:r,text:M},r))}if(W.type==="assistant"&&Array.isArray((ge=W.message)==null?void 0:ge.content))for(let M of W.message.content){if(M.type==="text"&&M.text&&(w.push(M.text),T==null||T({type:"delta",jobId:r,text:M.text},r)),M.type==="tool_use"&&M.name){let Pe=((ye=M.input)==null?void 0:ye.file_path)||((we=M.input)==null?void 0:we.path)||void 0;T==null||T(q({type:"tool_use",jobId:r,tool:M.name},Pe?{file:Pe}:{}),r),M.name==="Edit"&&((ve=M.input)!=null&&ve.file_path)?U.push({tool:"Edit",file_path:M.input.file_path,old_string:M.input.old_string,new_string:M.input.new_string,replace_all:M.input.replace_all}):M.name==="Write"&&((Se=M.input)!=null&&Se.file_path)&&U.push({tool:"Write",file_path:M.input.file_path,content:M.input.content})}M.type==="thinking"&&M.thinking&&(T==null||T({type:"thinking",jobId:r,text:M.thinking},r))}W.type==="user"&&((xe=(Ie=W.tool_use_result)==null?void 0:Ie.file)!=null&&xe.filePath)&&(T==null||T({type:"tool_use",jobId:r,tool:"Read",file:W.tool_use_result.file.filePath},r))}catch(W){}});let g=[];(z=f.stderr)==null||z.on("data",S=>{g.push(S.toString())}),f.on("close",S=>{clearTimeout(O),Z.close(),w.length===0&&v.size>0&&console.warn(`[Claude:${r}] No text captured. Event types seen: ${[...v].join(", ")}`),H?($=!0,F=`Timed out after ${Math.round(A/6e4)} minutes`):S!==0&&S!==null&&($=!0,F=g.join("")||`Claude process exited with code ${S}`),B({sessionId:J,text:w.join(""),success:!$,error:$?F:void 0,fileEdits:U.length>0?U:void 0})}),f.on("error",S=>{clearTimeout(O),$=!0,F=S.message,B({sessionId:J,text:w.join(""),success:!1,error:F,fileEdits:U.length>0?U:void 0})})});return{process:f,result:L}}import{spawn as Et}from"child_process";import{createInterface as Ot}from"readline";function st(r,t){let{prompt:e,projectRoot:n,screenshotPath:s,resumeSessionId:a,model:l,onEvent:i}=t,u=[];a?(u.push("exec","resume",a),l&&u.push("-m",l),u.push("--json","--full-auto",e),s&&u.push("--image",s)):(u.push("exec","--json","--full-auto"),l&&u.push("-m",l),u.push(e),s&&u.push("--image",s));let h=Et("codex",u,{cwd:n,stdio:["ignore","pipe","pipe"],env:q({},process.env)}),A=new Promise(T=>{var $;let k,f=[],L=!1,B="",J=Ot({input:h.stdout}),w=new Set;J.on("line",F=>{var H,O,Z,v;if(F.trim())try{let g=JSON.parse(F),z=(H=g.type)!=null?H:"unknown";if(w.add(z),z==="thread.started"&&g.thread_id&&!k&&(k=g.thread_id),(z==="item.agentMessage.delta"||z==="item/agentMessage/delta")&&((O=g.delta)!=null&&O.text)&&(f.push(g.delta.text),i==null||i({type:"delta",jobId:r,text:g.delta.text},r)),(z==="item.reasoning.delta"||z==="item/reasoning/delta")&&((Z=g.delta)!=null&&Z.text)&&(i==null||i({type:"thinking",jobId:r,text:g.delta.text},r)),(z==="item.started"||z==="item/started")&&g.item){let S=g.item.type;if(S==="command_execution")i==null||i({type:"tool_use",jobId:r,tool:"Bash"},r);else if(S==="file_change"){let Q=g.item.filename||g.item.path;i==null||i(q({type:"tool_use",jobId:r,tool:"Edit"},Q?{file:Q}:{}),r)}else if(S==="file_read"){let Q=g.item.filename||g.item.path;i==null||i(q({type:"tool_use",jobId:r,tool:"Read"},Q?{file:Q}:{}),r)}else if(S==="web_search")i==null||i({type:"tool_use",jobId:r,tool:"WebSearch"},r);else if(S==="mcp_tool_call"){let Q=g.item.tool_name||g.item.name||"MCP";i==null||i({type:"tool_use",jobId:r,tool:Q},r)}}if((z==="item.completed"||z==="item/completed")&&g.item){if(g.item.type==="agent_message"){let S=g.item.text;typeof S=="string"&&S&&(f.push(S),i==null||i({type:"delta",jobId:r,text:S},r))}else if(g.item.type==="reasoning"){let S=g.item.text;typeof S=="string"&&S&&(i==null||i({type:"thinking",jobId:r,text:S},r))}}z==="turn.failed"&&(L=!0,B=((v=g.error)==null?void 0:v.message)||g.message||"Turn failed")}catch(g){}});let U=[];($=h.stderr)==null||$.on("data",F=>{U.push(F.toString())}),h.on("close",F=>{J.close(),f.length===0&&w.size>0&&console.warn(`[Codex:${r}] No text captured. Event types seen: ${[...w].join(", ")}`),F!==0&&F!==null&&(L=!0,B=U.join("")||`Codex process exited with code ${F}`),T({sessionId:k,text:f.join(""),success:!L,error:L?B:void 0})}),h.on("error",F=>{L=!0,B=F.message,T({sessionId:k,text:f.join(""),success:!1,error:B})})});return{process:h,result:A}}import{execFile as Dt}from"child_process";import{copyFile as ot,mkdir as rt,readdir as At,readFile as _t,writeFile as Nt}from"fs/promises";import{join as le}from"path";var ke=class{constructor(t){this.projectRoot=t;let e=le(t,".popmelt");this.decisionsDir=le(e,"decisions"),this.screenshotsDir=le(e,"screenshots")}async persist(t,e,n){try{await rt(this.decisionsDir,{recursive:!0}),await rt(this.screenshotsDir,{recursive:!0});try{await ot(e,le(this.screenshotsDir,`s-${t.id}.png`))}catch(s){}for(let s=0;s<n.length;s++)try{let a=t.pastedImagePaths[s];a&&await ot(n[s],le(this.screenshotsDir,a.replace("screenshots/","")))}catch(a){}await Nt(le(this.decisionsDir,`d-${t.id}.json`),JSON.stringify(t,null,2))}catch(s){console.error("[DecisionStore] Failed to persist decision record:",s)}}async listDecisionIds(){try{return(await At(this.decisionsDir)).filter(e=>e.startsWith("d-")&&e.endsWith(".json")).map(e=>e.slice(2,-5))}catch(t){return[]}}async loadDecision(t){try{let e=await _t(le(this.decisionsDir,`d-${t}.json`),"utf-8");return JSON.parse(e)}catch(e){return null}}async loadDecisions(t){return(await Promise.all(t.map(n=>this.loadDecision(n)))).filter(n=>n!==null)}captureGitDiff(t){return new Promise(e=>{Dt("git",["diff","HEAD"],{cwd:t,timeout:5e3,maxBuffer:1024*1024},(n,s)=>{if(n){e(null);return}e(s||null)})})}};import{readFile as it,writeFile as he}from"fs/promises";import{join as De}from"path";var ne="[Materializer]",Jt={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Te=class{constructor(t,e,n={}){this.projectRoot=t;this.decisionStore=e;this.options=n;this.cachedIndex=null;this.running=!1;let s=De(t,".popmelt");this.indexPath=De(s,"materialized.json"),this.modelPath=De(s,"model.json")}get isRunning(){return this.running}async loadModel(){try{let t=await it(this.modelPath,"utf-8");return JSON.parse(t)}catch(t){return null}}async addComponent(t){let e=await this.loadModel();e||(e={tokens:{},components:{},rules:[]}),(!e.components||typeof e.components!="object")&&(e.components={});let n=e.components;return n[t]?{added:!1,alreadyExists:!0}:(n[t]={description:""},await he(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ne} Added component "${t}" to model`),{added:!0,alreadyExists:!1})}async updateToken(t,e){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]});let s=t.split("."),a=n;for(let u=0;u<s.length-1;u++){let h=s[u];(!a[h]||typeof a[h]!="object")&&(a[h]={}),a=a[h]}let l=s[s.length-1],i;try{i=JSON.parse(e)}catch(u){i=null}if(i&&typeof i=="object"&&i!==null&&"value"in i)a[l]=i;else{let u=a[l];u&&typeof u=="object"&&u!==null&&"value"in u?u.value=e:a[l]=e}return await he(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ne} Updated token "${t}" \u2192 "${e.slice(0,80)}"`),{updated:!0}}async removeToken(t){let e=await this.loadModel();if(!e)return{removed:!1};let n=t.split("."),s=e;for(let l=0;l<n.length-1;l++){let i=n[l];if(!s[i]||typeof s[i]!="object")return{removed:!1};s=s[i]}let a=n[n.length-1];return a in s?(delete s[a],await he(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ne} Removed token "${t}" from model`),{removed:!0}):{removed:!1}}async removeComponent(t){let e=await this.loadModel();if(!e)return{removed:!1};let n=e.components;return!n||!n[t]?{removed:!1}:(delete n[t],await he(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ne} Removed component "${t}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let t=await this.loadIndex(),e=new Set(t.materializedIds),s=(await this.decisionStore.listDecisionIds()).filter(l=>!e.has(l));return s.length===0?[]:(await this.decisionStore.loadDecisions(s)).filter(l=>l.resolutions.some(i=>{var h;let u=(h=i.finalScope)!=null?h:i.inferredScope;return(u==null?void 0:u.breadth)==="pattern"}))}async run(){var t,e,n,s,a,l,i;if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;try{let u=await this.getUnmaterializedPatternDecisions();if(u.length===0)return{processedIds:[],success:!0};let h=u.map(J=>J.id);console.log(`${ne} Processing ${h.length} pattern-scoped decision(s): ${h.join(", ")}`),(e=(t=this.options).onEvent)==null||e.call(t,{type:"materialize_started",decisionIds:h});let A=await this.loadModel(),T=Ut(u,A),k=!0,f;try{let{result:J}=be(`mat-${Date.now()}`,{prompt:T,projectRoot:this.projectRoot,maxTurns:(n=this.options.maxTurns)!=null?n:5,maxBudgetUsd:(s=this.options.maxBudgetUsd)!=null?s:.5,allowedTools:["Read"],claudePath:(a=this.options.claudePath)!=null?a:"claude"}),w=await J;if(!w.success)k=!1,f=w.error,console.error(`${ne} Claude spawn error:`,f);else{let U=Bt(w.text);U?(await he(this.modelPath,JSON.stringify(U,null,2)),console.log(`${ne} Successfully materialized ${h.length} decision(s) \u2192 ${this.modelPath}`)):(k=!1,f="No <model> block found in response",console.error(`${ne} ${f}`))}}catch(J){k=!1,f=J instanceof Error?J.message:String(J),console.error(`${ne} Error:`,f)}let L=await this.loadIndex(),B=new Set(L.materializedIds);for(let J of h)B.add(J);return L.materializedIds=[...B],L.lastRunAt=Date.now(),L.lastRunDecisionIds=h,L.lastRunError=f!=null?f:null,await this.persistIndex(L),(i=(l=this.options).onEvent)==null||i.call(l,{type:"materialize_done",decisionIds:h,success:k,error:f}),{processedIds:h,success:k,error:f}}finally{this.running=!1}}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let t=await it(this.indexPath,"utf-8"),e=JSON.parse(t);return this.cachedIndex=e,e}catch(t){return this.cachedIndex=se(q({},Jt),{materializedIds:[],lastRunDecisionIds:[]}),this.cachedIndex}}async persistIndex(t){this.cachedIndex=t;try{await he(this.indexPath,JSON.stringify(t,null,2))}catch(e){console.error(`${ne} Failed to write index:`,e)}}};function Bt(r){let t=r.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!(t!=null&&t[1]))return null;try{let e=JSON.parse(t[1]);return typeof e!="object"||e===null||Array.isArray(e)?null:e}catch(e){return null}}function Ut(r,t){let e=r.map(s=>{let l=s.resolutions.filter(h=>{var T;let A=(T=h.finalScope)!=null?T:h.inferredScope;return(A==null?void 0:A.breadth)==="pattern"}).map(h=>{var f,L,B,J;let A=(f=h.finalScope)!=null?f:h.inferredScope,T=(L=A==null?void 0:A.target)!=null?L:"unknown",k=(J=(B=h.filesModified)==null?void 0:B.join(", "))!=null?J:"none";return`- **${h.summary}** [scope: pattern/${T}]
29
- Files modified: ${k}`}).join(`
30
- `),i=s.annotations.map(h=>h.instruction).filter(Boolean).join(`
31
- `),u=s.gitDiff?`
32
- \`\`\`diff
33
- ${s.gitDiff.slice(0,2e3)}
34
- \`\`\``:"";return`### Decision ${s.id} (${new Date(s.createdAt).toISOString()})
35
- Page: ${s.url}
36
- ${l}
37
- ${u}
38
- ${i?`
39
- Original instructions:
40
- ${i}`:""}`}).join(`
41
-
42
- `);return`You are extracting a local design model from accumulated design decisions.
43
-
44
- ## Instructions
45
- 1. Review the current model (if any) and the new decisions below.
46
- 2. Determine what design tokens, component patterns, and rules to add or update.
47
- 3. Output the complete updated model as a JSON object inside <model> tags.
48
-
49
- ${t?`## Current Model
50
- \`\`\`json
51
- ${JSON.stringify(t,null,2)}
52
- \`\`\`
53
-
54
- Merge the new decisions into the existing model. Preserve existing entries that are not contradicted by new decisions.`:"No model exists yet. Create one from scratch based on the decisions below."}
55
-
56
- ## Design Decisions to Materialize
57
- ${e}
58
-
59
- ## Output Format
60
- Output the full model inside <model> tags. The model is a JSON object with these sections:
61
- - \`tokens\`: Design tokens (colors, spacing, typography, etc.)
62
- - \`components\`: Component-level patterns (e.g., button styles, card layouts)
63
- - \`rules\`: Array of plain-language rules extracted from decisions
64
-
65
- Example:
66
- <model>
67
- {
68
- "tokens": {
69
- "colors": { "primary": "#3b82f6" },
70
- "spacing": {
71
- "sm": "4px",
72
- "md": "8px",
73
- "section-gap": { "value": "32px", "property": "gap", "bindings": ["gap-8"] }
74
- }
75
- },
76
- "components": {
77
- "button": { "padding": "12px 24px", "borderRadius": "8px" }
78
- },
79
- "rules": [
80
- "Buttons use 12px vertical padding and 24px horizontal padding",
81
- "Primary actions use the primary color"
82
- ]
83
- }
84
- </model>
85
-
86
- ## Guidelines
87
- - Map token-scoped decisions to \`tokens\`, component-scoped to \`components\`.
88
- - Extract clear, enforceable rules into the \`rules\` array.
89
- - When merging, new decisions override conflicting older values.
90
- - Keep the model concise \u2014 only include patterns with clear evidence from decisions.
91
- - Do NOT output resolution or question blocks. Just output the <model> block.
92
- - Spacing tokens can be plain strings ("8px") or objects with code bindings:
93
- { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
94
- - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
95
- - bindings: Tailwind class names (without responsive prefixes) that use this token
96
- Include property and bindings when the decision context has class-level evidence.`}import{readFile as lt}from"fs/promises";import{homedir as dt}from"os";import{join as fe}from"path";var _e=/popmelt/i;function Ne(){return{found:!1,name:null,scope:null,disabled:!1}}function me(r,t,e=!1){return{found:!0,name:r,scope:t,disabled:e}}function Re(r){for(let t of Object.keys(r))if(_e.test(t))return t;return null}async function Ae(r){try{let t=await lt(r,"utf-8");return JSON.parse(t)}catch(t){return null}}async function Je(r){let t=dt(),e=await Ae(fe(t,".claude.json"));if(e&&typeof e=="object"){let s=e;if(s.mcpServers&&typeof s.mcpServers=="object"){let a=Re(s.mcpServers);if(a)return me(a,"user")}if(s.projects&&typeof s.projects=="object"){let l=s.projects[r];if(l&&typeof l=="object"){let i=l;if(i.mcpServers&&typeof i.mcpServers=="object"){let u=Re(i.mcpServers);if(u){let h=Array.isArray(i.disabledMcpjsonServers)&&i.disabledMcpjsonServers.some(A=>_e.test(A));return me(u,"project",h)}}}}}let n=await Ae(fe(r,".mcp.json"));if(n&&typeof n=="object"){let s=n;if(s.mcpServers&&typeof s.mcpServers=="object"){let l=Re(s.mcpServers);if(l){let i=await at(r,l);return me(l,"mcp.json",i)}}let a=Re(s);if(a&&a!=="mcpServers"){let l=await at(r,a);return me(a,"mcp.json",l)}}return Ne()}async function at(r,t){let e=fe(r,".claude","settings.local.json"),n=await Ae(e);if(n&&typeof n=="object"){let s=n;if(Array.isArray(s.disabledMcpjsonServers))return s.disabledMcpjsonServers.some(a=>a===t)}return!1}var Ft=/^\[mcp_servers\.([^\]]+)\]/;function Lt(r){let t=r.split(`
97
- `),e=[],n=null;for(let s of t){let a=s.match(Ft);a?(n&&e.push({name:n.name,body:n.bodyLines.join(`
98
- `)}),n={name:a[1],bodyLines:[]}):s.startsWith("[")?n&&(e.push({name:n.name,body:n.bodyLines.join(`
99
- `)}),n=null):n&&n.bodyLines.push(s)}return n&&e.push({name:n.name,body:n.bodyLines.join(`
100
- `)}),e}function zt(r){return/enabled\s*=\s*false/i.test(r)}async function Be(r){let t=process.env.CODEX_HOME||fe(dt(),".codex"),e=await ct(fe(t,"config.toml"),"user");if(e.found)return e;let n=await ct(fe(r,".codex","config.toml"),"project");return n.found?n:Ne()}async function ct(r,t){try{let e=await lt(r,"utf-8"),n=Lt(e);for(let s of n)if(_e.test(s.name)){let a=zt(s.body);return me(s.name,t,a)}}catch(e){}return Ne()}import{mkdir as Ht,readFile as ut,writeFile as pt}from"fs/promises";import{homedir as ht}from"os";import{dirname as jt,join as Ue}from"path";var ft="https://mcp.popmelt.com/mcp";async function mt(r=ft){let t=Ue(ht(),".claude.json"),e;try{let s=await ut(t,"utf-8");e=JSON.parse(s)}catch(s){e={}}(!e.mcpServers||typeof e.mcpServers!="object")&&(e.mcpServers={});let n=e.mcpServers;for(let s of Object.keys(n))if(/popmelt/i.test(s))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:r},await pt(t,JSON.stringify(e,null,2)+`
101
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function gt(r=ft){let t=process.env.CODEX_HOME||Ue(ht(),".codex"),e=Ue(t,"config.toml"),n;try{n=await ut(e,"utf-8")}catch(a){n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Ht(jt(e),{recursive:!0});let s=`
102
- [mcp_servers.popmelt]
103
- url = "${r}"
104
- `;return await pt(e,n+s,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Fe(r){let e=(r.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!e)throw new Error("Missing multipart boundary");let n=e[1]||e[2],s=await Gt(r),a=Buffer.from(`--${n}`),l=Buffer.from(`--${n}--`),i,u,h,A,T,k,f,L,B,J,w,U,$=[],F=0,H=[];for(;F<s.length;){let O=s.indexOf(a,F);if(O===-1)break;let Z=O+a.length;if(s.slice(O,O+l.length).equals(l))break;let v=Z;s[v]===13&&s[v+1]===10&&(v+=2);let g=s.indexOf(`\r
105
- \r
106
- `,v);if(g===-1)break;let z=s.slice(v,g).toString("utf-8"),S=g+4,Q=s.indexOf(a,S),de=Q!==-1?Q-2:s.length;H.push({headers:z,body:s.slice(S,de)}),F=Q!==-1?Q:s.length}for(let O of H){let Z=O.headers.match(/name="([^"]+)"/);if(!Z)continue;let v=Z[1];if(v==="screenshot")i=O.body;else if(v==="feedback")u=O.body.toString("utf-8");else if(v==="color")h=O.body.toString("utf-8");else if(v==="provider")A=O.body.toString("utf-8");else if(v==="model")T=O.body.toString("utf-8");else if(v==="goal")k=O.body.toString("utf-8");else if(v==="pageUrl")f=O.body.toString("utf-8");else if(v==="viewport")L=O.body.toString("utf-8");else if(v==="planId")B=O.body.toString("utf-8");else if(v==="manifest")J=O.body.toString("utf-8");else if(v==="tasks")w=O.body.toString("utf-8");else if(v==="sourceId")U=O.body.toString("utf-8");else if(v.startsWith("image-")){let g=v.split("-"),z=parseInt(g[g.length-1],10),S=g.slice(1,-1).join("-");S&&!isNaN(z)&&$.push({annotationId:S,index:z,data:O.body})}}if(!i)throw new Error("Missing screenshot field");return u||(u=""),{screenshot:i,feedback:u,color:h,provider:A,model:T,goal:k,pageUrl:f,viewport:L,planId:B,manifest:J,tasks:w,sourceId:U,pastedImages:$}}function Gt(r){return new Promise((t,e)=>{let n=[];r.on("data",s=>n.push(s)),r.on("end",()=>t(Buffer.concat(n))),r.on("error",e)})}function $e(r,t){var n,s;let e=[];if(r.annotations.length>0){e.push("## Annotations");for(let a of r.annotations){let l=a.elements.map(h=>{let A=[h.selector];return h.reactComponent&&A.push(`(${h.reactComponent})`),A.join(" ")}).join(", "),i=a.instruction||"No text";e.push(`- id=${a.id} [${a.type}] ${i} \u2192 Elements: ${l||"none"}`);let u=t==null?void 0:t[a.id];if(u&&u.length>0)for(let h of u)e.push(` Attached image: use the Read tool to view ${h}`)}}if(r.styleModifications.length>0){e.push(""),e.push("## Style Changes (make permanent in source)"),e.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 a of r.styleModifications){let l=(n=a.element)!=null&&n.reactComponent?`(${a.element.reactComponent})`:"";for(let i of a.changes)e.push(`- ${a.selector} ${l}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if((s=r.spacingTokenChanges)!=null&&s.length){e.push(""),e.push("## Spacing Token Changes"),e.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let a of r.spacingTokenChanges){e.push(`
107
- ### ${a.tokenName}: ${a.originalPx}px \u2192 ${a.newPx}px`);for(let l of a.affectedElements){let i=l.reactComponent?` (${l.reactComponent})`:"";l.matchedClass&&l.suggestedClass?e.push(`- ${l.selector}${i}: \`${l.matchedClass}\` \u2192 \`${l.suggestedClass}\``):e.push(`- ${l.selector}${i}: ${l.property} ${a.originalPx}px \u2192 ${a.newPx}px`),e.push(` class="${l.className}"`)}}}if(r.inspectedElement){let a=r.inspectedElement;e.push(""),e.push("## Inspected Element"),e.push("The developer has this element selected in the inspector:");let l=[a.selector];a.reactComponent&&l.push(`(${a.reactComponent})`),a.context&&l.push(`in ${a.context}`),a.textContent&&l.push(`"${a.textContent.slice(0,80)}"`),e.push(`- ${l.join(" ")}`)}return e.join(`
108
- `)}function yt(r,t,e){var a;let n=[];if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),(e==null?void 0:e.provider)!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),n.push("")),n.push(`The developer annotated their running app at ${t.url} (${t.viewport.width}x${t.viewport.height}).`),e!=null&&e.threadHistory&&e.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let l=0;for(let i of e.threadHistory)if(i.role==="human")l++,i.replyToQuestion?(n.push(`### Round ${l} (human) \u2014 reply`),n.push(`"${i.replyToQuestion}"`)):(n.push(`### Round ${l} (human)`),i.feedbackSummary&&n.push(`Annotations: ${i.feedbackSummary}`),i.annotationIds&&i.annotationIds.length>0&&n.push(`Annotation IDs: ${i.annotationIds.join(", ")}`));else if(i.question)n.push(`### Round ${l} (assistant) \u2014 question`),n.push(`"${i.question}"`);else{if(n.push(`### Round ${l} (assistant)`),i.responseText&&n.push(`Response: ${i.responseText}`),i.resolutions&&i.resolutions.length>0)for(let u of i.resolutions){let h=(a=u.finalScope)!=null?a:u.inferredScope,A=h?` [${h.breadth} ${h.target}]`:"";n.push(`- ${u.annotationId}: ${u.status}${A} \u2014 ${u.summary}`),u.filesModified&&u.filesModified.length>0&&n.push(` Files: ${u.filesModified.join(", ")}`)}i.toolsUsed&&i.toolsUsed.length>0&&n.push(`Tools used: ${i.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(e!=null&&e.designModel){n.push(""),n.push("## Established Design Policies"),n.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let l=e.designModel.rules;if(Array.isArray(l)&&l.length>0){n.push(""),n.push("Rules:");for(let h of l)typeof h=="string"&&n.push(`- ${h}`)}let i=e.designModel.tokens;i&&typeof i=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(i,null,2)),n.push("```"));let u=e.designModel.components;u&&typeof u=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(u,null,2)),n.push("```")),n.push(""),n.push("### Novel Pattern Detection"),n.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:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you decided to do (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}e!=null&&e.designModel||(n.push(""),n.push("## Design Context"),n.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."));let s=$e(t,e==null?void 0:e.imagePaths);return s&&(n.push(""),n.push(s)),n.push(""),n.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."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output a resolution block listing what you did for each annotation:"),n.push("<resolution>"),n.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),n.push("</resolution>"),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
109
- `)}function wt(r){var e;let t=r.match(/<question>\s*([\s\S]*?)\s*<\/question>/);return(e=t==null?void 0:t[1])!=null?e:null}function vt(r,t,e,n){let s=[];s.push("You are continuing work on a UI based on the developer's reply to your question."),s.push(""),e!=="codex"&&s.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`);let a=t.find(l=>l.role==="human"&&l.feedbackContext);if(a!=null&&a.feedbackContext&&(s.push(""),s.push(a.feedbackContext)),t.length>0){s.push(""),s.push("## Conversation History");let l=0;for(let i of t)i.role==="human"?(l++,i.replyToQuestion?(s.push(`### Round ${l} (human) \u2014 reply`),s.push(`"${i.replyToQuestion}"`)):(s.push(`### Round ${l} (human)`),i.feedbackSummary&&s.push(`Annotations: ${i.feedbackSummary}`))):i.question?(s.push(`### Round ${l} (assistant) \u2014 question`),s.push(`"${i.question}"`)):(s.push(`### Round ${l} (assistant)`),i.responseText&&s.push(`Response: ${i.responseText}`))}if(s.push(""),s.push("The developer answered your question. Continue working based on their reply."),s.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),s.push(""),s.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n&&n.length>0){s.push(""),s.push("## Attached Images"),s.push("The developer attached reference images with their reply:");for(let l of n)s.push(`Attached image: use the Read tool to view the image at: ${l}`)}return s.push(""),s.push("## Resolution"),s.push("After completing all work, output a resolution block listing what you did for each annotation:"),s.push("<resolution>"),s.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),s.push("</resolution>"),s.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),s.push(""),s.push("### Scope classification"),s.push("Each resolution MUST include scope fields:"),s.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),s.push("- `inferredScope`: What scope the change actually has, based on what you modified."),s.push("Scope has two dimensions:"),s.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),s.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),s.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),s.push("If you cannot confidently determine scope, set it to null."),s.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.'),s.push(""),s.push("## Questions"),s.push("If you still need clarification, output:"),s.push("<question>Your question here</question>"),s.push("You may output BOTH a <resolution> and a <question> in the same response."),s.join(`
110
- `)}function Wt(r){if(typeof r!="object"||r===null)return!1;let t=r;return(t.breadth==="instance"||t.breadth==="pattern")&&(t.target==="element"||t.target==="component"||t.target==="token")}function Qt(r){if(typeof r!="object"||r===null||typeof r.annotationId!="string"||r.status!=="resolved"&&r.status!=="needs_review"||typeof r.summary!="string")return!1;let t=r;for(let e of["declaredScope","inferredScope","finalScope"])if(t[e]!==void 0&&t[e]!==null&&!Wt(t[e]))return!1;return!0}function St(r){let t=r.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!t||!t[1])return[];try{let e=JSON.parse(t[1]);return Array.isArray(e)?e.filter(Qt):[]}catch(e){return[]}}function It(r){let t=r.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!(t!=null&&t[1]))return[];try{let e=JSON.parse(t[1]);return Array.isArray(e)?e.filter(n=>{if(typeof n!="object"||n===null)return!1;let s=n;return(s.category==="token"||s.category==="component"||s.category==="element")&&typeof s.element=="string"&&typeof s.decision=="string"&&typeof s.reason=="string"}):[]}catch(e){return[]}}var Me=class{constructor(t=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.maxConcurrency=t}setProcessor(t){this.processor=t}get active(){let t=this.activeJobs.values().next();return t.done?null:t.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(t,e){e?this.activeProcesses.set(t,e):this.activeProcesses.delete(t)}enqueue(t){return this.queue.push(t),this.processNext(),this.queue.length+this.activeJobs.size}addListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}broadcast(t,e,n){for(let s of this.listeners)s(t,e,n)}cancelJob(t){let e=this.activeProcesses.get(t),n=this.activeJobs.get(t);return!e||!n?!1:(e.kill("SIGTERM"),this.activeProcesses.delete(t),this.activeJobs.delete(t),n.status="error",n.error="Cancelled by user",this.broadcast({type:"error",jobId:n.id,message:"Cancelled by user",cancelled:!0},n.id,n.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let t=Array.from(this.activeJobs.keys());for(let e of t)this.cancelJob(e);return!0}destroy(){for(let t of this.activeProcesses.values())t.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear()}async destroyAsync(t=1e4){let e=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),e.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let n of e)try{n.kill("SIGTERM")}catch(s){}await Promise.all(e.map(n=>new Promise(s=>{let a=!1,l=()=>{a||(a=!0,s())};n.on("exit",l),n.on("error",l),setTimeout(()=>{if(!a){try{n.kill("SIGKILL")}catch(i){}setTimeout(l,500)}},t)}))),this.activeProcesses.clear(),this.activeJobs.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let t=this.queue.shift();this.activeJobs.set(t.id,t),t.status="running",this.broadcast({type:"job_started",jobId:t.id,position:0,threadId:t.threadId},t.id,t.sourceId),this.processor(t).catch(e=>{t.status="error",t.error=e instanceof Error?e.message:String(e),this.broadcast({type:"error",jobId:t.id,message:t.error},t.id,t.sourceId)}).finally(()=>{this.activeJobs.delete(t.id),this.activeProcesses.delete(t.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id)})}}};import{mkdir as Yt,readFile as qt,writeFile as Xt}from"fs/promises";import{dirname as Kt,join as Vt}from"path";var Zt={version:1,threads:{}},Ce=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=Vt(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await qt(this.filePath,"utf-8"),e=JSON.parse(t);if(e&&e.version===1&&e.threads)return this.cache=e,this.cache}catch(t){}return this.cache=se(q({},Zt),{threads:{}}),this.cache}async getThread(t){var n;return(n=(await this.load()).threads[t])!=null?n:null}async findContinuationThread(t){if(t.length===0)return null;let e=await this.load(),n=new Set(t);for(let s of Object.values(e.threads))if(s.elementIdentifiers.some(l=>n.has(l)))return s;return null}async createThread(t,e){let n=await this.load(),s={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:e,messages:[]};return n.threads[t]=s,await this.persist(),s}async appendMessage(t,e){let s=(await this.load()).threads[t];s&&(s.messages.push(e),s.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,e){let s=(await this.load()).threads[t];if(!s)return;let a=new Set(s.elementIdentifiers);for(let l of e)a.has(l)||s.elementIdentifiers.push(l);s.updatedAt=Date.now(),await this.persist()}async getThreadHistory(t,e=6){let n=await this.getThread(t);return!n||n.messages.length===0?[]:n.messages.length<=e?n.messages:[n.messages[0],...n.messages.slice(-(e-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await Yt(Kt(this.filePath),{recursive:!0}),await Xt(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var In={};var hn=1111,fn=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],mn=1800*1e3,gn=3600*1e3;function Pt(r){if(!r)return!1;try{let t=new URL(r);return t.hostname==="localhost"||t.hostname==="127.0.0.1"}catch(t){return!1}}function yn(r,t){let e=r.headers.origin;Pt(e)&&(t.setHeader("Access-Control-Allow-Origin",e),t.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type"))}function I(r,t,e){r.writeHead(t,{"Content-Type":"application/json"}),r.end(JSON.stringify(e))}function wn(r,t){if(!r)return t;let e=r.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!e)return t;let[,n,s,a]=e;return`\x1B[38;2;${parseInt(n,16)};${parseInt(s,16)};${parseInt(a,16)}m${t}\x1B[0m`}function He(r,t){try{r.res.write(`event: ${t.type}
111
- data: ${JSON.stringify(t)}
112
-
113
- `)}catch(e){}}async function vn(r){try{let t=new AbortController,e=setTimeout(()=>t.abort(),500),n=await fetch(`http://127.0.0.1:${r}/status`,{signal:t.signal});return clearTimeout(e),n.ok?await n.json():null}catch(t){return null}}function Sn(r,t){return new Promise((e,n)=>{let s=l=>{r.removeListener("listening",a),n(l)},a=()=>{r.removeListener("error",s),e()};r.once("error",s),r.once("listening",a),r.listen(t,"127.0.0.1")})}async function bt(r={}){var We,Qe,Ye,qe,Xe,Ke,Ve,Ze,et;let t=(We=r.port)!=null?We:hn,e=(Qe=r.projectRoot)!=null?Qe:process.cwd(),n=nn("sha256").update(e).digest("hex").slice(0,12),s=(Ye=r.devOrigin)!=null?Ye:process.env.PORT?`http://localhost:${process.env.PORT}`:null,a=(qe=r.tempDir)!=null?qe:re(dn(),"popmelt-bridge"),l=(Xe=r.maxTurns)!=null?Xe:40,i=(Ke=r.maxBudgetUsd)!=null?Ke:1,u=[...(Ve=r.allowedTools)!=null?Ve:fn],h=(Ze=r.claudePath)!=null?Ze:"claude",A=(et=r.provider)!=null?et:"claude",T=r.timeoutMs,k=t,f={};for(let o of["claude","codex"])try{let c=en("which",[o],{encoding:"utf-8"}).trim();f[o]={available:!0,path:c}}catch(c){f[o]={available:!1,path:null}}function L(o,c){return new Promise(p=>{let d=tn(c,["--version"],{stdio:["ignore","ignore","ignore"]}),m=!1,y=N=>{m||(m=!0,p(N))},_=setTimeout(()=>{d.kill("SIGTERM"),y(!0)},5e3);d.on("error",()=>{clearTimeout(_),y(!1)}),d.on("close",N=>{clearTimeout(_),y(N===0)})})}let[B,J]=await Promise.all([Je(e),Be(e)]);f.claude&&(f.claude.mcp=B),f.codex&&(f.codex.mcp=J),B.found&&B.name&&u.push(`mcp__${B.name}__*`),await sn(a,{recursive:!0}),xt(a).catch(()=>{});let w=new Me(1),U=new Set,$=new Ce(e),F=new ke(e),H=new Te(e,F,{claudePath:h,onEvent:o=>{for(let c of U)He(c,o)}}),O=20,Z=300*1e3,v=[],g=null,z;w.addListener((o,c,p)=>{for(let d of U)(!p||!d.sourceId||d.sourceId===p)&&He(d,o)}),w.setProcessor(async o=>{var j,G,V,te,ie,ue;let c=o._replyPrompt,p=o._replyImagePaths,d=(j=o.provider)!=null?j:A,m;if(o.threadId){let b=await $.getThread(o.threadId);if(b){for(let C=b.messages.length-1;C>=0;C--)if(b.messages[C].sessionId){m=b.messages[C].sessionId;break}}}let y;if(m&&c){let b=(G=await $.getThread(o.threadId))==null?void 0:G.messages.filter(E=>E.role==="human").pop();if(y=(b==null?void 0:b.replyToQuestion)||(b==null?void 0:b.feedbackSummary)||"",p&&p.length>0){y+=`
114
-
115
- The developer attached reference images with their reply:`;for(let E of p)y+=`
116
- Attached image: use the Read tool to view the image at: ${E}`}y+=`
117
-
118
- After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(m)y=$e(o.feedback,o.imagePaths)+`
119
-
120
- Follow the developer's instructions. If they ask for changes, apply them to the source files.
121
-
122
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
123
-
124
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${o.screenshotPath}`:"");else{let b=!c&&o.threadId?await $.getThreadHistory(o.threadId):void 0,C=c?null:await H.loadModel();y=c!=null?c:yt(o.screenshotPath,o.feedback,{threadHistory:b&&b.length>0?b:void 0,provider:d,imagePaths:o.imagePaths,designModel:C!=null?C:void 0})}let _=wn(o.color,`[\u22B9 ${k}:${o.id}]`);console.log(`${_} Reviewing feedback ${o.screenshotPath} (provider: ${d})${o.threadId?` (thread: ${o.threadId})`:""}${m?` (resuming: ${m.slice(0,8)})`:""}`);let N=(b,C)=>{w.broadcast(b,C,o.sourceId)},{process:X,result:x}=d==="codex"?st(o.id,{prompt:y,projectRoot:e,screenshotPath:o.screenshotPath,resumeSessionId:m,model:o.model,onEvent:N}):be(o.id,{prompt:y,projectRoot:e,maxTurns:l,maxBudgetUsd:i,allowedTools:u,claudePath:h,resumeSessionId:m,model:o.model,timeoutMs:T,onEvent:N});w.setActiveProcess(o.id,X);let P=await x;if(o.result=P.text,P.success){console.log(`${_} Iteration complete`),P.fileEdits&&P.fileEdits.length>0&&console.log(`${_} Captured ${P.fileEdits.length} file edit(s): ${P.fileEdits.map(Y=>`${Y.tool} ${Y.file_path}`).join(", ")}`),o.status="done";let b=wt(P.text),C=St(P.text);if(C.length>0&&o.annotationIds&&o.annotationIds.length>0){let Y=new Set(o.annotationIds);C.every(R=>Y.has(R.annotationId))||(C=C.map((R,D)=>se(q({},R),{annotationId:o.annotationIds[D%o.annotationIds.length]})))}let E=P.fileEdits&&P.fileEdits.length>0?P.fileEdits.map(Y=>`${Y.tool} ${Y.file_path.split("/").pop()}`):void 0;o.threadId&&await $.appendMessage(o.threadId,{role:"assistant",timestamp:Date.now(),jobId:o.id,responseText:P.text,resolutions:C.length>0?C:void 0,question:b!=null?b:void 0,sessionId:P.sessionId,toolsUsed:E,model:o.model,provider:o.provider}),F.captureGitDiff(e).then(async Y=>{var ee;let ae=Date.now(),R=o.imagePaths?Object.values(o.imagePaths).flat():[],D=[];if(o.imagePaths)for(let[pe,$t]of Object.entries(o.imagePaths))for(let Oe=0;Oe<$t.length;Oe++)D.push(`screenshots/p-${o.id}-${pe}-${Oe}.png`);await F.persist({version:1,id:o.id,createdAt:o.createdAt,completedAt:ae,durationMs:ae-o.createdAt,url:o.feedback.url,viewport:o.feedback.viewport,screenshotPath:`screenshots/s-${o.id}.png`,pastedImagePaths:D,annotations:o.feedback.annotations,styleModifications:o.feedback.styleModifications,inspectedElement:o.feedback.inspectedElement,provider:o.provider,model:o.model,sessionId:P.sessionId,threadId:o.threadId,responseText:P.text,resolutions:C.length>0?C:[],question:b!=null?b:void 0,fileEdits:(ee=P.fileEdits)!=null?ee:[],toolsUsed:E,gitDiff:Y},o.screenshotPath,R)}).catch(()=>{}),C.length>0&&C.some(ae=>{var D;let R=(D=ae.finalScope)!=null?D:ae.inferredScope;return(R==null?void 0:R.breadth)==="pattern"})&&H.run().catch(()=>{}),b&&(console.log(`${_} \u{1F4AC} Question detected: "${b.slice(0,120)}" \u2192 broadcasting to ${U.size} SSE clients (threadId=${(V=o.threadId)!=null?V:o.id}, annotationIds=${(ie=(te=o.annotationIds)==null?void 0:te.join(","))!=null?ie:"none"})`),w.broadcast({type:"question",jobId:o.id,threadId:(ue=o.threadId)!=null?ue:o.id,question:b,annotationIds:o.annotationIds},o.id,o.sourceId));let oe=It(P.text);oe.length>0&&(console.log(`${_} Novel pattern(s): ${oe.map(Y=>`${Y.category}/${Y.element}`).join(", ")}`),w.broadcast({type:"novel_patterns",jobId:o.id,patterns:oe,threadId:o.threadId},o.id,o.sourceId)),w.broadcast({type:"done",jobId:o.id,success:!0,resolutions:C.length>0?C:void 0,responseText:P.text,threadId:o.threadId},o.id,o.sourceId),v.push({id:o.id,status:"done",completedAt:Date.now(),threadId:o.threadId})}else console.error(`${_} Error: ${P.error}`),o.status="error",o.error=P.error,o.threadId&&await $.appendMessage(o.threadId,{role:"assistant",timestamp:Date.now(),jobId:o.id,error:P.error||"Unknown error",model:o.model,provider:o.provider}),w.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:P.error||"Unknown error"},o.id,o.sourceId),v.push({id:o.id,status:"error",completedAt:Date.now(),error:P.error,threadId:o.threadId});let K=Date.now()-Z;for(;v.length>0&&(v[0].completedAt<K||v.length>O);)v.shift()});let S=ln(async(o,c)=>{if(yn(o,c),o.method==="OPTIONS"){c.writeHead(204),c.end();return}let d=new URL(o.url||"/",`http://127.0.0.1:${k}`).pathname;try{if(o.method==="POST"&&d==="/send")await Q(o,c);else if(o.method==="GET"&&d==="/events")ge(o,c);else if(o.method==="GET"&&d==="/status")ye(c);else if(o.method==="GET"&&d==="/capabilities")I(c,200,{providers:f});else if(o.method==="POST"&&d==="/mcp/install")await Se(o,c);else if(o.method==="POST"&&d==="/reply")await de(o,c);else if(o.method==="POST"&&d==="/cancel")we(o,c);else if(o.method==="POST"&&d==="/materialize")await ve(c);else if(o.method==="POST"&&d==="/model/component")await Ie(o,c);else if(o.method==="DELETE"&&d==="/model/component")await xe(o,c);else if(o.method==="PATCH"&&d==="/model/token")await W(o,c);else if(o.method==="DELETE"&&d==="/model/token")await Ee(o,c);else if(o.method==="GET"&&d==="/model"){let m=await H.loadModel();I(c,200,{model:m})}else if(o.method==="GET"&&d.startsWith("/thread/")){let m=d.slice(8);await Tt(m,c)}else o.method==="GET"&&(d==="/canvas"||d==="/canvas/")?M(o,c):o.method==="GET"&&d==="/canvas/manifest"?await Pe(c):o.method==="GET"&&d==="/canvas/app.mjs"?await kt(c):I(c,404,{error:"Not found"})}catch(m){console.error("[Bridge] Request error:",m),I(c,500,{error:m instanceof Error?m.message:"Internal error"})}});async function Q(o,c){let{screenshot:p,feedback:d,color:m,provider:y,model:_,sourceId:N,pastedImages:X}=await Fe(o),x;try{x=JSON.parse(d)}catch(E){I(c,400,{error:"Invalid feedback JSON"});return}let P=Le().slice(0,8),K=re(a,`screenshot-${P}.png`);await ze(K,p);let j={};if(X.length>0)for(let E of X){let oe=re(a,`pasted-${P}-${E.annotationId}-${E.index}.png`);await ze(oe,E.data),j[E.annotationId]||(j[E.annotationId]=[]),j[E.annotationId].push(oe)}let G=x.annotations.map(E=>E.linkedSelector).filter(E=>!!E),V;if(G.length>0){let E=await $.findContinuationThread(G);E?(V=E.id,await $.addElementIdentifiers(V,G)):V=(await $.createThread(P,G)).id}else V=(await $.createThread(P,[])).id;let te=x.annotations.map(E=>E.id),ie=se(q({id:P,status:"queued",screenshotPath:K,feedback:x,createdAt:Date.now(),color:m,threadId:V,annotationIds:te,provider:y==="claude"||y==="codex"?y:void 0,model:_||void 0},Object.keys(j).length>0?{imagePaths:j}:{}),{sourceId:N||void 0}),ue=x.annotations.map(E=>E.instruction||`[${E.type}]`).join("; "),b=$e(x,Object.keys(j).length>0?j:void 0);await $.appendMessage(V,{role:"human",timestamp:Date.now(),jobId:P,screenshotPath:K,annotationIds:te,feedbackSummary:ue,feedbackContext:b||void 0});let C=w.enqueue(ie);I(c,200,{jobId:P,position:C,threadId:V})}async function de(o,c){let p=o.headers["content-type"]||"",d,m,y,_,N,X,x=[];if(p.includes("multipart/form-data")){let R=await Fe(o),D=R.feedback?JSON.parse(R.feedback):{};d=D.threadId,m=D.reply,y=D.color,_=D.provider,N=D.model,X=D.sourceId||R.sourceId;for(let ee of R.pastedImages)x.push(ee.data)}else{let R=[];try{for(var E=ce(o),oe,Y,ae;oe=!(Y=await E.next()).done;oe=!1){let pe=Y.value;R.push(typeof pe=="string"?Buffer.from(pe):pe)}}catch(Y){ae=[Y]}finally{try{oe&&(Y=E.return)&&await Y.call(E)}finally{if(ae)throw ae[0]}}let D=Buffer.concat(R).toString("utf-8"),ee;try{ee=JSON.parse(D)}catch(pe){I(c,400,{error:"Invalid JSON"});return}d=ee.threadId,m=ee.reply,y=ee.color,_=ee.provider,N=ee.model,X=ee.sourceId}if(!d||!m){I(c,400,{error:"Missing threadId or reply"});return}if(!await $.getThread(d)){I(c,404,{error:"Thread not found"});return}let K=Le().slice(0,8),j=[];for(let R=0;R<x.length;R++){let D=re(a,`reply-${K}-${R}.png`);await ze(D,x[R]),j.push(D)}let G="";{let R=await $.getThreadHistory(d);for(let D=R.length-1;D>=0;D--)if(R[D].screenshotPath){G=R[D].screenshotPath;break}}if(!G){I(c,400,{error:"No screenshot available"});return}await $.appendMessage(d,{role:"human",timestamp:Date.now(),jobId:K,replyToQuestion:m,screenshotPath:G});let V=await $.getThreadHistory(d),te=[];for(let R of V)if(R.annotationIds)for(let D of R.annotationIds)te.includes(D)||te.push(D);let ie=_==="claude"||_==="codex"?_:void 0,ue=vt(G,V,ie,j.length>0?j:void 0),b={id:K,status:"queued",screenshotPath:G,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:y,threadId:d,annotationIds:te.length>0?te:void 0,provider:ie,model:N||void 0,sourceId:X||void 0};b._replyPrompt=ue,j.length>0&&(b._replyImagePaths=j);let C=w.enqueue(b);I(c,200,{jobId:K,position:C,threadId:d})}function ge(o,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
125
- data: {"status":"connected"}
126
-
127
- `),!s&&o.headers.origin&&Pt(o.headers.origin)&&(s=o.headers.origin);let d=new URL(o.url||"/",`http://127.0.0.1:${k}`).searchParams.get("sourceId")||void 0,m={id:Le().slice(0,8),res:c,sourceId:d};U.add(m),o.on("close",()=>{U.delete(m)})}function ye(o){let c=w.allActive;I(o,200,{ok:!0,projectId:n,devOrigin:s,activeJob:c[0]?{id:c[0].id,status:c[0].status}:null,activeJobs:c.map(p=>({id:p.id,status:p.status})),queueDepth:w.depth,recentJobs:v})}async function we(o,c){let d=new URL(o.url||"/",`http://127.0.0.1:${k}`).searchParams.get("jobId"),y=(d?w.allActive.filter(N=>N.id===d):w.allActive).map(N=>N.threadId).filter(Boolean),_=d?w.cancelJob(d):w.cancelActive();for(let N of y)await $.appendMessage(N,{role:"assistant",timestamp:Date.now(),jobId:d||"",cancelled:!0});I(c,200,{cancelled:_})}async function ve(o){if(H.isRunning){I(o,200,{skipped:!0,reason:"Already running"});return}let c=await H.getUnmaterializedPatternDecisions();if(c.length===0){I(o,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}H.run().catch(()=>{}),I(o,200,{started:!0,decisionCount:c.length,decisionIds:c.map(p=>p.id)})}async function Se(o,c){var K,j;let p=[];try{for(var N=ce(o),X,x,P;X=!(x=await N.next()).done;X=!1){let G=x.value;p.push(typeof G=="string"?Buffer.from(G):G)}}catch(x){P=[x]}finally{try{X&&(x=N.return)&&await x.call(N)}finally{if(P)throw P[0]}}let d;if(p.length>0)try{d=JSON.parse(Buffer.concat(p).toString("utf-8")).serverUrl}catch(G){}let m=[];(K=f.claude)!=null&&K.available&&f.claude.mcp&&!f.claude.mcp.found&&m.push(await mt(d)),(j=f.codex)!=null&&j.available&&f.codex.mcp&&!f.codex.mcp.found&&m.push(await gt(d));let[y,_]=await Promise.all([Je(e),Be(e)]);f.claude&&(f.claude.mcp=y),f.codex&&(f.codex.mcp=_),I(c,200,{results:m,capabilities:{providers:f}})}async function Ie(o,c){let p=[];try{for(var y=ce(o),_,N,X;_=!(N=await y.next()).done;_=!1){let x=N.value;p.push(typeof x=="string"?Buffer.from(x):x)}}catch(N){X=[N]}finally{try{_&&(N=y.return)&&await N.call(y)}finally{if(X)throw X[0]}}let d;try{d=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch(x){I(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){I(c,400,{error:"Missing or invalid name"});return}let m=await H.addComponent(d.name);I(c,200,m)}async function xe(o,c){let p=[];try{for(var y=ce(o),_,N,X;_=!(N=await y.next()).done;_=!1){let x=N.value;p.push(typeof x=="string"?Buffer.from(x):x)}}catch(N){X=[N]}finally{try{_&&(N=y.return)&&await N.call(y)}finally{if(X)throw X[0]}}let d;try{d=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch(x){I(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){I(c,400,{error:"Missing or invalid name"});return}let m=await H.removeComponent(d.name);I(c,200,m)}async function W(o,c){let p=[];try{for(var y=ce(o),_,N,X;_=!(N=await y.next()).done;_=!1){let x=N.value;p.push(typeof x=="string"?Buffer.from(x):x)}}catch(N){X=[N]}finally{try{_&&(N=y.return)&&await N.call(y)}finally{if(X)throw X[0]}}let d;try{d=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch(x){I(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"||typeof d.value!="string"){I(c,400,{error:"Missing or invalid path/value"});return}let m=await H.updateToken(d.path,d.value);I(c,200,m)}async function Ee(o,c){let p=[];try{for(var y=ce(o),_,N,X;_=!(N=await y.next()).done;_=!1){let x=N.value;p.push(typeof x=="string"?Buffer.from(x):x)}}catch(N){X=[N]}finally{try{_&&(N=y.return)&&await N.call(y)}finally{if(X)throw X[0]}}let d;try{d=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch(x){I(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"){I(c,400,{error:"Missing or invalid path"});return}let m=await H.removeToken(d.path);I(c,200,m)}function M(o,c){let p=s!=null?s:"http://localhost:3000";if(!s){let m=o.headers.referer||o.headers.origin;if(m)try{let y=new URL(typeof m=="string"?m:m[0]||"");(y.hostname==="localhost"||y.hostname==="127.0.0.1")&&(p=y.origin)}catch(y){}}let d=nt(k,p);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(d)}async function Pe(o){let c=Date.now();if(g&&c<g.expires){I(o,200,g.data);return}try{let{scanForComponents:p}=await import("./react-scanner-5NIJ6ZPL.mjs"),{generateRenderFiles:d}=await import("./render-generator-ZNV3RDU7.mjs"),m=await p(e);g={data:m,expires:c+5e3},d(m,e,z).then(y=>{z=y}).catch(y=>console.warn("[Bridge] Render generation failed:",y)),I(o,200,m)}catch(p){console.error("[Bridge] Scanner error:",p),I(o,500,{error:"Failed to scan components"})}}async function kt(o){let c=[re(e,"node_modules","@popmelt.com","core","dist","canvas.mjs"),re(e,"packages","popmelt","dist","canvas.mjs")];try{let p=pn(In.url);c.unshift(re(un(p),"canvas.mjs"))}catch(p){}for(let p of c)try{let d=await on(p,"utf-8");o.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),o.end(d);return}catch(d){}console.error("[Bridge] Canvas bundle not found in:",c),I(o,404,{error:"Canvas bundle not found"})}async function Tt(o,c){let p=await $.getThread(o);if(!p){I(c,404,{error:"Thread not found"});return}let d=p.messages.map(_=>{var N=_,{screenshotPath:m}=N,y=tt(N,["screenshotPath"]);return y});I(c,200,{id:p.id,createdAt:p.createdAt,messages:d})}let je=9,Ge=!1;for(let o=t;o<t+je;o++)try{await Sn(S,o),k=o,Ge=!0,console.log(`[\u22B9 is watching :${k}]`);break}catch(c){if(c.code==="EADDRINUSE"){let p=await vn(o);if(p&&p.projectId===n)return console.log(`[\u22B9 already watching :${o}]`),{port:o,projectId:n,close:async()=>{}};continue}throw c}if(!Ge)throw new Error(`[Bridge] All ports ${t}\u2013${t+je-1} in use`);for(let[o,c]of Object.entries(f))!c.available||!c.path||L(o,c.path).then(p=>{if(p)console.log(`[Bridge] ${o} warmed up`);else{console.warn(`[Bridge] ${o} warm-up failed \u2014 marking unavailable`),c.available=!1,c.path=null;for(let d of U)He(d,{type:"capabilities_changed",data:{}})}});let Rt=setInterval(()=>{xt(a).catch(()=>{})},mn);return{port:k,projectId:n,close:async()=>{clearInterval(Rt),await w.destroyAsync();for(let o of U)try{o.res.end()}catch(c){}return U.clear(),new Promise(o=>{S.close(()=>o())})}}}async function xt(r){try{let t=await rn(r),e=Date.now();for(let n of t){let s=re(r,n);try{let a=await an(s);e-a.mtimeMs>gn&&await cn(s)}catch(a){}}}catch(t){}}async function xs(r){if(process.env.NODE_ENV==="production"&&!(r!=null&&r.force))throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");let t=await bt(r);return process.env.POPMELT_BRIDGE_PORT=String(t.port),t}export{xs as startPopmelt};