@popmelt.com/core 0.7.3 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge-entry.mjs +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/index.mjs +20 -20
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/{server-5Q2HPNSJ.mjs → server-X7YF2NX2.mjs} +1 -1
- package/dist/server.mjs +1 -1
- package/package.json +1 -1
package/dist/plugin-astro.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{request as y}from"http";function
|
|
1
|
+
import{request as y}from"http";async function _(a){try{let l=await fetch(`${a}/status`);return l.ok?await l.json():null}catch{return null}}function w(a){let l=a?.basePath??"/popmelt",h=a?.bridge!==!1,n=null,c=null,P=null;return{name:"popmelt",hooks:{async"astro:server:setup"({server:u}){if(!h||process.env.POPMELT_BRIDGE_URL){if(process.env.POPMELT_BRIDGE_URL)try{n=new URL(process.env.POPMELT_BRIDGE_URL).port?parseInt(new URL(process.env.POPMELT_BRIDGE_URL).port,10):null,c=process.env.POPMELT_PROJECT_ID||null,c||(c=(await _(process.env.POPMELT_BRIDGE_URL))?.projectId??null)}catch{}}else try{let{startPopmelt:o}=await import("./server-X7YF2NX2.mjs"),t=u.config,p=t?.server?.host===!0?"0.0.0.0":t?.server?.host||"localhost",i=t?.server?.port??4321,d=`http://${p==="0.0.0.0"?"localhost":p}:${i}`,s=await o({port:a?.port,projectRoot:a?.projectRoot,devOrigin:d,force:!0,detached:!0});n=s.port,c=s.projectId,P=s.close,console.log(`[popmelt] bridge ready at http://localhost:${n}`)}catch(o){console.warn("[popmelt] bridge failed to start:",o.message??o)}u.middlewares.use((o,t,p)=>{let i=o.url||"";if(i.startsWith(l)){if(n===null)return p();let d=`http://localhost:${n}`,s="/canvas"+i.slice(l.length),r=new URL(s,d),e=y(r,{method:o.method,headers:{...o.headers,host:r.host}},g=>{t.writeHead(g.statusCode||502,g.headers),g.pipe(t)});e.on("error",()=>{t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`Popmelt bridge not running on port ${n}`)}),o.pipe(e);return}if(n!==null&&(o.headers.accept?.includes("text/html")||i==="/"||i.endsWith(".html"))){let d=t.write,s=t.end,r="";t.write=function(e,...g){return r+=typeof e=="string"?e:e.toString("utf8"),!0},t.end=function(e,...g){e&&(r+=typeof e=="string"?e:e.toString("utf8"));let f=`http://localhost:${n}`,m=`<script type="text/javascript">window.__POPMELT_BRIDGE_URL__=${JSON.stringify(f)};window.__POPMELT_PROJECT_ID__=${JSON.stringify(c)};</script>`;r=r.replace("<head>",`<head>${m}`),t.getHeader("content-length")&&t.setHeader("content-length",Buffer.byteLength(r)),d.call(t,r,"utf8"),s.call(t)}}p()})}}}}export{w as popmelt};
|
package/dist/plugin-vite.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{request as m}from"http";function
|
|
1
|
+
import{request as m}from"http";async function f(n){try{let o=await fetch(`${n}/status`);return o.ok?await o.json():null}catch{return null}}function R(n){let o=n?.basePath??"/popmelt",h=n?.bridge!==!1,e=null,s=null,P=null;return{name:"popmelt",async configureServer(a){if(!h||process.env.POPMELT_BRIDGE_URL){if(process.env.POPMELT_BRIDGE_URL)try{e=new URL(process.env.POPMELT_BRIDGE_URL).port?parseInt(new URL(process.env.POPMELT_BRIDGE_URL).port,10):null,s=process.env.POPMELT_PROJECT_ID||null,s||(s=(await f(process.env.POPMELT_BRIDGE_URL))?.projectId??null)}catch{}}else try{let{startPopmelt:t}=await import("./server-X7YF2NX2.mjs"),r=a.config,i=r?.server?.host===!0?"0.0.0.0":r?.server?.host||"localhost",c=r?.server?.port??5173,p=`http://${i==="0.0.0.0"?"localhost":i}:${c}`,l=await t({port:n?.port,projectRoot:n?.projectRoot,devOrigin:p,force:!0,detached:!0});e=l.port,s=l.projectId,P=l.close,console.log(`[popmelt] bridge ready at http://localhost:${e}`)}catch(t){console.warn("[popmelt] bridge failed to start:",t.message??t)}a.middlewares.use((t,r,i)=>{let c=t.url||"";if(!c.startsWith(o)||e===null)return i();let p=`http://localhost:${e}`,l="/canvas"+c.slice(o.length),u=new URL(l,p),g=m(u,{method:t.method,headers:{...t.headers,host:u.host}},d=>{r.writeHead(d.statusCode||502,d.headers),d.pipe(r)});g.on("error",()=>{r.writeHead(502,{"Content-Type":"text/plain"}),r.end(`Popmelt bridge not running on port ${e}`)}),t.pipe(g)})},transformIndexHtml(){if(e===null)return;let a=`http://localhost:${e}`;return[{tag:"script",attrs:{type:"text/javascript"},children:`window.__POPMELT_BRIDGE_URL__=${JSON.stringify(a)};window.__POPMELT_PROJECT_ID__=${JSON.stringify(s)};`,injectTo:"head-prepend"}]}}}export{R as popmelt};
|
|
@@ -328,7 +328,7 @@ url = "${s}"
|
|
|
328
328
|
`)}function dn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function un(s,t,n,e){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=t.find(a=>a.role==="human"&&a.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),t.length>0){o.push(""),o.push("## Conversation History");let a=0;for(let c of t)c.role==="human"?(a++,c.replyToQuestion?(o.push(`### Round ${a} (human) \u2014 reply`),o.push(`"${c.replyToQuestion}"`)):(o.push(`### Round ${a} (human)`),c.feedbackSummary&&o.push(`Annotations: ${c.feedbackSummary}`))):c.question?(o.push(`### Round ${a} (assistant) \u2014 question`),o.push(`"${c.question}"`)):(o.push(`### Round ${a} (assistant)`),c.responseText&&o.push(`Response: ${c.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e&&e.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let a of e)o.push(`Attached image: use the Read tool to view the image at: ${a}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output a resolution block listing what you did for each annotation:"),o.push("<resolution>"),o.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),o.push("</resolution>"),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
|
|
329
329
|
`)}function Qs(s){if(typeof s!="object"||s===null)return!1;let t=s;return(t.breadth==="instance"||t.breadth==="pattern")&&(t.target==="element"||t.target==="component"||t.target==="token")}function Zs(s){if(typeof s!="object"||s===null||typeof s.annotationId!="string"||s.status!=="resolved"&&s.status!=="needs_review"||typeof s.summary!="string")return!1;let t=s;for(let n of["declaredScope","inferredScope","finalScope"])if(t[n]!==void 0&&t[n]!==null&&!Qs(t[n]))return!1;return!0}function pn(s){let t=s.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(Zs):[]}catch{return[]}}function fn(s){let t=s.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 o=e;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}import{execFile as eo}from"child_process";import{readdir as to,readFile as no,stat as so}from"fs/promises";import{homedir as Ce}from"os";import{join as me}from"path";var Ye=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static"},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static"}],$e=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],Oe={id:"",label:"Default",source:"cli"},oo=/^\s*-\s+"([^"]+)"/;function ro(s){let t=[],n=!1;for(let e of s.split(`
|
|
330
330
|
`)){if(/^\s*`model`:/.test(e)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(e))break;if(!n)continue;let o=e.match(oo);if(!o?.[1])continue;let i=o[1];t.push({id:i,label:gt(i),source:"cli"})}return Ve([Oe,...t])}function io(s){let t=JSON.parse(s);return(Array.isArray(t.models)?t.models:[]).filter(e=>e.visibility===void 0||e.visibility==="list").sort((e,o)=>{let i=typeof e.priority=="number"?e.priority:Number.MAX_SAFE_INTEGER,a=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-a}).flatMap(e=>{let o=typeof e.slug=="string"?e.slug:typeof e.id=="string"?e.id:"";if(!o)return[];let i=typeof e.display_name=="string"&&e.display_name.trim()?e.display_name.trim():gt(o);return[{id:o,label:i,source:"cli"}]})}function ao(s){let t=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Ve(t.map(n=>({id:n,label:gt(n),source:"cli"})))}function gt(s){if(!s)return"Default";let t={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=s.replace(/-\d{8,}$/,"");if(t[s])return t[s];if(t[n])return t[n];let e=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(e){let i=e[1]==="sonnet"?"Sonn":po(e[1]),a=e[2]&&e[3]?` ${e[2]}.${e[3]}`:"";return`${i}${a}${e[4]?" Fast":""}`}let o=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let i=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${i}`:o[3]==="codex"?`Codex ${i}`:o[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function hn(s="copilot"){let t=await qe(s,["help","config"]),n=ro(t);return n.length>1?n:[Oe]}async function mn(s="codex"){let t=await qe(s,["debug","models"]).catch(async()=>{let e=process.env.CODEX_HOME||me(Ce(),".codex");return vn(me(e,"models_cache.json"))}),n=io(t);return n.length>0?Ve([...n,...$e]):$e}async function gn(s="claude"){let t=me(Ce(),".claude"),n=[me(Ce(),".claude","stats-cache.json"),me(Ce(),".claude","settings.json"),me(Ce(),".claude.json"),me(t,"cache","changelog.md")],[e,o,i]=await Promise.all([qe(s,["--help"]).catch(()=>""),qe(s,["--version"]).catch(()=>""),co(t).catch(()=>[])]),a=uo([...n,...i]),c=await Promise.all(a.map(k=>vn(k).catch(()=>""))),h=ao([e,o,...c].join(`
|
|
331
|
-
`));return Ve([...Ye,...h])}function qe(s,t,n=5e3){return new Promise((e,o)=>{eo(s,t,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}e(a)})})}async function vn(s){return no(s,"utf-8")}async function co(s){let t=[me(s,"projects"),me(s,"telemetry")],n=[];for(let e of t)await yn(e,n,4);return n.sort((e,o)=>o.mtimeMs-e.mtimeMs).slice(0,80).map(e=>e.path)}async function yn(s,t,n){if(n<0)return;let e;try{e=await to(s,{withFileTypes:!0})}catch{return}await Promise.all(e.map(async o=>{let i=me(s,o.name);if(o.isDirectory()){await yn(i,t,n-1);return}if(!(!o.isFile()||!lo(o.name)))try{let a=await so(i);if(a.size>2e6)return;t.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function lo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function Ve(s){let t=new Set,n=[];for(let e of s)t.has(e.id)||(t.add(e.id),n.push(e));return n}function uo(s){return[...new Set(s)]}function po(s){return s.charAt(0).toUpperCase()+s.slice(1)}var Ke=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 o=this.bufferEvent(n,t);for(let i of this.listeners)i(o,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let o={...n,seq:e.nextSeq++};return e.events.push(o),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),o}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),o=this.accumulators.get(t)??{response:"",thinking:""},i=this.activeJobs.has(t);if(!e)return null;let a=n<0?e.events:e.events.filter(c=>c.seq>n);return{jobId:t,events:a,currentSeq:e.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(t,n,e){let o=this.accumulators.get(t);o||(o={response:"",thinking:""},this.accumulators.set(t,o)),o[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,threadId:e.threadId,message:"Cancelled by user",cancelled:!0,provider:e.provider,model:e.model},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(o=>{let i=!1,a=()=>{i||(i=!0,o())};e.on("exit",a),e.on("error",a),setTimeout(()=>{if(!i){try{e.kill("SIGKILL")}catch{}setTimeout(a,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,threadId:t.threadId,message:t.error,provider:t.provider,model:t.model},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 fo,readFile as ho,writeFile as mo}from"fs/promises";import{dirname as go,join as vo}from"path";var yo={version:1,threads:{}},Qe=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=vo(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await ho(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={...yo,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 o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>e.has(a)))return o;return null}async createThread(t,n){let e=await this.load(),o={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=o,await this.persist(),o}async appendMessage(t,n){let o=(await this.load()).threads[t];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let o=(await this.load()).threads[t];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((o,i)=>i.updatedAt-o.updatedAt),e.slice(0,t).map(o=>{let a=o.messages.find(c=>c.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(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 fo(go(this.filePath),{recursive:!0}),await mo(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var Ze="0.7.
|
|
331
|
+
`));return Ve([...Ye,...h])}function qe(s,t,n=5e3){return new Promise((e,o)=>{eo(s,t,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}e(a)})})}async function vn(s){return no(s,"utf-8")}async function co(s){let t=[me(s,"projects"),me(s,"telemetry")],n=[];for(let e of t)await yn(e,n,4);return n.sort((e,o)=>o.mtimeMs-e.mtimeMs).slice(0,80).map(e=>e.path)}async function yn(s,t,n){if(n<0)return;let e;try{e=await to(s,{withFileTypes:!0})}catch{return}await Promise.all(e.map(async o=>{let i=me(s,o.name);if(o.isDirectory()){await yn(i,t,n-1);return}if(!(!o.isFile()||!lo(o.name)))try{let a=await so(i);if(a.size>2e6)return;t.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function lo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function Ve(s){let t=new Set,n=[];for(let e of s)t.has(e.id)||(t.add(e.id),n.push(e));return n}function uo(s){return[...new Set(s)]}function po(s){return s.charAt(0).toUpperCase()+s.slice(1)}var Ke=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 o=this.bufferEvent(n,t);for(let i of this.listeners)i(o,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let o={...n,seq:e.nextSeq++};return e.events.push(o),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),o}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),o=this.accumulators.get(t)??{response:"",thinking:""},i=this.activeJobs.has(t);if(!e)return null;let a=n<0?e.events:e.events.filter(c=>c.seq>n);return{jobId:t,events:a,currentSeq:e.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(t,n,e){let o=this.accumulators.get(t);o||(o={response:"",thinking:""},this.accumulators.set(t,o)),o[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,threadId:e.threadId,message:"Cancelled by user",cancelled:!0,provider:e.provider,model:e.model},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(o=>{let i=!1,a=()=>{i||(i=!0,o())};e.on("exit",a),e.on("error",a),setTimeout(()=>{if(!i){try{e.kill("SIGKILL")}catch{}setTimeout(a,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,threadId:t.threadId,message:t.error,provider:t.provider,model:t.model},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 fo,readFile as ho,writeFile as mo}from"fs/promises";import{dirname as go,join as vo}from"path";var yo={version:1,threads:{}},Qe=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=vo(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await ho(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={...yo,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 o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>e.has(a)))return o;return null}async createThread(t,n){let e=await this.load(),o={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=o,await this.persist(),o}async appendMessage(t,n){let o=(await this.load()).threads[t];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let o=(await this.load()).threads[t];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((o,i)=>i.updatedAt-o.updatedAt),e.slice(0,t).map(o=>{let a=o.messages.find(c=>c.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(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 fo(go(this.filePath),{recursive:!0}),await mo(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var Ze="0.7.4";var To=1111,Io=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Mo=1800*1e3,Co=3600*1e3;function kn(s){if(!s)return!1;try{let t=new URL(s);return t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="::1"||t.hostname==="[::1]"}catch{return!1}}function $o(s){let t=[];for(let n of s)if(n.type==="delta"){let e=n.text;if(!e)continue;let o=t[t.length-1];o&&o.kind==="text"?o.text+=e:t.push({kind:"text",text:e})}else if(n.type==="tool_use"){let e=n.tool||"",o=n.file??void 0,i=n.content??void 0,a=o?o.split("/").pop()??o:void 0,c;switch(e){case"Read":c=a?`Reading ${a}`:"Reading file";break;case"Edit":c=a?`Editing ${a}`:"Editing file";break;case"Write":c=a?`Writing ${a}`:"Writing file";break;case"Bash":c=i?i.split(`
|
|
332
332
|
`)[0].trim().slice(0,60):"Running command";break;case"Glob":c="Searching files";break;case"Grep":c="Searching code";break;case"WebFetch":c="Fetching page";break;case"WebSearch":c="Searching web";break;default:c=e?`Using ${e}`:"tool";break}let h=o??i??void 0,k=t[t.length-1];k&&k.kind==="tool_group"&&k.tool===e?k.items.push({label:c,detail:h}):t.push({kind:"tool_group",tool:e,items:[{label:c,detail:h}]})}return t}function Oo(s,t){let n=s.headers.origin;kn(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, X-Popmelt-Project-Id"))}function y(s,t,n){s.writeHead(t,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}function _o(s,t){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||t.searchParams.get("projectId")||null}function Ao(s,t){if(!s)return t;let n=s.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return t;let[,e,o,i]=n;return`\x1B[38;2;${parseInt(e,16)};${parseInt(o,16)};${parseInt(i,16)}m${t}\x1B[0m`}function yt(s,t){try{s.res.write(`event: ${t.type}
|
|
333
333
|
data: ${JSON.stringify(t)}
|
|
334
334
|
|
package/dist/server.mjs
CHANGED
|
@@ -328,7 +328,7 @@ url = "${s}"
|
|
|
328
328
|
`)}function dn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function un(s,t,n,e){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=t.find(a=>a.role==="human"&&a.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),t.length>0){o.push(""),o.push("## Conversation History");let a=0;for(let c of t)c.role==="human"?(a++,c.replyToQuestion?(o.push(`### Round ${a} (human) \u2014 reply`),o.push(`"${c.replyToQuestion}"`)):(o.push(`### Round ${a} (human)`),c.feedbackSummary&&o.push(`Annotations: ${c.feedbackSummary}`))):c.question?(o.push(`### Round ${a} (assistant) \u2014 question`),o.push(`"${c.question}"`)):(o.push(`### Round ${a} (assistant)`),c.responseText&&o.push(`Response: ${c.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e&&e.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let a of e)o.push(`Attached image: use the Read tool to view the image at: ${a}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output a resolution block listing what you did for each annotation:"),o.push("<resolution>"),o.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),o.push("</resolution>"),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
|
|
329
329
|
`)}function Qs(s){if(typeof s!="object"||s===null)return!1;let t=s;return(t.breadth==="instance"||t.breadth==="pattern")&&(t.target==="element"||t.target==="component"||t.target==="token")}function Zs(s){if(typeof s!="object"||s===null||typeof s.annotationId!="string"||s.status!=="resolved"&&s.status!=="needs_review"||typeof s.summary!="string")return!1;let t=s;for(let n of["declaredScope","inferredScope","finalScope"])if(t[n]!==void 0&&t[n]!==null&&!Qs(t[n]))return!1;return!0}function pn(s){let t=s.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(Zs):[]}catch{return[]}}function fn(s){let t=s.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 o=e;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}import{execFile as eo}from"child_process";import{readdir as to,readFile as no,stat as so}from"fs/promises";import{homedir as Ce}from"os";import{join as me}from"path";var Ye=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static"},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static"}],$e=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],Oe={id:"",label:"Default",source:"cli"},oo=/^\s*-\s+"([^"]+)"/;function ro(s){let t=[],n=!1;for(let e of s.split(`
|
|
330
330
|
`)){if(/^\s*`model`:/.test(e)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(e))break;if(!n)continue;let o=e.match(oo);if(!o?.[1])continue;let i=o[1];t.push({id:i,label:gt(i),source:"cli"})}return Ve([Oe,...t])}function io(s){let t=JSON.parse(s);return(Array.isArray(t.models)?t.models:[]).filter(e=>e.visibility===void 0||e.visibility==="list").sort((e,o)=>{let i=typeof e.priority=="number"?e.priority:Number.MAX_SAFE_INTEGER,a=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-a}).flatMap(e=>{let o=typeof e.slug=="string"?e.slug:typeof e.id=="string"?e.id:"";if(!o)return[];let i=typeof e.display_name=="string"&&e.display_name.trim()?e.display_name.trim():gt(o);return[{id:o,label:i,source:"cli"}]})}function ao(s){let t=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Ve(t.map(n=>({id:n,label:gt(n),source:"cli"})))}function gt(s){if(!s)return"Default";let t={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=s.replace(/-\d{8,}$/,"");if(t[s])return t[s];if(t[n])return t[n];let e=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(e){let i=e[1]==="sonnet"?"Sonn":po(e[1]),a=e[2]&&e[3]?` ${e[2]}.${e[3]}`:"";return`${i}${a}${e[4]?" Fast":""}`}let o=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let i=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${i}`:o[3]==="codex"?`Codex ${i}`:o[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function hn(s="copilot"){let t=await qe(s,["help","config"]),n=ro(t);return n.length>1?n:[Oe]}async function mn(s="codex"){let t=await qe(s,["debug","models"]).catch(async()=>{let e=process.env.CODEX_HOME||me(Ce(),".codex");return vn(me(e,"models_cache.json"))}),n=io(t);return n.length>0?Ve([...n,...$e]):$e}async function gn(s="claude"){let t=me(Ce(),".claude"),n=[me(Ce(),".claude","stats-cache.json"),me(Ce(),".claude","settings.json"),me(Ce(),".claude.json"),me(t,"cache","changelog.md")],[e,o,i]=await Promise.all([qe(s,["--help"]).catch(()=>""),qe(s,["--version"]).catch(()=>""),co(t).catch(()=>[])]),a=uo([...n,...i]),c=await Promise.all(a.map(k=>vn(k).catch(()=>""))),h=ao([e,o,...c].join(`
|
|
331
|
-
`));return Ve([...Ye,...h])}function qe(s,t,n=5e3){return new Promise((e,o)=>{eo(s,t,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}e(a)})})}async function vn(s){return no(s,"utf-8")}async function co(s){let t=[me(s,"projects"),me(s,"telemetry")],n=[];for(let e of t)await yn(e,n,4);return n.sort((e,o)=>o.mtimeMs-e.mtimeMs).slice(0,80).map(e=>e.path)}async function yn(s,t,n){if(n<0)return;let e;try{e=await to(s,{withFileTypes:!0})}catch{return}await Promise.all(e.map(async o=>{let i=me(s,o.name);if(o.isDirectory()){await yn(i,t,n-1);return}if(!(!o.isFile()||!lo(o.name)))try{let a=await so(i);if(a.size>2e6)return;t.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function lo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function Ve(s){let t=new Set,n=[];for(let e of s)t.has(e.id)||(t.add(e.id),n.push(e));return n}function uo(s){return[...new Set(s)]}function po(s){return s.charAt(0).toUpperCase()+s.slice(1)}var Ke=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 o=this.bufferEvent(n,t);for(let i of this.listeners)i(o,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let o={...n,seq:e.nextSeq++};return e.events.push(o),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),o}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),o=this.accumulators.get(t)??{response:"",thinking:""},i=this.activeJobs.has(t);if(!e)return null;let a=n<0?e.events:e.events.filter(c=>c.seq>n);return{jobId:t,events:a,currentSeq:e.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(t,n,e){let o=this.accumulators.get(t);o||(o={response:"",thinking:""},this.accumulators.set(t,o)),o[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,threadId:e.threadId,message:"Cancelled by user",cancelled:!0,provider:e.provider,model:e.model},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(o=>{let i=!1,a=()=>{i||(i=!0,o())};e.on("exit",a),e.on("error",a),setTimeout(()=>{if(!i){try{e.kill("SIGKILL")}catch{}setTimeout(a,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,threadId:t.threadId,message:t.error,provider:t.provider,model:t.model},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 fo,readFile as ho,writeFile as mo}from"fs/promises";import{dirname as go,join as vo}from"path";var yo={version:1,threads:{}},Qe=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=vo(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await ho(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={...yo,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 o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>e.has(a)))return o;return null}async createThread(t,n){let e=await this.load(),o={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=o,await this.persist(),o}async appendMessage(t,n){let o=(await this.load()).threads[t];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let o=(await this.load()).threads[t];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((o,i)=>i.updatedAt-o.updatedAt),e.slice(0,t).map(o=>{let a=o.messages.find(c=>c.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(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 fo(go(this.filePath),{recursive:!0}),await mo(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var Ze="0.7.
|
|
331
|
+
`));return Ve([...Ye,...h])}function qe(s,t,n=5e3){return new Promise((e,o)=>{eo(s,t,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}e(a)})})}async function vn(s){return no(s,"utf-8")}async function co(s){let t=[me(s,"projects"),me(s,"telemetry")],n=[];for(let e of t)await yn(e,n,4);return n.sort((e,o)=>o.mtimeMs-e.mtimeMs).slice(0,80).map(e=>e.path)}async function yn(s,t,n){if(n<0)return;let e;try{e=await to(s,{withFileTypes:!0})}catch{return}await Promise.all(e.map(async o=>{let i=me(s,o.name);if(o.isDirectory()){await yn(i,t,n-1);return}if(!(!o.isFile()||!lo(o.name)))try{let a=await so(i);if(a.size>2e6)return;t.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function lo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function Ve(s){let t=new Set,n=[];for(let e of s)t.has(e.id)||(t.add(e.id),n.push(e));return n}function uo(s){return[...new Set(s)]}function po(s){return s.charAt(0).toUpperCase()+s.slice(1)}var Ke=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 o=this.bufferEvent(n,t);for(let i of this.listeners)i(o,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let o={...n,seq:e.nextSeq++};return e.events.push(o),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),o}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),o=this.accumulators.get(t)??{response:"",thinking:""},i=this.activeJobs.has(t);if(!e)return null;let a=n<0?e.events:e.events.filter(c=>c.seq>n);return{jobId:t,events:a,currentSeq:e.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(t,n,e){let o=this.accumulators.get(t);o||(o={response:"",thinking:""},this.accumulators.set(t,o)),o[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,threadId:e.threadId,message:"Cancelled by user",cancelled:!0,provider:e.provider,model:e.model},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(o=>{let i=!1,a=()=>{i||(i=!0,o())};e.on("exit",a),e.on("error",a),setTimeout(()=>{if(!i){try{e.kill("SIGKILL")}catch{}setTimeout(a,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,threadId:t.threadId,message:t.error,provider:t.provider,model:t.model},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 fo,readFile as ho,writeFile as mo}from"fs/promises";import{dirname as go,join as vo}from"path";var yo={version:1,threads:{}},Qe=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=vo(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await ho(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={...yo,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 o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>e.has(a)))return o;return null}async createThread(t,n){let e=await this.load(),o={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=o,await this.persist(),o}async appendMessage(t,n){let o=(await this.load()).threads[t];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let o=(await this.load()).threads[t];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((o,i)=>i.updatedAt-o.updatedAt),e.slice(0,t).map(o=>{let a=o.messages.find(c=>c.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(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 fo(go(this.filePath),{recursive:!0}),await mo(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var Ze="0.7.4";var To=1111,Io=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Mo=1800*1e3,Co=3600*1e3;function kn(s){if(!s)return!1;try{let t=new URL(s);return t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="::1"||t.hostname==="[::1]"}catch{return!1}}function $o(s){let t=[];for(let n of s)if(n.type==="delta"){let e=n.text;if(!e)continue;let o=t[t.length-1];o&&o.kind==="text"?o.text+=e:t.push({kind:"text",text:e})}else if(n.type==="tool_use"){let e=n.tool||"",o=n.file??void 0,i=n.content??void 0,a=o?o.split("/").pop()??o:void 0,c;switch(e){case"Read":c=a?`Reading ${a}`:"Reading file";break;case"Edit":c=a?`Editing ${a}`:"Editing file";break;case"Write":c=a?`Writing ${a}`:"Writing file";break;case"Bash":c=i?i.split(`
|
|
332
332
|
`)[0].trim().slice(0,60):"Running command";break;case"Glob":c="Searching files";break;case"Grep":c="Searching code";break;case"WebFetch":c="Fetching page";break;case"WebSearch":c="Searching web";break;default:c=e?`Using ${e}`:"tool";break}let h=o??i??void 0,k=t[t.length-1];k&&k.kind==="tool_group"&&k.tool===e?k.items.push({label:c,detail:h}):t.push({kind:"tool_group",tool:e,items:[{label:c,detail:h}]})}return t}function Oo(s,t){let n=s.headers.origin;kn(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, X-Popmelt-Project-Id"))}function y(s,t,n){s.writeHead(t,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}function _o(s,t){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||t.searchParams.get("projectId")||null}function Ao(s,t){if(!s)return t;let n=s.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return t;let[,e,o,i]=n;return`\x1B[38;2;${parseInt(e,16)};${parseInt(o,16)};${parseInt(i,16)}m${t}\x1B[0m`}function yt(s,t){try{s.res.write(`event: ${t.type}
|
|
333
333
|
data: ${JSON.stringify(t)}
|
|
334
334
|
|
package/package.json
CHANGED