@popmelt.com/core 0.6.7 → 0.6.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popmelt.com/core",
3
- "version": "0.6.7",
3
+ "version": "0.6.8",
4
4
  "description": "The design collaboration layer for AI coding agents",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "author": "Popmelt <reb@popmelt.com> (https://popmelt.com)",
@@ -1,221 +0,0 @@
1
- import{spawn as xn}from"child_process";import{createHash as bn}from"crypto";import{dirname as kn,join as In}from"path";import{fileURLToPath as Tn}from"url";import{execFileSync as nn,spawn as rt}from"child_process";import{createHash as sn,randomUUID as be}from"crypto";import{mkdir as on,readFile as it,readdir as rn,stat as an,unlink as cn,writeFile as ke}from"fs/promises";import{createServer as ln}from"http";import{tmpdir as dn}from"os";import{basename as un,dirname as pn,join as ne}from"path";import{fileURLToPath as hn}from"url";function Be(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 Rt}from"child_process";import{createInterface as Et}from"readline";var $t=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),Je=1e5;function Mt(r){let t=r.input?.file_path||r.input?.path;if(!t)return;let n=t.includes(".")?`.${t.split(".").pop().toLowerCase()}`:"";if(!$t.has(n))return;let e;if(r.name==="Write"&&typeof r.input?.content=="string"?e=r.input.content:r.name==="Edit"&&typeof r.input?.new_string=="string"&&(e=r.input.new_string),!!e)return e.length>Je?e.slice(0,Je)+`
29
- \u2026[truncated]`:e}function de(r,t){let{prompt:n,projectRoot:e,maxTurns:s=40,maxBudgetUsd:l=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:a="claude",resumeSessionId:p,model:m,timeoutMs:x=3e5,onEvent:C}=t,O=[];p?O.push("--resume",p,"-p",n):O.push("-p",n),O.push("--output-format","stream-json","--verbose","--max-turns",String(s),"--max-budget-usd",String(l)),m&&O.push("--model",m);for(let z of i)O.push("--allowedTools",z);let v=Rt(a,O,{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),H=new Promise(z=>{let X,R=[],U=[],A=!1,F="",g=!1,j=setTimeout(()=>{g=!0,v.kill("SIGTERM"),setTimeout(()=>{try{v.kill("SIGKILL")}catch{}},5e3)},x),S=Et({input:v.stdout}),k=new Set;S.on("line",B=>{if(B.trim())try{let N=JSON.parse(B);N.session_id&&!X&&(X=N.session_id);let Z=N.type??(N.event?.type?`event.${N.event.type}`:"unknown");if(k.add(Z),N.type==="result"&&N.result&&R.length===0){let $=typeof N.result=="string"?N.result:"";$&&(R.push($),C?.({type:"delta",jobId:r,text:$},r))}if(N.type==="assistant"&&Array.isArray(N.message?.content))for(let $ of N.message.content){if($.type==="text"&&$.text&&(R.push($.text),C?.({type:"delta",jobId:r,text:$.text},r)),$.type==="tool_use"&&$.name){let ce=$.input?.file_path||$.input?.path||void 0,fe=Mt($);C?.({type:"tool_use",jobId:r,tool:$.name,...ce?{file:ce}:{},...fe?{content:fe}:{}},r),$.name==="Edit"&&$.input?.file_path?U.push({tool:"Edit",file_path:$.input.file_path,old_string:$.input.old_string,new_string:$.input.new_string,replace_all:$.input.replace_all}):$.name==="Write"&&$.input?.file_path&&U.push({tool:"Write",file_path:$.input.file_path,content:$.input.content})}$.type==="thinking"&&$.thinking&&C?.({type:"thinking",jobId:r,text:$.thinking},r)}N.type==="user"&&N.tool_use_result?.file?.filePath&&C?.({type:"tool_use",jobId:r,tool:"Read",file:N.tool_use_result.file.filePath},r)}catch{}});let I=[];v.stderr?.on("data",B=>{I.push(B.toString())}),v.on("close",B=>{if(clearTimeout(j),S.close(),R.length===0&&k.size>0&&console.warn(`[Claude:${r}] No text captured. Event types seen: ${[...k].join(", ")}`),g)A=!0,F=`Timed out after ${Math.round(x/6e4)} minutes`;else if(B!==0&&B!==null){A=!0;let N=I.join("").trim(),Z=R.length===0&&k.size>0?` (no text captured, event types: ${[...k].join(", ")})`:"";F=N||`Claude process exited with code ${B}${Z}`}z({sessionId:X,text:R.join(""),success:!A,error:A?F:void 0,fileEdits:U.length>0?U:void 0})}),v.on("error",B=>{clearTimeout(j),A=!0,F=B.message,z({sessionId:X,text:R.join(""),success:!1,error:F,fileEdits:U.length>0?U:void 0})})});return{process:v,result:H}}import{spawn as Ot}from"child_process";import{createInterface as Ct}from"readline";function At(r){let t=r.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return t?t[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):r}function Ue(r,t){let{prompt:n,projectRoot:e,screenshotPath:s,resumeSessionId:l,model:i,onEvent:a}=t,p=[];l?(p.push("exec","resume",l),i&&p.push("-m",i),p.push("--json","--full-auto",n),s&&p.push("--image",s)):(p.push("exec","--json","--full-auto"),i&&p.push("-m",i),p.push(n),s&&p.push("--image",s));let m=Ot("codex",p,{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),x=new Promise(C=>{let O,v=[],H=[],z=!1,X="",R=Ct({input:m.stdout}),U=new Set;R.on("line",F=>{if(F.trim())try{let g=JSON.parse(F),j=g.type??"unknown";if(U.add(j),j==="thread.started"&&g.thread_id&&!O&&(O=g.thread_id),(j==="item.agentMessage.delta"||j==="item/agentMessage/delta")&&g.delta?.text&&(v.push(g.delta.text),a?.({type:"delta",jobId:r,text:g.delta.text},r)),(j==="item.reasoning.delta"||j==="item/reasoning/delta")&&g.delta?.text&&a?.({type:"thinking",jobId:r,text:g.delta.text},r),(j==="item.started"||j==="item/started")&&g.item){let S=g.item.type;if(S==="command_execution"){let k=g.item.command,I=k?At(k):void 0,B=I?`Bash: ${I.split(`
30
- `)[0].slice(0,80)}`:"Bash";H.push(B),a?.({type:"tool_use",jobId:r,tool:"Bash",...I?{content:I}:{}},r)}else if(S==="file_change"){let k=g.item.filename||g.item.path;H.push(k?`Edit ${k.split("/").pop()}`:"Edit"),a?.({type:"tool_use",jobId:r,tool:"Edit",...k?{file:k}:{}},r)}else if(S==="file_read"){let k=g.item.filename||g.item.path;H.push(k?`Read ${k.split("/").pop()}`:"Read"),a?.({type:"tool_use",jobId:r,tool:"Read",...k?{file:k}:{}},r)}else if(S==="web_search")H.push("WebSearch"),a?.({type:"tool_use",jobId:r,tool:"WebSearch"},r);else if(S==="mcp_tool_call"){let k=g.item.tool_name||g.item.name||"MCP";H.push(k),a?.({type:"tool_use",jobId:r,tool:k},r)}}if((j==="item.completed"||j==="item/completed")&&g.item){if(g.item.type==="agent_message"){let S=g.item.text;typeof S=="string"&&S&&(v.push(S),a?.({type:"delta",jobId:r,text:S},r))}else if(g.item.type==="reasoning"){let S=g.item.text;typeof S=="string"&&S&&a?.({type:"thinking",jobId:r,text:S},r)}else if(g.item.type==="file_change"&&Array.isArray(g.item.changes))for(let S of g.item.changes){let k=S.path||S.filename,I=S.kind==="add"?"Write":"Edit";k&&(H.push(`${I} ${k.split("/").pop()}`),a?.({type:"tool_use",jobId:r,tool:I,file:k},r))}}j==="turn.failed"&&(z=!0,X=g.error?.message||g.message||"Turn failed")}catch{}});let A=[];m.stderr?.on("data",F=>{A.push(F.toString())}),m.on("close",F=>{R.close(),v.length===0&&U.size>0&&console.warn(`[Codex:${r}] No text captured. Event types seen: ${[...U].join(", ")}`),F!==0&&F!==null&&(z=!0,X=A.join("")||`Codex process exited with code ${F}`),C({sessionId:O,text:v.join(""),success:!z,error:z?X:void 0,toolsUsed:H.length>0?H:void 0})}),m.on("error",F=>{z=!0,X=F.message,C({sessionId:O,text:v.join(""),success:!1,error:X,toolsUsed:H.length>0?H:void 0})})});return{process:m,result:x}}import{execFile as Dt}from"child_process";import{copyFile as Fe,mkdir as je,readdir as _t,readFile as Nt,writeFile as Bt}from"fs/promises";import{join as ae}from"path";var ge=class{constructor(t){this.projectRoot=t;let n=ae(t,".popmelt");this.decisionsDir=ae(n,"decisions"),this.screenshotsDir=ae(n,"screenshots")}async persist(t,n,e){try{await je(this.decisionsDir,{recursive:!0}),await je(this.screenshotsDir,{recursive:!0});try{await Fe(n,ae(this.screenshotsDir,`s-${t.id}.webp`))}catch{}for(let s=0;s<e.length;s++)try{let l=t.pastedImagePaths[s];l&&await Fe(e[s],ae(this.screenshotsDir,l.replace("screenshots/","")))}catch{}await Bt(ae(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 _t(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(t){try{let n=await Nt(ae(this.decisionsDir,`d-${t}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(t){return(await Promise.all(t.map(e=>this.loadDecision(e)))).filter(e=>e!==null)}captureGitDiff(t){return new Promise(n=>{Dt("git",["diff","HEAD"],{cwd:t,timeout:5e3,maxBuffer:1024*1024},(e,s)=>{if(e){n(null);return}n(s||null)})})}};import{readFile as Le,writeFile as re}from"fs/promises";import{join as Te}from"path";var q="[Materializer]",Jt={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null};function Ut(r){return Array.isArray(r)?r.map((t,n)=>typeof t=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:t,sources:[]}:t&&typeof t=="object"&&typeof t.text=="string"?t:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(t),sources:[]}):[]}function ue(r){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let e=n;if(typeof e.id!="string"||typeof e.text!="string"){console.warn(`${q} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}t.push({id:e.id,scope:typeof e.scope=="string"?e.scope:"general",text:e.text,sources:Array.isArray(e.sources)?e.sources.filter(s=>typeof s=="string"):[]})}return t.length>30&&console.warn(`${q} Rule count ${t.length} exceeds cap of 30`),t}var ye=class{constructor(t,n,e={}){this.projectRoot=t;this.decisionStore=n;this.options=e;this.cachedIndex=null;this.running=!1;let s=Te(t,".popmelt");this.indexPath=Te(s,"materialized.json"),this.modelPath=Te(s,"model.json")}get isRunning(){return this.running}async loadModel(){try{let t=await Le(this.modelPath,"utf-8"),n=JSON.parse(t);return Array.isArray(n.rules)&&(n.rules=Ut(n.rules)),n}catch{return null}}async addComponent(t){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let e=n.components;return e[t]?{added:!1,alreadyExists:!0}:(e[t]={description:""},await re(this.modelPath,JSON.stringify(n,null,2)),console.log(`${q} Added component "${t}" to model`),{added:!0,alreadyExists:!1})}async updateToken(t,n){let e=await this.loadModel();e||(e={tokens:{},components:{},rules:[]});let s=t.split("."),l=e;for(let p=0;p<s.length-1;p++){let m=s[p];(!l[m]||typeof l[m]!="object")&&(l[m]={}),l=l[m]}let i=s[s.length-1],a;try{a=JSON.parse(n)}catch{a=null}if(a&&typeof a=="object"&&a!==null&&"value"in a)l[i]=a;else{let p=l[i];p&&typeof p=="object"&&p!==null&&"value"in p?p.value=n:l[i]=n}return await re(this.modelPath,JSON.stringify(e,null,2)),console.log(`${q} Updated token "${t}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(t){let n=await this.loadModel();if(!n)return{removed:!1};let e=t.split("."),s=n;for(let i=0;i<e.length-1;i++){let a=e[i];if(!s[a]||typeof s[a]!="object")return{removed:!1};s=s[a]}let l=e[e.length-1];return l in s?(delete s[l],await re(this.modelPath,JSON.stringify(n,null,2)),console.log(`${q} Removed token "${t}" from model`),{removed:!0}):{removed:!1}}async removeComponent(t){let n=await this.loadModel();if(!n)return{removed:!1};let e=n.components;return!e||!e[t]?{removed:!1}:(delete e[t],await re(this.modelPath,JSON.stringify(n,null,2)),console.log(`${q} Removed component "${t}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let t=await this.loadIndex(),n=new Set(t.materializedIds),s=(await this.decisionStore.listDecisionIds()).filter(i=>!n.has(i));return s.length===0?[]:(await this.decisionStore.loadDecisions(s)).filter(i=>i.resolutions.some(a=>(a.finalScope??a.inferredScope)?.breadth==="pattern"))}async run(){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;try{let t=await this.getUnmaterializedPatternDecisions();if(t.length===0)return{processedIds:[],success:!0};let n=t.map(m=>m.id);console.log(`${q} Processing ${n.length} pattern-scoped decision(s): ${n.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:n});let e=await this.loadModel(),s=Ft(t,e),l=!0,i;try{let{result:m}=de(`mat-${Date.now()}`,{prompt:s,projectRoot:this.projectRoot,maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"],claudePath:this.options.claudePath??"claude"}),x=await m;if(!x.success)l=!1,i=x.error,console.error(`${q} Claude spawn error:`,i);else{let C=we(x.text);C?(Array.isArray(C.rules)&&(C.rules=ue(C.rules)),await re(this.modelPath,JSON.stringify(C,null,2)),console.log(`${q} Successfully materialized ${n.length} decision(s) \u2192 ${this.modelPath}`)):(l=!1,i="No <model> block found in response",console.error(`${q} ${i}`))}}catch(m){l=!1,i=m instanceof Error?m.message:String(m),console.error(`${q} Error:`,i)}let a=await this.loadIndex(),p=new Set(a.materializedIds);for(let m of n)p.add(m);return a.materializedIds=[...p],a.lastRunAt=Date.now(),a.lastRunDecisionIds=n,a.lastRunError=i??null,await this.persistIndex(a),this.options.onEvent?.({type:"materialize_done",decisionIds:n,success:l,error:i}),{processedIds:n,success:l,error:i}}finally{this.running=!1}}async consolidate(){if(this.running)return{success:!1,error:"Already running"};this.running=!0;try{let t=await this.loadModel();if(!t)return{success:!1,error:"No model exists"};let n=jt(t),{result:e}=de(`consolidate-${Date.now()}`,{prompt:n,projectRoot:this.projectRoot,maxTurns:this.options.maxTurns??3,maxBudgetUsd:this.options.maxBudgetUsd??.3,allowedTools:[],claudePath:this.options.claudePath??"claude"}),s=await e;if(!s.success)return console.error(`${q} Consolidation spawn error:`,s.error),{success:!1,error:s.error};let l=we(s.text);return l?(Array.isArray(l.rules)&&(l.rules=ue(l.rules)),!l.tokens&&t.tokens&&(l.tokens=t.tokens),!l.components&&t.components&&(l.components=t.components),await re(this.modelPath,JSON.stringify(l,null,2)),console.log(`${q} Consolidation complete \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${q} No <model> block in consolidation response`),{success:!1,error:"No <model> block found"})}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`${q} Consolidation error:`,n),{success:!1,error:n}}finally{this.running=!1}}async writeModel(t){Array.isArray(t.rules)&&(t.rules=ue(t.rules)),await re(this.modelPath,JSON.stringify(t,null,2)),console.log(`${q} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let t=await Le(this.indexPath,"utf-8"),n=JSON.parse(t);return this.cachedIndex=n,n}catch{return this.cachedIndex={...Jt,materializedIds:[],lastRunDecisionIds:[]},this.cachedIndex}}async persistIndex(t){this.cachedIndex=t;try{await re(this.indexPath,JSON.stringify(t,null,2))}catch(n){console.error(`${q} Failed to write index:`,n)}}};function we(r){let t=r.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}function Ft(r,t){let n=r.map(l=>{let a=l.resolutions.filter(x=>(x.finalScope??x.inferredScope)?.breadth==="pattern").map(x=>{let O=(x.finalScope??x.inferredScope)?.target??"unknown",v=x.filesModified?.join(", ")??"none";return`- **${x.summary}** [scope: pattern/${O}]
31
- Files modified: ${v}`}).join(`
32
- `),p=l.annotations.map(x=>x.instruction).filter(Boolean).join(`
33
- `),m=l.gitDiff?`
34
- \`\`\`diff
35
- ${l.gitDiff.slice(0,2e3)}
36
- \`\`\``:"";return`### Decision ${l.id} (${new Date(l.createdAt).toISOString()})
37
- Page: ${l.url}
38
- ${a}
39
- ${m}
40
- ${p?`
41
- Original instructions:
42
- ${p}`:""}`}).join(`
43
-
44
- `),e=r.map(l=>l.id);return`You are extracting a local design model from accumulated design decisions.
45
-
46
- ## Instructions
47
- 1. Review the current model (if any) and the new decisions below.
48
- 2. Determine what design tokens, component patterns, and rules to add or update.
49
- 3. Output the complete updated model as a JSON object inside <model> tags.
50
-
51
- ${t?`## Current Model
52
- \`\`\`json
53
- ${JSON.stringify(t,null,2)}
54
- \`\`\`
55
-
56
- 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."}
57
-
58
- ## Design Decisions to Materialize
59
- ${n}
60
-
61
- ## Output Format
62
- Output the full model inside <model> tags. The model is a JSON object with these sections:
63
- - \`tokens\`: Design tokens (colors, spacing, typography, etc.)
64
- - \`components\`: Component-level patterns (e.g., button styles, card layouts)
65
- - \`rules\`: Array of structured rule objects
66
-
67
- ### Rule format
68
- Each rule is a JSON object:
69
- \`\`\`json
70
- { "id": "a1b2c3d4", "scope": "typography", "text": "Body text uses Inter at 16px/1.5", "sources": ["d-abc123"] }
71
- \`\`\`
72
-
73
- Fields:
74
- - \`id\`: 8-character hex string. Preserve IDs for unchanged rules. Generate new IDs for new or merged rules.
75
- - \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
76
- - \`text\`: A clear, enforceable design rule
77
- - \`sources\`: Array of decision IDs that informed this rule. For new rules from these decisions, use: ${JSON.stringify(e)}
78
-
79
- ### Rule guidelines
80
- - **Hard cap: 30 rules maximum.** Merge rules covering the same concern into one.
81
- - **Reject:** workflow advice ("After fixing X, verify Y"), instance-level observations ("The hero section uses 32px gap"), rules that merely restate a token or component already in the model.
82
- - **Keep:** Enforceable patterns, constraints, relationships between elements, accessibility requirements.
83
-
84
- Example:
85
- <model>
86
- {
87
- "tokens": {
88
- "colors": { "primary": "#3b82f6" },
89
- "spacing": {
90
- "sm": "4px",
91
- "md": "8px",
92
- "section-gap": { "value": "32px", "property": "gap", "bindings": ["gap-8"] }
93
- }
94
- },
95
- "components": {
96
- "button": { "padding": "12px 24px", "borderRadius": "8px" }
97
- },
98
- "rules": [
99
- { "id": "a1b2c3d4", "scope": "typography", "text": "Body text uses Inter at 16px/1.5", "sources": ["d-abc123"] },
100
- { "id": "e5f6a7b8", "scope": "color", "text": "Primary actions use the primary color token", "sources": ["d-def456"] }
101
- ]
102
- }
103
- </model>
104
-
105
- ## Guidelines
106
- - Map token-scoped decisions to \`tokens\`, component-scoped to \`components\`.
107
- - Extract clear, enforceable rules into the \`rules\` array as structured objects.
108
- - When merging, new decisions override conflicting older values.
109
- - Keep the model concise \u2014 only include patterns with clear evidence from decisions.
110
- - Do NOT output resolution or question blocks. Just output the <model> block.
111
- - Spacing tokens can be plain strings ("8px") or objects with code bindings:
112
- { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
113
- - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
114
- - bindings: Tailwind class names (without responsive prefixes) that use this token
115
- Include property and bindings when the decision context has class-level evidence.`}function jt(r){return`You are consolidating a design model's rules. The model has accumulated too many rules and needs cleanup.
116
-
117
- ## Current Model
118
- \`\`\`json
119
- ${JSON.stringify(r,null,2)}
120
- \`\`\`
121
-
122
- ## Instructions
123
- 1. Review all current rules.
124
- 2. Merge rules that cover the same concern into single, clear rules.
125
- 3. Remove rules that are:
126
- - Workflow advice ("After SSR fixes, re-verify headless output")
127
- - Instance-level observations ("Footer tagline is 'Design everything.'")
128
- - Restating tokens or components already defined elsewhere in the model
129
- - Procedural instructions rather than design constraints
130
- 4. Output the full model with consolidated rules.
131
-
132
- ## Rule format
133
- Each rule MUST be a JSON object:
134
- { "id": "a1b2c3d4", "scope": "<scope>", "text": "<rule text>", "sources": ["<decision-id>", ...] }
135
-
136
- - \`id\`: 8-char hex. Preserve the ID of the most representative source rule when merging. Generate new 8-char hex IDs for genuinely new rules.
137
- - \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
138
- - \`text\`: Clear, enforceable design constraint
139
- - \`sources\`: Merge source arrays when combining rules
140
-
141
- ## Hard cap: 30 rules maximum.
142
-
143
- Prioritize rules that are:
144
- - Enforceable constraints (not preferences)
145
- - Cross-cutting (affect many elements)
146
- - Not already captured by tokens or component definitions in the model
147
-
148
- ## Output
149
- Output the complete model inside <model> tags. Preserve tokens and components as-is \u2014 only rules change.
150
-
151
- <model>
152
- { "tokens": { ... }, "components": { ... }, "rules": [ ... ] }
153
- </model>`}function ze(r){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.
154
-
155
- ## Current Model
156
- \`\`\`json
157
- ${JSON.stringify(r,null,2)}
158
- \`\`\`
159
-
160
- ## Instructions
161
- 1. Review all current rules, tokens, and components.
162
- 2. Propose specific changes \u2014 additions, merges, removals \u2014 with brief reasoning for each.
163
- 3. Present your proposals as clear text so the developer can review them.
164
- 4. Do NOT output a <model> block yet. First get the developer's approval.
165
-
166
- ## Output format
167
- - List each proposed change as a numbered item with a short rationale.
168
- - Group by action: **Merge**, **Add**, **Remove**, **Reword**.
169
- - After your proposals, output a <question> block asking the developer to approve, adjust, or reject.
170
-
171
- Example:
172
- **Merge**
173
- 1. Rules "Body text uses Inter 16px" and "Paragraph text is Inter 16/1.5" \u2192 "Body/paragraph text uses Inter at 16px/1.5" (they say the same thing)
174
-
175
- **Remove**
176
- 2. "After fixing SSR, re-verify headless output" \u2014 workflow advice, not a design constraint
177
-
178
- **Add**
179
- 3. "Primary actions use the primary color token; secondary actions use gray-500" \u2014 implied by token usage but not codified
180
-
181
- <question>
182
- These are my proposed rule changes. Would you like to approve all of them, adjust specific items, or add more? Once you're happy I'll output the final model.
183
- </question>
184
-
185
- ## After approval
186
- When the developer approves (says "yes", "looks good", "go ahead", etc.), output the complete updated model inside <model> tags \u2014 the full JSON with tokens, components, and the revised rules array. Do NOT output partial models. Preserve tokens and components as-is unless the developer asks to change them.`}import{readFile as Ge}from"fs/promises";import{homedir as qe}from"os";import{join as le}from"path";var Ee=/popmelt/i;function $e(){return{found:!1,name:null,scope:null,disabled:!1}}function pe(r,t,n=!1){return{found:!0,name:r,scope:t,disabled:n}}function ve(r){for(let t of Object.keys(r))if(Ee.test(t))return t;return null}async function Re(r){try{let t=await Ge(r,"utf-8");return JSON.parse(t)}catch{return null}}async function Me(r){let t=qe(),n=await Re(le(t,".claude.json"));if(n&&typeof n=="object"){let s=n;if(s.mcpServers&&typeof s.mcpServers=="object"){let l=ve(s.mcpServers);if(l)return pe(l,"user")}if(s.projects&&typeof s.projects=="object"){let i=s.projects[r];if(i&&typeof i=="object"){let a=i;if(a.mcpServers&&typeof a.mcpServers=="object"){let p=ve(a.mcpServers);if(p){let m=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(x=>Ee.test(x));return pe(p,"project",m)}}}}}let e=await Re(le(r,".mcp.json"));if(e&&typeof e=="object"){let s=e;if(s.mcpServers&&typeof s.mcpServers=="object"){let i=ve(s.mcpServers);if(i){let a=await He(r,i);return pe(i,"mcp.json",a)}}let l=ve(s);if(l&&l!=="mcpServers"){let i=await He(r,l);return pe(l,"mcp.json",i)}}return $e()}async function He(r,t){let n=le(r,".claude","settings.local.json"),e=await Re(n);if(e&&typeof e=="object"){let s=e;if(Array.isArray(s.disabledMcpjsonServers))return s.disabledMcpjsonServers.some(l=>l===t)}return!1}var Lt=/^\[mcp_servers\.([^\]]+)\]/;function zt(r){let t=r.split(`
187
- `),n=[],e=null;for(let s of t){let l=s.match(Lt);l?(e&&n.push({name:e.name,body:e.bodyLines.join(`
188
- `)}),e={name:l[1],bodyLines:[]}):s.startsWith("[")?e&&(n.push({name:e.name,body:e.bodyLines.join(`
189
- `)}),e=null):e&&e.bodyLines.push(s)}return e&&n.push({name:e.name,body:e.bodyLines.join(`
190
- `)}),n}function Ht(r){return/enabled\s*=\s*false/i.test(r)}async function Oe(r){let t=process.env.CODEX_HOME||le(qe(),".codex"),n=await We(le(t,"config.toml"),"user");if(n.found)return n;let e=await We(le(r,".codex","config.toml"),"project");return e.found?e:$e()}async function We(r,t){try{let n=await Ge(r,"utf-8"),e=zt(n);for(let s of e)if(Ee.test(s.name)){let l=Ht(s.body);return pe(s.name,t,l)}}catch{}return $e()}import{mkdir as Wt,readFile as Ye,writeFile as Qe}from"fs/promises";import{homedir as Xe}from"os";import{dirname as Gt,join as Ce}from"path";var Ve="https://mcp.popmelt.com/mcp";async function Ke(r=Ve){let t=Ce(Xe(),".claude.json"),n;try{let s=await Ye(t,"utf-8");n=JSON.parse(s)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let e=n.mcpServers;for(let s of Object.keys(e))if(/popmelt/i.test(s))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return e.popmelt={type:"http",url:r},await Qe(t,JSON.stringify(n,null,2)+`
191
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Ze(r=Ve){let t=process.env.CODEX_HOME||Ce(Xe(),".codex"),n=Ce(t,"config.toml"),e;try{e=await Ye(n,"utf-8")}catch{e=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(e))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Wt(Gt(n),{recursive:!0});let s=`
192
- [mcp_servers.popmelt]
193
- url = "${r}"
194
- `;return await Qe(n,e+s,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Ae(r){let n=(r.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let e=n[1]||n[2],s=await qt(r),l=Buffer.from(`--${e}`),i=Buffer.from(`--${e}--`),a,p,m,x,C,O,v,H,z,X,R,U,A=[],F=[],g=0,j=[];for(;g<s.length;){let S=s.indexOf(l,g);if(S===-1)break;let k=S+l.length;if(s.slice(S,S+i.length).equals(i))break;let I=k;s[I]===13&&s[I+1]===10&&(I+=2);let B=s.indexOf(`\r
195
- \r
196
- `,I);if(B===-1)break;let N=s.slice(I,B).toString("utf-8"),Z=B+4,$=s.indexOf(l,Z),ce=$!==-1?$-2:s.length;j.push({headers:N,body:s.slice(Z,ce)}),g=$!==-1?$:s.length}for(let S of j){let k=S.headers.match(/name="([^"]+)"/);if(!k)continue;let I=k[1];if(I==="screenshot")a=S.body;else if(I==="feedback")p=S.body.toString("utf-8");else if(I==="color")m=S.body.toString("utf-8");else if(I==="provider")x=S.body.toString("utf-8");else if(I==="model")C=S.body.toString("utf-8");else if(I==="goal")O=S.body.toString("utf-8");else if(I==="pageUrl")v=S.body.toString("utf-8");else if(I==="viewport")H=S.body.toString("utf-8");else if(I==="planId")z=S.body.toString("utf-8");else if(I==="manifest")X=S.body.toString("utf-8");else if(I==="tasks")R=S.body.toString("utf-8");else if(I==="sourceId")U=S.body.toString("utf-8");else if(I.startsWith("screenshot-")){let B=I.slice(11);try{let N=decodeURIComponent(B);F.push({pathname:N,data:S.body})}catch{}}else if(I.startsWith("image-")){let B=I.split("-"),N=parseInt(B[B.length-1],10),Z=B.slice(1,-1).join("-");Z&&!isNaN(N)&&A.push({annotationId:Z,index:N,data:S.body})}}if(!a)throw new Error("Missing screenshot field");return p||(p=""),{screenshot:a,feedback:p,color:m,provider:x,model:C,goal:O,pageUrl:v,viewport:H,planId:z,manifest:X,tasks:R,sourceId:U,pastedImages:A,pageScreenshots:F}}function qt(r){return new Promise((t,n)=>{let e=[];r.on("data",s=>e.push(s)),r.on("end",()=>t(Buffer.concat(e))),r.on("error",n)})}function he(r,t){let n=[];if(r.annotations.length>0){n.push("## Annotations");for(let e of r.annotations){let s=e.elements.map(a=>{let p=[a.selector];return a.reactComponent&&p.push(`(${a.reactComponent})`),p.join(" ")}).join(", "),l=e.instruction||"No text";n.push(`- id=${e.id} [${e.type}] ${l} \u2192 Elements: ${s||"none"}`);let i=t?.[e.id];if(i&&i.length>0)for(let a of i)n.push(` Attached image: use the Read tool to view ${a}`)}}if(r.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let e of r.styleModifications){let s=e.element?.reactComponent?`(${e.element.reactComponent})`:"";for(let l of e.changes)n.push(`- ${e.selector} ${s}: ${l.property} ${l.original} \u2192 ${l.modified}`)}}if(r.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let e of r.spacingTokenChanges){n.push(`
197
- ### ${e.tokenName}: ${e.originalPx}px \u2192 ${e.newPx}px`);for(let s of e.affectedElements){let l=s.reactComponent?` (${s.reactComponent})`:"";s.matchedClass&&s.suggestedClass?n.push(`- ${s.selector}${l}: \`${s.matchedClass}\` \u2192 \`${s.suggestedClass}\``):n.push(`- ${s.selector}${l}: ${s.property} ${e.originalPx}px \u2192 ${e.newPx}px`),n.push(` class="${s.className}"`)}}}if(r.inspectedElement){let e=r.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let s=[e.selector];e.reactComponent&&s.push(`(${e.reactComponent})`),e.context&&s.push(`in ${e.context}`),e.textContent&&s.push(`"${e.textContent.slice(0,80)}"`),n.push(`- ${s.join(" ")}`)}return n.join(`
198
- `)}function et(r,t,n){let e=[],l=new Set(t.annotations.map(i=>i.pathname).filter(Boolean)).size>1;if(e.push("You are reviewing a UI screenshot with developer annotations."),e.push(""),!l&&n?.provider!=="codex"&&(e.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`),e.push("")),e.push(`The developer annotated their running app at ${t.url} (${t.viewport.width}x${t.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){e.push(""),e.push("## Previous Conversation");let i=0;for(let a of n.threadHistory)if(a.role==="human")i++,a.replyToQuestion?(e.push(`### Round ${i} (human) \u2014 reply`),e.push(`"${a.replyToQuestion}"`)):(e.push(`### Round ${i} (human)`),a.feedbackSummary&&e.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&e.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)e.push(`### Round ${i} (assistant) \u2014 question`),e.push(`"${a.question}"`);else{if(e.push(`### Round ${i} (assistant)`),a.responseText&&e.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let p of a.resolutions){let m=p.finalScope??p.inferredScope,x=m?` [${m.breadth} ${m.target}]`:"";e.push(`- ${p.annotationId}: ${p.status}${x} \u2014 ${p.summary}`),p.filesModified&&p.filesModified.length>0&&e.push(` Files: ${p.filesModified.join(", ")}`)}a.toolsUsed&&a.toolsUsed.length>0&&e.push(`Tools used: ${a.toolsUsed.join(", ")}`)}e.push(""),e.push("The current round is shown in full below.")}if(n?.designModel){e.push(""),e.push("## Established Design Policies"),e.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let i=n.designModel.rules;if(Array.isArray(i)&&i.length>0)if(e.push(""),e.push("Rules:"),i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"scope"in i[0]){let x=new Map;for(let C of i)if(typeof C=="object"&&C!==null&&"text"in C){let O=C,v=O.scope||"general";x.has(v)||x.set(v,[]),x.get(v).push(O.text)}for(let[C,O]of x){e.push(`**${C.charAt(0).toUpperCase()+C.slice(1)}**`);for(let v of O)e.push(`- ${v}`)}}else for(let x of i)typeof x=="string"&&e.push(`- ${x}`);let a=n.designModel.tokens;a&&typeof a=="object"&&(e.push(""),e.push("Design tokens:"),e.push("```json"),e.push(JSON.stringify(a,null,2)),e.push("```"));let p=n.designModel.components;p&&typeof p=="object"&&(e.push(""),e.push("Component patterns:"),e.push("```json"),e.push(JSON.stringify(p,null,2)),e.push("```")),e.push(""),e.push("### Novel Pattern Detection"),e.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),e.push("<novel>"),e.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),e.push("</novel>"),e.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),e.push("- `element`: What you are styling or creating"),e.push("- `decision`: What you decided to do (specific values)"),e.push("- `reason`: Why this is novel (what is missing from the model)"),e.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(e.push(""),e.push("## Design Context"),e.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code.")),l){let i=n?.screenshotPaths??{},a=new Map;for(let p of t.annotations){let m=p.pathname||new URL(t.url).pathname;a.has(m)||a.set(m,[]),a.get(m).push(p)}e.push(""),e.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[p,m]of a){e.push(""),e.push(`## Page: ${p}`);let x=i[p];x&&n?.provider!=="codex"?e.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${x}`):!x&&n?.provider!=="codex"&&(Object.keys(i).length===0?(e.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${r}`),e.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):e.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let C={...t,annotations:m,styleModifications:t.styleModifications},O=he(C,n?.imagePaths);O&&(e.push(""),e.push(O))}}else{let i=he(t,n?.imagePaths);i&&(e.push(""),e.push(i))}return e.push(""),e.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),e.push(""),e.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e.push(""),e.push("## Resolution"),e.push("After completing all work, output a resolution block listing what you did for each annotation:"),e.push("<resolution>"),e.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),e.push("</resolution>"),e.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),e.push(""),e.push("### Scope classification"),e.push("Each resolution MUST include scope fields:"),e.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),e.push("- `inferredScope`: What scope the change actually has, based on what you modified."),e.push("Scope has two dimensions:"),e.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),e.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),e.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),e.push("If you cannot confidently determine scope, set it to null."),e.push(""),e.push("## Questions"),e.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),e.push('<question>What do you mean by "..."?</question>'),e.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),e.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),e.join(`
199
- `)}function tt(r){return r.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function nt(r,t,n,e){let s=[];s.push("You are continuing work on a UI based on the developer's reply to your question."),s.push(""),n!=="codex"&&s.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${r}`);let l=t.find(i=>i.role==="human"&&i.feedbackContext);if(l?.feedbackContext&&(s.push(""),s.push(l.feedbackContext)),t.length>0){s.push(""),s.push("## Conversation History");let i=0;for(let a of t)a.role==="human"?(i++,a.replyToQuestion?(s.push(`### Round ${i} (human) \u2014 reply`),s.push(`"${a.replyToQuestion}"`)):(s.push(`### Round ${i} (human)`),a.feedbackSummary&&s.push(`Annotations: ${a.feedbackSummary}`))):a.question?(s.push(`### Round ${i} (assistant) \u2014 question`),s.push(`"${a.question}"`)):(s.push(`### Round ${i} (assistant)`),a.responseText&&s.push(`Response: ${a.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."),e&&e.length>0){s.push(""),s.push("## Attached Images"),s.push("The developer attached reference images with their reply:");for(let i of e)s.push(`Attached image: use the Read tool to view the image at: ${i}`)}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(`
200
- `)}function Yt(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 n of["declaredScope","inferredScope","finalScope"])if(t[n]!==void 0&&t[n]!==null&&!Yt(t[n]))return!1;return!0}function st(r){let t=r.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!t||!t[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(Qt):[]}catch{return[]}}function ot(r){let t=r.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!t?.[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(e=>{if(typeof e!="object"||e===null)return!1;let s=e;return(s.category==="token"||s.category==="component"||s.category==="element")&&typeof s.element=="string"&&typeof s.decision=="string"&&typeof s.reason=="string"}):[]}catch{return[]}}var Se=class{constructor(t=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=t}setProcessor(t){this.processor=t}get active(){let t=this.activeJobs.values().next();return t.done?null:t.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(t,n){n?this.activeProcesses.set(t,n):this.activeProcesses.delete(t)}enqueue(t){return this.queue.push(t),this.processNext(),this.queue.length+this.activeJobs.size}addListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}broadcast(t,n,e){let s=this.bufferEvent(n,t);for(let l of this.listeners)l(s,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let s={...n,seq:e.nextSeq++};return e.events.push(s),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),s}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),s=this.accumulators.get(t)??{response:"",thinking:""},l=this.activeJobs.has(t);if(!e)return null;let i=n<0?e.events:e.events.filter(a=>a.seq>n);return{jobId:t,events:i,currentSeq:e.nextSeq-1,accumulated:{...s},jobActive:l}}accumulateText(t,n,e){let s=this.accumulators.get(t);s||(s={response:"",thinking:""},this.accumulators.set(t,s)),s[n]+=e}getAccumulated(t){return this.accumulators.get(t)??null}scheduleBufferCleanup(t){let n=this.cleanupTimers.get(t);n&&clearTimeout(n);let e=setTimeout(()=>{this.eventBuffers.delete(t),this.accumulators.delete(t),this.cleanupTimers.delete(t)},6e4);this.cleanupTimers.set(t,e)}cancelJob(t){let n=this.activeProcesses.get(t),e=this.activeJobs.get(t);return!n||!e?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(t),this.activeJobs.delete(t),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,message:"Cancelled by user",cancelled:!0},e.id,e.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let t=Array.from(this.activeJobs.keys());for(let n of t)this.cancelJob(n);return!0}destroy(){for(let t of this.activeProcesses.values())t.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}async destroyAsync(t=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let e of n)try{e.kill("SIGTERM")}catch{}await Promise.all(n.map(e=>new Promise(s=>{let l=!1,i=()=>{l||(l=!0,s())};e.on("exit",i),e.on("error",i),setTimeout(()=>{if(!l){try{e.kill("SIGKILL")}catch{}setTimeout(i,500)}},t)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let t=this.queue.shift();this.activeJobs.set(t.id,t),t.status="running",this.broadcast({type:"job_started",jobId:t.id,position:0,threadId:t.threadId},t.id,t.sourceId),this.processor(t).catch(n=>{t.status="error",t.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:t.id,message:t.error},t.id,t.sourceId)}).finally(()=>{this.activeJobs.delete(t.id),this.activeProcesses.delete(t.id),this.scheduleBufferCleanup(t.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id)})}}};import{mkdir as Xt,readFile as Vt,writeFile as Kt}from"fs/promises";import{dirname as Zt,join as en}from"path";var tn={version:1,threads:{}},Pe=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=en(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await Vt(this.filePath,"utf-8"),n=JSON.parse(t);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...tn,threads:{}},this.cache}async getThread(t){return(await this.load()).threads[t]??null}async findContinuationThread(t){if(t.length===0)return null;let n=await this.load(),e=new Set(t);for(let s of Object.values(n.threads))if(s.elementIdentifiers.some(i=>e.has(i)))return s;return null}async createThread(t,n){let e=await this.load(),s={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=s,await this.persist(),s}async appendMessage(t,n){let s=(await this.load()).threads[t];s&&(s.messages.push(n),s.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let s=(await this.load()).threads[t];if(!s)return;let l=new Set(s.elementIdentifiers);for(let i of n)l.has(i)||s.elementIdentifiers.push(i);s.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((s,l)=>l.updatedAt-s.updatedAt),e.slice(0,t).map(s=>{let i=s.messages.find(a=>a.role==="human")?.feedbackSummary||"[thread]";return{id:s.id,createdAt:s.createdAt,updatedAt:s.updatedAt,preview:i,messageCount:s.messages.length,elementIdentifiers:s.elementIdentifiers}})}async getThreadHistory(t,n=6){let e=await this.getThread(t);return!e||e.messages.length===0?[]:e.messages.length<=n?e.messages:[e.messages[0],...e.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await Xt(Zt(this.filePath),{recursive:!0}),await Kt(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var xe="0.6.6";var fn=1111,mn=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],gn=1800*1e3,yn=3600*1e3;function ct(r){if(!r)return!1;try{let t=new URL(r);return t.hostname==="localhost"||t.hostname==="127.0.0.1"}catch{return!1}}function wn(r){let t=[];for(let n of r)if(n.type==="delta"){let e=n.text;if(!e)continue;let s=t[t.length-1];s&&s.kind==="text"?s.text+=e:t.push({kind:"text",text:e})}else if(n.type==="tool_use"){let e=n.tool||"",s=n.file??void 0,l=n.content??void 0,i=s?s.split("/").pop()??s:void 0,a;switch(e){case"Read":a=i?`Reading ${i}`:"Reading file";break;case"Edit":a=i?`Editing ${i}`:"Editing file";break;case"Write":a=i?`Writing ${i}`:"Writing file";break;case"Bash":a=l?l.split(`
201
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":a="Searching files";break;case"Grep":a="Searching code";break;case"WebFetch":a="Fetching page";break;case"WebSearch":a="Searching web";break;default:a=e?`Using ${e}`:"tool";break}let p=s??l??void 0,m=t[t.length-1];m&&m.kind==="tool_group"&&m.tool===e?m.items.push({label:a,detail:p}):t.push({kind:"tool_group",tool:e,items:[{label:a,detail:p}]})}return t}function vn(r,t){let n=r.headers.origin;ct(n)&&(t.setHeader("Access-Control-Allow-Origin",n),t.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type"))}function w(r,t,n){r.writeHead(t,{"Content-Type":"application/json"}),r.end(JSON.stringify(n))}function Sn(r,t){if(!r)return t;let n=r.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return t;let[,e,s,l]=n;return`\x1B[38;2;${parseInt(e,16)};${parseInt(s,16)};${parseInt(l,16)}m${t}\x1B[0m`}function De(r,t){try{r.res.write(`event: ${t.type}
202
- data: ${JSON.stringify(t)}
203
-
204
- `)}catch{}}async function Ie(r){try{let t=new AbortController,n=setTimeout(()=>t.abort(),500),e=await fetch(`http://127.0.0.1:${r}/status`,{signal:t.signal});return clearTimeout(n),e.ok?await e.json():null}catch{return null}}function Pn(r,t){return new Promise((n,e)=>{let s=i=>{r.removeListener("listening",l),e(i)},l=()=>{r.removeListener("error",s),n()};r.once("error",s),r.once("listening",l),r.listen(t,"127.0.0.1")})}async function lt(r={}){let t=r.port??fn,n=r.projectRoot??process.cwd(),e=sn("sha256").update(n).digest("hex").slice(0,12),s=r.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),l=r.tempDir??ne(dn(),"popmelt-bridge"),i=r.maxTurns??40,a=r.maxBudgetUsd??1,p=[...r.allowedTools??mn],m=r.claudePath??"claude",x=r.provider??"claude",C=r.timeoutMs,O=t,v={};for(let o of["claude","codex"])try{let c=nn("which",[o],{encoding:"utf-8"}).trim();v[o]={available:!0,path:c}}catch{v[o]={available:!1,path:null}}function H(o,c){return new Promise(h=>{let d=rt(c,["--version"],{stdio:["ignore","ignore","ignore"]}),f=!1,u=D=>{f||(f=!0,h(D))},y=setTimeout(()=>{d.kill("SIGTERM"),u(!0)},5e3);d.on("error",()=>{clearTimeout(y),u(!1)}),d.on("close",D=>{clearTimeout(y),u(D===0)})})}let[z,X]=await Promise.all([Me(n),Oe(n)]);v.claude&&(v.claude.mcp=z),v.codex&&(v.codex.mcp=X),z.found&&z.name&&p.push(`mcp__${z.name}__*`),await on(l,{recursive:!0}),at(l).catch(()=>{});let R=new Se(1),U=new Set,A=new Pe(n),F=new ge(n),g=new ye(n,F,{claudePath:m,onEvent:o=>{for(let c of U)De(c,o)}}),j=20,S=300*1e3,k=[],I=new Set,B=null,N;R.addListener((o,c,h)=>{for(let d of U)(!h||!d.sourceId||d.sourceId===h)&&De(d,o)}),R.setProcessor(async o=>{let c=o._replyPrompt,h=o._replyImagePaths,d=o.provider??x,f;if(o.threadId){let b=await A.getThread(o.threadId);if(b){for(let T=b.messages.length-1;T>=0;T--)if(b.messages[T].sessionId){f=b.messages[T].sessionId;break}}}let u;if(f&&c){let b=(await A.getThread(o.threadId))?.messages.filter(Y=>Y.role==="human").pop();if(u=b?.replyToQuestion||b?.feedbackSummary||"",h&&h.length>0){u+=`
205
-
206
- The developer attached reference images with their reply:`;for(let Y of h)u+=`
207
- Attached image: use the Read tool to view the image at: ${Y}`}u+=`
208
-
209
- After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(f)u=he(o.feedback,o.imagePaths)+`
210
-
211
- Follow the developer's instructions. If they ask for changes, apply them to the source files.
212
-
213
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
214
-
215
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${o.screenshotPath}`:"");else{let b=!c&&o.threadId?await A.getThreadHistory(o.threadId):void 0,T=c?null:await g.loadModel();u=c??et(o.screenshotPath,o.feedback,{threadHistory:b&&b.length>0?b:void 0,provider:d,imagePaths:o.imagePaths,designModel:T??void 0,screenshotPaths:o.screenshotPaths})}let y=Sn(o.color,`[\u22B9 ${O}:${o.id}]`),D=o.screenshotPaths&&Object.keys(o.screenshotPaths).length>0?`${Object.keys(o.screenshotPaths).length} pages [${Object.keys(o.screenshotPaths).join(", ")}]`:o.screenshotPath;console.log(`${y} Reviewing ${D} (provider: ${d})${o.threadId?` (thread: ${o.threadId})`:""}${f?` (resuming: ${f.slice(0,8)})`:""}`);let L=(b,T)=>{b.type==="delta"&&"text"in b?R.accumulateText(T,"response",b.text):b.type==="thinking"&&"text"in b&&R.accumulateText(T,"thinking",b.text),R.broadcast(b,T,o.sourceId)},{process:V,result:W}=d==="codex"?Ue(o.id,{prompt:u,projectRoot:n,screenshotPath:o.screenshotPath,resumeSessionId:f,model:o.model,onEvent:L}):de(o.id,{prompt:u,projectRoot:n,maxTurns:i,maxBudgetUsd:a,allowedTools:p,claudePath:m,resumeSessionId:f,model:o.model,timeoutMs:C,onEvent:L});R.setActiveProcess(o.id,V);let P=await W;if(o.result=P.text,P.success){console.log(`${y} Iteration complete`),P.fileEdits&&P.fileEdits.length>0&&console.log(`${y} Captured ${P.fileEdits.length} file edit(s): ${P.fileEdits.map(J=>`${J.tool} ${J.file_path}`).join(", ")}`),o.status="done";let b=tt(P.text),T=st(P.text);if(T.length>0&&o.annotationIds&&o.annotationIds.length>0){let J=new Set(o.annotationIds);T.every(_=>J.has(_.annotationId))||(T=T.map((_,Q)=>({..._,annotationId:o.annotationIds[Q%o.annotationIds.length]})))}let Y=P.fileEdits&&P.fileEdits.length>0?P.fileEdits.map(J=>`${J.tool} ${J.file_path.split("/").pop()}`):P.toolsUsed,ee=R.getBufferedEvents(o.id),se=ee?wn(ee.events):void 0;if(o.threadId&&await A.appendMessage(o.threadId,{role:"assistant",timestamp:Date.now(),jobId:o.id,responseText:P.text,resolutions:T.length>0?T:void 0,question:b??void 0,sessionId:P.sessionId,toolsUsed:Y,segments:se&&se.length>0?se:void 0,model:o.model,provider:o.provider}),F.captureGitDiff(n).then(async J=>{let M=Date.now(),_=o.imagePaths?Object.values(o.imagePaths).flat():[],Q=[];if(o.imagePaths)for(let[ie,E]of Object.entries(o.imagePaths))for(let K=0;K<E.length;K++)Q.push(`screenshots/p-${o.id}-${ie}-${K}.webp`);await F.persist({version:1,id:o.id,createdAt:o.createdAt,completedAt:M,durationMs:M-o.createdAt,url:o.feedback.url,viewport:o.feedback.viewport,screenshotPath:`screenshots/s-${o.id}.webp`,pastedImagePaths:Q,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:T.length>0?T:[],question:b??void 0,fileEdits:P.fileEdits??[],toolsUsed:Y,gitDiff:J},o.screenshotPath,_)}).catch(()=>{}),T.length>0&&T.some(M=>(M.finalScope??M.inferredScope)?.breadth==="pattern")&&g.run().catch(()=>{}),o.kind==="synthesize"&&P.text){let J=we(P.text);if(J){Array.isArray(J.rules)&&(J.rules=ue(J.rules));let M=await g.loadModel();M&&(!J.tokens&&M.tokens&&(J.tokens=M.tokens),!J.components&&M.components&&(J.components=M.components)),await g.writeModel(J),console.log(`${y} Synthesize: model.json updated`)}}b&&(console.log(`${y} \u{1F4AC} Question detected: "${b.slice(0,120)}" \u2192 broadcasting to ${U.size} SSE clients (threadId=${o.threadId??o.id}, annotationIds=${o.annotationIds?.join(",")??"none"})`),R.broadcast({type:"question",jobId:o.id,threadId:o.threadId??o.id,question:b,annotationIds:o.annotationIds},o.id,o.sourceId));let te=ot(P.text);te.length>0&&(console.log(`${y} Novel pattern(s): ${te.map(J=>`${J.category}/${J.element}`).join(", ")}`),R.broadcast({type:"novel_patterns",jobId:o.id,patterns:te,threadId:o.threadId},o.id,o.sourceId)),R.broadcast({type:"done",jobId:o.id,success:!0,resolutions:T.length>0?T:void 0,responseText:P.text,threadId:o.threadId},o.id,o.sourceId),k.push({id:o.id,status:"done",completedAt:Date.now(),threadId:o.threadId,annotationIds:o.annotationIds})}else console.error(`${y} Error: ${P.error}`),o.status="error",o.error=P.error,o.threadId&&await A.appendMessage(o.threadId,{role:"assistant",timestamp:Date.now(),jobId:o.id,error:P.error||"Unknown error",model:o.model,provider:o.provider}),R.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:P.error||"Unknown error"},o.id,o.sourceId),k.push({id:o.id,status:"error",completedAt:Date.now(),error:P.error,threadId:o.threadId,annotationIds:o.annotationIds});let G=Date.now()-S;for(;k.length>0&&(k[0].completedAt<G||k.length>j);)k.shift()});let Z=ln(async(o,c)=>{if(vn(o,c),o.method==="OPTIONS"){c.writeHead(204),c.end();return}let h=o.url||"/",d=h.split("?")[0],f=new URL(h,`http://127.0.0.1:${O}`),u=f.pathname;try{if(o.method==="POST"&&u==="/send")await $(o,c);else if(o.method==="GET"&&u==="/events")fe(o,c);else if(o.method==="GET"&&u==="/status")dt(c);else if(o.method==="PATCH"&&u==="/config")await ut(o,c);else if(o.method==="POST"&&u==="/shutdown")w(c,200,{ok:!0}),setTimeout(()=>process.exit(0),100);else if(o.method==="POST"&&u==="/restart")w(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let y of U)try{y.res.end()}catch{}Z.close(()=>{rt(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(o.method==="GET"&&u==="/capabilities")w(c,200,{providers:v});else if(o.method==="POST"&&u==="/mcp/install")await mt(o,c);else if(o.method==="POST"&&u==="/reply")await ce(o,c);else if(o.method==="POST"&&u==="/cancel")pt(o,c);else if(o.method==="POST"&&u==="/materialize")await ht(c);else if(o.method==="POST"&&u==="/model/component")await gt(o,c);else if(o.method==="DELETE"&&u==="/model/component")await yt(o,c);else if(o.method==="PATCH"&&u==="/model/token")await wt(o,c);else if(o.method==="DELETE"&&u==="/model/token")await vt(o,c);else if(o.method==="POST"&&u==="/model/consolidate")g.consolidate().catch(y=>console.error("[Bridge] Consolidation error:",y)),w(c,200,{started:!0});else if(o.method==="POST"&&u==="/model/synthesize")await ft(o,c);else if(o.method==="GET"&&u==="/model"){let y=await g.loadModel();w(c,200,{model:y})}else if(o.method==="GET"&&u.startsWith("/jobs/")&&u.endsWith("/events")){let y=u.slice(6,u.length-7),D=parseInt(f.searchParams.get("afterSeq")??"-1",10),L=R.getBufferedEvents(y,isNaN(D)?-1:D);L?w(c,200,L):w(c,404,{error:"Unknown job"})}else if(o.method==="GET"&&d.startsWith("/files/"))await bt(d.slice(7),c);else if(o.method==="GET"&&u==="/threads/recent"){let y=Math.min(Math.max(parseInt(f.searchParams.get("limit")??"5",10)||5,1),20),D=await A.listRecent(y);w(c,200,D)}else if(o.method==="GET"&&u.startsWith("/thread/")){let y=u.slice(8);await kt(y,c)}else o.method==="GET"&&(u==="/canvas"||u==="/canvas/")?St(o,c):o.method==="GET"&&u==="/canvas/manifest"?await Pt(c):o.method==="GET"&&u==="/canvas/app.mjs"?await xt(c):w(c,404,{error:"Not found"})}catch(y){console.error("[Bridge] Request error:",y),w(c,500,{error:y instanceof Error?y.message:"Internal error"})}});async function $(o,c){let{screenshot:h,feedback:d,color:f,provider:u,model:y,sourceId:D,pastedImages:L,pageScreenshots:V}=await Ae(o),W;try{W=JSON.parse(d)}catch{w(c,400,{error:"Invalid feedback JSON"});return}let P=be().slice(0,8),G={};if(V.length>0)for(let E of V){let K=encodeURIComponent(E.pathname),oe=ne(l,`screenshot-${P}-${K}.webp`);await ke(oe,E.data),G[E.pathname]=oe}let b=ne(l,`screenshot-${P}.webp`);await ke(b,h);let T={};if(L.length>0)for(let E of L){let K=ne(l,`pasted-${P}-${E.annotationId}-${E.index}.webp`);await ke(K,E.data),T[E.annotationId]||(T[E.annotationId]=[]),T[E.annotationId].push(K)}let Y=W.annotations.map(E=>E.linkedSelector?E.pathname?`${E.pathname}:${E.linkedSelector}`:E.linkedSelector:null).filter(E=>!!E),ee;if(Y.length>0){let E=await A.findContinuationThread(Y);E?(ee=E.id,await A.addElementIdentifiers(ee,Y)):ee=(await A.createThread(P,Y)).id}else ee=(await A.createThread(P,[])).id;let se=W.annotations.map(E=>E.id),te=Object.keys(G).length>0,J={id:P,status:"queued",screenshotPath:b,feedback:W,createdAt:Date.now(),color:f,threadId:ee,annotationIds:se,provider:u==="claude"||u==="codex"?u:void 0,model:y||void 0,...Object.keys(T).length>0?{imagePaths:T}:{},sourceId:D||void 0,...te?{screenshotPaths:G}:{}},M=new Set(W.annotations.map(E=>E.pathname).filter(Boolean)),_;if(M.size>1){let E=new Map;for(let K of W.annotations){let oe=K.pathname||"(unknown)";E.has(oe)||E.set(oe,[]),E.get(oe).push(K.instruction||`[${K.type}]`)}_=[...E.entries()].map(([K,oe])=>`\`${K}\`
216
- ${oe.map(Tt=>`- ${Tt}`).join(`
217
- `)}`).join(`
218
- `)}else _=W.annotations.map(E=>E.instruction||`[${E.type}]`).join("; ");let Q=he(W,Object.keys(T).length>0?T:void 0);await A.appendMessage(ee,{role:"human",timestamp:Date.now(),jobId:P,screenshotPath:b,...te?{screenshotPaths:G}:{},...Object.keys(T).length>0?{imagePaths:T}:{},annotationIds:se,feedbackSummary:_,feedbackContext:Q||void 0});let ie=R.enqueue(J);w(c,200,{jobId:P,position:ie,threadId:ee})}async function ce(o,c){let h=o.headers["content-type"]||"",d,f,u,y,D,L,V=[];if(h.includes("multipart/form-data")){let M=await Ae(o),_=M.feedback?JSON.parse(M.feedback):{};d=_.threadId,f=_.reply,u=_.color,y=_.provider,D=_.model,L=_.sourceId||M.sourceId;for(let Q of M.pastedImages)V.push(Q.data)}else{let M=[];for await(let ie of o)M.push(typeof ie=="string"?Buffer.from(ie):ie);let _=Buffer.concat(M).toString("utf-8"),Q;try{Q=JSON.parse(_)}catch{w(c,400,{error:"Invalid JSON"});return}d=Q.threadId,f=Q.reply,u=Q.color,y=Q.provider,D=Q.model,L=Q.sourceId}if(!d||!f){w(c,400,{error:"Missing threadId or reply"});return}if(!await A.getThread(d)){w(c,404,{error:"Thread not found"});return}let P=be().slice(0,8),G=[];for(let M=0;M<V.length;M++){let _=ne(l,`reply-${P}-${M}.webp`);await ke(_,V[M]),G.push(_)}let b="";{let M=await A.getThreadHistory(d);for(let _=M.length-1;_>=0;_--)if(M[_].screenshotPath){b=M[_].screenshotPath;break}}if(!b&&!I.has(d)){w(c,400,{error:"No screenshot available"});return}await A.appendMessage(d,{role:"human",timestamp:Date.now(),jobId:P,replyToQuestion:f,screenshotPath:b,...G.length>0?{replyImagePaths:G}:{}});let T=await A.getThreadHistory(d),Y=[];for(let M of T)if(M.annotationIds)for(let _ of M.annotationIds)Y.includes(_)||Y.push(_);let ee=y==="claude"||y==="codex"?y:void 0,se=nt(b,T,ee,G.length>0?G:void 0),te={id:P,status:"queued",screenshotPath:b,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:u,threadId:d,annotationIds:Y.length>0?Y:void 0,provider:ee,model:D||void 0,sourceId:L||void 0};I.has(d)&&(te.kind="synthesize"),te._replyPrompt=se,G.length>0&&(te._replyImagePaths=G);let J=R.enqueue(te);w(c,200,{jobId:P,position:J,threadId:d})}function fe(o,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
219
- data: {"status":"connected"}
220
-
221
- `),o.headers.origin&&ct(o.headers.origin)&&s!==o.headers.origin&&(s=o.headers.origin);let d=new URL(o.url||"/",`http://127.0.0.1:${O}`).searchParams.get("sourceId")||void 0,f={id:be().slice(0,8),res:c,sourceId:d};U.add(f),o.on("close",()=>{U.delete(f)})}function dt(o){let c=R.allActive;w(o,200,{ok:!0,version:xe,projectId:e,devOrigin:s,activeJob:c[0]?{id:c[0].id,status:c[0].status}:null,activeJobs:c.map(h=>({id:h.id,status:h.status,threadId:h.threadId,annotationIds:h.annotationIds,color:h.color})),queueDepth:R.depth,recentJobs:k})}async function ut(o,c){let h=await new Promise(d=>{let f="";o.on("data",u=>{f+=u.toString()}),o.on("end",()=>d(f))});try{let d=JSON.parse(h);typeof d.devOrigin=="string"&&(s=d.devOrigin||null),w(c,200,{ok:!0,devOrigin:s})}catch{w(c,400,{error:"Invalid JSON"})}}async function pt(o,c){let d=new URL(o.url||"/",`http://127.0.0.1:${O}`).searchParams.get("jobId"),u=(d?R.allActive.filter(D=>D.id===d):R.allActive).map(D=>D.threadId).filter(Boolean),y=d?R.cancelJob(d):R.cancelActive();for(let D of u)await A.appendMessage(D,{role:"assistant",timestamp:Date.now(),jobId:d||"",cancelled:!0});w(c,200,{cancelled:y})}async function ht(o){if(g.isRunning){w(o,200,{skipped:!0,reason:"Already running"});return}let c=await g.getUnmaterializedPatternDecisions();if(c.length===0){w(o,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}g.run().catch(()=>{}),w(o,200,{started:!0,decisionCount:c.length,decisionIds:c.map(h=>h.id)})}async function ft(o,c){let h=await g.loadModel();if(!h){w(c,400,{error:"No model exists yet"});return}let d,f;try{let P=[];for await(let b of o)P.push(typeof b=="string"?Buffer.from(b):b);let G=JSON.parse(Buffer.concat(P).toString());d=G.provider,f=G.model}catch{}let u=ze(h),y=be().slice(0,8),L=(await A.createThread(y,[])).id;I.add(L),await A.appendMessage(L,{role:"human",timestamp:Date.now(),jobId:y,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let V={id:y,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:L,kind:"synthesize",provider:d==="claude"||d==="codex"?d:void 0,model:f||void 0};V._replyPrompt=u;let W=R.enqueue(V);w(c,200,{jobId:y,position:W,threadId:L})}async function mt(o,c){let h=[];for await(let D of o)h.push(typeof D=="string"?Buffer.from(D):D);let d;if(h.length>0)try{d=JSON.parse(Buffer.concat(h).toString("utf-8")).serverUrl}catch{}let f=[];v.claude?.available&&v.claude.mcp&&!v.claude.mcp.found&&f.push(await Ke(d)),v.codex?.available&&v.codex.mcp&&!v.codex.mcp.found&&f.push(await Ze(d));let[u,y]=await Promise.all([Me(n),Oe(n)]);v.claude&&(v.claude.mcp=u),v.codex&&(v.codex.mcp=y),w(c,200,{results:f,capabilities:{providers:v}})}async function gt(o,c){let h=[];for await(let u of o)h.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{w(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){w(c,400,{error:"Missing or invalid name"});return}let f=await g.addComponent(d.name);w(c,200,f)}async function yt(o,c){let h=[];for await(let u of o)h.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{w(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){w(c,400,{error:"Missing or invalid name"});return}let f=await g.removeComponent(d.name);w(c,200,f)}async function wt(o,c){let h=[];for await(let u of o)h.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{w(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"||typeof d.value!="string"){w(c,400,{error:"Missing or invalid path/value"});return}let f=await g.updateToken(d.path,d.value);w(c,200,f)}async function vt(o,c){let h=[];for await(let u of o)h.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{w(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"){w(c,400,{error:"Missing or invalid path"});return}let f=await g.removeToken(d.path);w(c,200,f)}function St(o,c){let h=s??"http://localhost:3000";if(!s){let f=o.headers.referer||o.headers.origin;if(f)try{let u=new URL(typeof f=="string"?f:f[0]||"");(u.hostname==="localhost"||u.hostname==="127.0.0.1")&&(h=u.origin)}catch{}}let d=Be(O,h);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(d)}async function Pt(o){let c=Date.now();if(B&&c<B.expires){w(o,200,B.data);return}try{let{scanForComponents:h}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:d}=await import("./render-generator-HWFLZYC3.mjs"),f=await h(n);B={data:f,expires:c+5e3},d(f,n,N).then(u=>{N=u}).catch(u=>console.warn("[Bridge] Render generation failed:",u)),w(o,200,f)}catch(h){console.error("[Bridge] Scanner error:",h),w(o,500,{error:"Failed to scan components"})}}async function xt(o){let c=[ne(n,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ne(n,"packages","popmelt","dist","canvas.mjs")];try{let h=hn(import.meta.url);c.unshift(ne(pn(h),"canvas.mjs"))}catch{}for(let h of c)try{let d=await it(h,"utf-8");o.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),o.end(d);return}catch{}console.error("[Bridge] Canvas bundle not found in:",c),w(o,404,{error:"Canvas bundle not found"})}async function bt(o,c){if(!o||o.includes("/")||o.includes("\\")||o.includes("..")){w(c,400,{error:"Invalid filename"});return}try{let h=await it(ne(l,o)),d=o.split(".").pop()?.toLowerCase(),f=d==="png"?"image/png":d==="webp"?"image/webp":d==="jpg"||d==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":f,"Cache-Control":"public, max-age=3600"}),c.end(h)}catch{w(c,404,{error:"File not found"})}}function me(o){return`/files/${un(o)}`}async function kt(o,c){let h=await A.getThread(o);if(!h){w(c,404,{error:"Thread not found"});return}let d=h.messages.map(({screenshotPath:f,screenshotPaths:u,imagePaths:y,replyImagePaths:D,...L})=>({...L,...f?{screenshotUrl:me(f)}:{},...u?{screenshotUrls:Object.fromEntries(Object.entries(u).map(([V,W])=>[V,me(W)]))}:{},...y?{imageUrls:Object.fromEntries(Object.entries(y).map(([V,W])=>[V,W.map(me)]))}:{},...D?{replyImageUrls:D.map(me)}:{}}));w(c,200,{id:h.id,createdAt:h.createdAt,messages:d})}let _e=9,Ne=!1;for(let o=t;o<t+_e;o++)try{await Pn(Z,o),O=o,Ne=!0,console.log(`[\u22B9 is watching :${O}]`);break}catch(c){if(c.code==="EADDRINUSE"){let h=await Ie(o);if(h&&h.projectId===e)return console.log(`[\u22B9 already watching :${o}]`),{port:o,projectId:e,close:async()=>{}};continue}throw c}if(!Ne)throw new Error(`[Bridge] All ports ${t}\u2013${t+_e-1} in use`);for(let[o,c]of Object.entries(v))!c.available||!c.path||H(o,c.path).then(h=>{if(h)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)De(d,{type:"capabilities_changed",data:{}})}});let It=setInterval(()=>{at(l).catch(()=>{})},gn);return{port:O,projectId:e,close:async()=>{clearInterval(It),await R.destroyAsync();for(let o of U)try{o.res.end()}catch{}return U.clear(),new Promise(o=>{Z.close(()=>o())})}}}async function at(r){try{let t=await rn(r),n=Date.now();for(let e of t){let s=ne(r,e);try{let l=await an(s);n-l.mtimeMs>yn&&await cn(s)}catch{}}}catch{}}var Rn=1111;async function Os(r){if(process.env.NODE_ENV==="production"&&!r?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(r?.detached)return En(r);let t=await lt(r);return process.env.POPMELT_BRIDGE_PORT=String(t.port),t}async function En(r){let t=r.port??Rn,n=r.projectRoot??process.cwd(),e=bn("sha256").update(n).digest("hex").slice(0,12);for(let i=t;i<t+10;i++){let a=await Ie(i);if(a&&a.projectId===e){if(a.version&&a.version!==xe){try{await fetch(`http://127.0.0.1:${i}/shutdown`,{method:"POST"})}catch{}await new Promise(m=>setTimeout(m,500));break}let p=r.devOrigin;if(p&&a.devOrigin!==p)try{await fetch(`http://127.0.0.1:${i}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:p})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(i),{port:i,projectId:e,close:async()=>{}}}}let s=In(kn(Tn(import.meta.url)),"bridge-entry.mjs");xn(process.execPath,[s],{detached:!0,stdio:"ignore",env:{...process.env,POPMELT_PORT:String(t),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:r.devOrigin??""}}).unref();let l=Date.now()+3e3;for(;Date.now()<l;){await new Promise(i=>setTimeout(i,100));for(let i=t;i<t+10;i++){let a=await Ie(i);if(a&&a.projectId===e)return process.env.POPMELT_BRIDGE_PORT=String(i),{port:i,projectId:e,close:async()=>{}}}}throw new Error(`[Bridge] Detached bridge failed to start within 3s (port ${t})`)}export{Os as startPopmelt};